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.standalone.MimeType;
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 com.sun.grizzly.util.buf.ByteChunk;
import java.io.File;
import java.io.FileInputStream;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyException;
import org.jruby.RubyIO;
import org.jruby.RubyHash;
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.Map;
import java.util.HashMap;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import org.jruby.RubyThread;
/**
* Adapter implementation that bridge JRuby on Rails with Grizzly.
*
* @author TAKAI Naoto
* @author Jean-Francois Arcand
* @author Pramod Gopinath
* @author Vivek Pandey
* @author Peter Williams
*/
public class RailsAdapter extends GrizzlyAdapter {
private final RubyObjectPool pool;
private RubyRuntimeAsyncFilter asyncFilter;
private final String contextRoot;
private final Map environment = new HashMap();
protected File webDir = null;
private ReentrantLock initializedLock = new ReentrantLock();
protected ConcurrentHashMap cache = new ConcurrentHashMap();
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);
}
//Looks like Rails ENV hash keeps state of previous request.
//we reset it a fresh with the initial value or else every request is going to be the same.
RubyHash env = (RubyHash) runtime.getObject().getConstant("ENV");
if(environment.size() == 0){
environment.putAll(env);
}else{
env.clear();
env.putAll(environment);
}
}
/**
* 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) {
// Commit the response so Grizzly doesn't add its own headers.
res.getResponse().setCommitted(true);
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 final Map> threadMaps =
new HashMap>();
private RubyThread getContextThread(Ruby runtime) {
RubyThread contextThread = null;
synchronized (threadMaps) {
WeakHashMap threadMap = threadMaps.get(runtime);
if(threadMap != null) {
contextThread = threadMap.get(Thread.currentThread());
} else {
threadMap = new WeakHashMap();
threadMaps.put(runtime, threadMap);
}
if(contextThread == null) {
contextThread = RubyThread.adopt(runtime.getThread(), Thread.currentThread());
threadMap.put(Thread.currentThread(), contextThread);
}
}
return contextThread;
}
private void dispatchRailsRequest(Ruby runtime, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
// RubyThread oldContext = runtime.getThreadService().getMainThread();
try {
//RubyThread context = getContextThread(runtime);
//runtime.getThreadService().setMainThread(context);
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;
}
// finally {
// runtime.getThreadService().setMainThread(oldContext);
// }
}
// public void afterService(GrizzlyRequest request, GrizzlyResponse response) throws Exception {
// request.getRequest().recycle();
// }
@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);
FileInputStream fis = null;
try{
if (webDir == null){
initializedLock.lock();
try{
webDir = new File(getRootFolder());
try {
setRootFolder(webDir.getCanonicalPath());
} catch (IOException e) {
logger.log(Level.WARNING,"service()",e);
}
} finally {
initializedLock.unlock();
}
}
// local file
File resource = cache.get(uri);
if (resource == null){
resource = new File(webDir, uri);
cache.put(uri,resource);
}
if (resource.isDirectory()) {
resource = new File(resource, "index.html");
cache.put(uri,resource);
}
if (!resource.exists()) {
if (getLogger().isLoggable(Level.FINE)){
getLogger().log(Level.FINE,"File not found " + resource);
}
res.setStatus(404);
customizedErrorPage(req,res);
return;
}
res.setStatus(200);
int dot=uri.lastIndexOf(".");
if( dot > 0 ) {
String ext=uri.substring(dot+1);
String ct= MimeType.get(ext);
if( ct!=null) {
res.setContentType(ct);
}
} else {
res.setContentType(MimeType.get("html"));
}
res.setContentLength((int)resource.length());
res.sendHeaders();
/* Workaround Linux NIO bug
* 6427312: (fc) FileChannel.transferTo() throws IOException "system call interrupted"
* 5103988: (fc) FileChannel.transferTo should return -1 for EAGAIN instead throws IOException
* 6253145: (fc) FileChannel.transferTo on Linux fails when going beyond 2GB boundary
* 6470086: (fc) FileChannel.transferTo(2147483647, 1, channel) cause "Value too large" exception
*/
fis = new FileInputStream(resource);
byte b[] = new byte[8192];
ByteChunk chunk = new ByteChunk();
int rd = 0;
while ((rd = fis.read(b)) > 0) {
chunk.setBytes(b, 0, rd);
res.doWrite(chunk);
}
} finally {
if (fis != null){
try{
fis.close();
} catch (IOException ex){}
}
}
res.setCommitted(true);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy