com.sun.grizzly.jruby.RailsAdapter Maven / Gradle / Ivy
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package com.sun.grizzly.jruby;
import com.sun.grizzly.http.SelectorThread;
import com.sun.grizzly.tcp.Request;
import com.sun.grizzly.tcp.Response;
import com.sun.grizzly.tcp.http11.GrizzlyAdapter;
import com.sun.grizzly.tcp.http11.GrizzlyRequest;
import com.sun.grizzly.tcp.http11.GrizzlyResponse;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyException;
import org.jruby.RubyIO;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Adapter implementation that bridge JRuby on Rails with Grizzly.
*
* @author TAKAI Naoto
* @author Jean-Francois Arcand
* @author Pramod Gopinath
* @author Vivek Pandey
*/
public class RailsAdapter extends GrizzlyAdapter {
private final RubyObjectPool pool;
private RubyRuntimeAsyncFilter asyncFilter;
private final String contextRoot;
public RailsAdapter(String railsRoot, String jrubyLib, int numRt, boolean asyncExecution, RubyRuntimeAsyncFilter asyncFilter) {
this("/", railsRoot, jrubyLib, numRt, asyncExecution);
this.asyncFilter = asyncFilter;
asyncFilter.setRubyRuntimeQueue(pool.getRubyRuntimeQueue());
}
public RailsAdapter(String contextRoot, String railsRoot, String jrubyLib, int numRt, boolean asyncExecution) {
super(railsRoot);
this.setHandleStaticResources(true);
this.setRootFolder(railsRoot + "/public");
this.contextRoot = contextRoot;
this.pool = new RubyObjectPool(railsRoot, jrubyLib, numRt, asyncExecution);
}
RubyObjectPool getPool() {
return pool;
}
void startRubyRuntimePool() {
try {
SelectorThread.logger().log(Level.INFO, "Starting Rails instances");
pool.start();
} catch (RaiseException e) {
e.printStackTrace();
System.out.println(e.getMessage());
// try to put some helpful information in the logs
RubyException re = e.getException();
String rubyMessage = (String) JavaEmbedUtils.rubyToJava(pool.borrowRuntime(), re.message, String.class);
String message = "Failed to load Rails: " + rubyMessage + "\n";
RubyArray backtrace = (RubyArray) re.backtrace();
for (Object aBacktrace : backtrace) {
String traceLine = (String) aBacktrace;
message += "\t" + traceLine + "\n";
}
getLogger().log(Level.SEVERE, message, e);
throw e;
}
}
void stopRubyRuntimePool() {
pool.stop();
}
/**
* The given Ruby runtime might not be configured with the correct context root for this adapter. Check if the
* $root is set correctly else set it now.
*/
private void loadRuntimeEnvironment(Ruby runtime) {
if (contextRoot != null && !contextRoot.equals("/")) {
String root = runtime.getGlobalVariables().get("$root").asString().asJavaString();
if (root == null || !root.equals(contextRoot)) {
runtime.defineReadonlyVariable("$root",
JavaEmbedUtils.javaToRuby(runtime, contextRoot));
}
}
String logger = runtime.getGlobalVariables().get("$logger").asString().asJavaString();
if (logger == null || logger.length() == 0) {
IRubyObject loggerObj = JavaEmbedUtils.javaToRuby(runtime, new Logger(getLogger()));
runtime.defineReadonlyVariable("$logger", loggerObj);
}
}
/**
* Logger to pass on to Rails Logger
*/
private static class Logger{
private final java.util.logging.Logger logger;
public Logger(java.util.logging.Logger logger) {
this.logger = logger;
}
public void log(String msg){
logger.info(msg);
}
}
public void service(GrizzlyRequest req, GrizzlyResponse res) {
Ruby runtime = null;
try {
runtime = pool.borrowRuntime();
if (runtime == null) {
throw new IllegalStateException(
"No Rails Instances available to satisfy the current request");
}
dispatchRailsRequest(runtime, req, res);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (runtime != null) {
pool.returnRuntime(runtime);
if (asyncFilter != null) {
asyncFilter.resume();
}
}
}
}
private void dispatchRailsRequest(Ruby runtime, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
try {
OutputStream os = res.getOutputStream();
RubyIO iObj = new RubyIO(runtime, req.getInputStream());
runtime.defineReadonlyVariable("$stdin", iObj);
RubyIO oObj = new RubyIO(runtime, os);
runtime.defineReadonlyVariable("$stdout", oObj);
loadRuntimeEnvironment(runtime);
IRubyObject[] args = {JavaEmbedUtils.javaToRuby(runtime, req.getRequest())};
IRubyObject responder = runtime.getGlobalVariables().get("$responder");
JavaEmbedUtils.invokeMethod(runtime, responder, "service", args, IRubyObject.class);
} catch (RaiseException e) {
getLogger().log(Level.SEVERE, e.getLocalizedMessage(), e);
RubyException exception = e.getException();
exception.printBacktrace(System.err);
throw e;
}
}
public void afterService(GrizzlyRequest request, GrizzlyResponse response) throws Exception {
}
@Override
protected void service(String uri, Request req, Response res) throws Exception {
if (contextRoot != null && uri.startsWith(contextRoot)) {
uri = uri.substring(contextRoot.length());
}
super.service(uri, req, res);
res.setCommitted(true);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy