All Downloads are FREE. Search and download functionalities are using the official Maven repository.

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.pool.DynamicPool;
import com.sun.grizzly.pool.DynamicPoolConfig;
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.tcp.http11.InternalOutputBuffer;
import com.sun.grizzly.util.buf.ByteChunk;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyException;
import org.jruby.RubyHash;
import org.jruby.RubyIO;
import org.jruby.RubyThread;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;

/**
 * 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 final DynamicPool pool;
    private RubyRuntimeAsyncFilter asyncFilter;
    private final String contextRoot;
    private final Map environment = new HashMap();
    private File webDir = null;
    private final ReentrantLock initializedLock = new ReentrantLock();

    private ConcurrentHashMap cache = new ConcurrentHashMap();

    private final boolean debugMode;
    public RailsAdapter(String railsRoot, String jrubyLib, int numRt, boolean asyncExecution, RubyRuntimeAsyncFilter asyncFilter) {
        this("/", railsRoot, jrubyLib, numRt, -1, -1, asyncExecution);
        this.asyncFilter = asyncFilter;
        asyncFilter.setRubyRuntimeQueue(pool.getObjectQueue());
    }

    public RailsAdapter(String contextRoot, String railsRoot, String jrubyLib, int numRt, int minRuntime, int maxRuntime, boolean asyncExecution) {
        super(railsRoot);
        this.setHandleStaticResources(true);
        this.setRootFolder(railsRoot + "/public");
        this.contextRoot = contextRoot;
        RubyAdapter myAdapter = new RubyAdapter(railsRoot,jrubyLib);
        DynamicPoolConfig myConfig = new DynamicPoolConfig(numRt, -1,maxRuntime,minRuntime,-1,-1,-1,-1,asyncExecution,false);
        // Using defaults for, in order, maximum generating, upThreshold, downThreshold, queueThreshold, newThreshold
        this.pool = new DynamicPool(myAdapter, myConfig);
        this.debugMode = isDebugMode();
    }

    //This is only so that NB 6.5 beta works with jruby < 1.1.3.
    //FIX ME: remove after
    private boolean isDebugMode() {
        if (org.jruby.runtime.Constants.VERSION != null) {
            logger.log(Level.INFO, "JRuby version is: " + org.jruby.runtime.Constants.VERSION);
            int i = org.jruby.runtime.Constants.VERSION.lastIndexOf('.');
            if (i != -1) {
                char ch = org.jruby.runtime.Constants.VERSION.charAt(i + 1);
                if((org.jruby.runtime.Constants.VERSION.charAt(0) == '1') && ch < '4'){
                    i = org.jruby.runtime.Constants.VERSION.substring(0, i).lastIndexOf('.');
                    if(i != -1){
                        ch = org.jruby.runtime.Constants.VERSION.charAt(i + 1);
                        if(ch == '1'){
                            //it is 1.1.x, where x < 4
                            logger.log(Level.INFO, "Value of last version number" + String.valueOf(ch));
                            return true;
                        }

                    }
                }
            }

        }
        return false;
    }


    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.borrowObject(), 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.
     * @param runtime the runtime to check the context root for
     */
    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);
            logger.fine(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.borrowObject();
            if (runtime == null) {
                throw new IllegalStateException(
                        "No Rails Instances available to satisfy the current request");
            }
            if(debugMode){
                dispatchRailsRequestDebugMode(runtime, req, res);
            }else{
                dispatchRailsRequest(runtime, req, res);
            }
            // More forceful commit to prevent Grizzly from adding its own headers
            try {
                ((InternalOutputBuffer)res.getResponse().getOutputBuffer()).commit();
            } catch (IOException e) {
                res.getResponse().setCommitted(true);
                logger.log(Level.WARNING, "IO Exception trying to commit Grizzly response! Response is committed: " + res.getResponse().isCommitted());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (runtime != null) {
                pool.returnObject(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 dispatchRailsRequestDebugMode(Ruby runtime, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
        RubyThread oldContext = runtime.getThreadService().getMainThread();
        try {
            RubyThread context = getContextThread(runtime);
            runtime.getThreadService().setMainThread(context);
            dispatchRailsRequest(runtime, req, res);
        } finally {
            runtime.getThreadService().setMainThread(oldContext);
        }
    }

    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;
        }
    }

    @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){}
            }
        }
        //Marker
        res.setCommitted(true);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy