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

org.atmosphere.cpr.AsynchronousProcessor Maven / Gradle / Ivy

There is a newer version: 3.0.13
Show newest version
/*
 * 
 * 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 org.atmosphere.cpr;

import org.atmosphere.cpr.AtmosphereServlet.Action;
import org.atmosphere.cpr.AtmosphereServlet.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereServlet.AtmosphereHandlerWrapper;
import org.atmosphere.handler.ReflectorServletProcessor;
import org.atmosphere.util.BroadcasterLookup;
import org.atmosphere.util.LoggerUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Base class which implement the semantics of supending and resuming of a 
 * Comet Request.
 * 
 * @author Jeanfrancois Arcand
 */
abstract public class AsynchronousProcessor implements CometSupport {

    private final static Action timedoutAction = new AtmosphereServlet.Action();
    private final static Action cancelledAction = new AtmosphereServlet.Action();

    protected final Logger logger = LoggerUtils.getLogger();
    
    protected final static String RESOURCE_EVENT = "org.atmosphere.cpr.AtmosphereResourceImpl";

    public final static String SUPPORT_SESSION = "org.atmosphere.cpr.AsynchronousProcessor.supportSession";

    private final AtmosphereConfig config;

    protected final ConcurrentHashMap
            aliveRequests = new ConcurrentHashMap();

    public AsynchronousProcessor(AtmosphereConfig config){
        this.config = config;
    }

    public void init(ServletConfig sc) throws ServletException{
    }

    /**
     * Is {@link HttpSession} supported
     * @return true if supported
     */
    protected boolean supportSession(){
        return config.supportSession;
    }

    /**
     * Return the container's name.
     */
    public String getContainerName() {
        return config.getServletConfig().getServletContext().getServerInfo();
    }
    
    /**
     * All proprietary Comet based {@link Servlet} must invoke the suspended
     * method when the first request comes in. The returned value, of type
     * {@link AtmosphereServlet.Action}, tells the proprietary Comet {@link Servlet}
     * to suspended or not the current {@link HttpServletResponse}.
     * 
     * @param req the {@link HttpServletRequest}
     * @param res the {@link HttpServletResponse}
     * @return action the Action operation.
     */
    public Action suspended(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException{     
        if (logger.isLoggable(Level.FINE)){
            logger.fine("(suspend) invoked:\n HttpServletRequest: " + req 
                    + "\n HttpServletResponse: " + res);
        }
        return action(req, res);
    }


    /**
     * Invoke the {@link AtmosphereHandler#onRequest} method.
     * @param req the {@link HttpServletRequest}
     * @param res the {@link HttpServletResponse}
     * @return action the Action operation.
     */
    Action action(HttpServletRequest req, HttpServletResponse res)
               throws IOException,ServletException{

        if (supportSession()){
            // Create the session needed to support the Resume
            // operation from disparate requests.
            HttpSession session = req.getSession(true);
            // Do not allow times out.
            session.setMaxInactiveInterval(-1);
        }

        req.setAttribute(SUPPORT_SESSION, supportSession());

        AtmosphereHandlerWrapper g = map(req);
        AtmosphereResourceImpl re = new AtmosphereResourceImpl(config,
                    g.broadcaster,req, res,this);
        g.atmosphereHandler.onRequest(re);
        
        if (re.event().isSuspended()){
            aliveRequests.put(req, re);
        }
        return re.action();
    }

    /**
     * {@inheritDoc}
     */
    public void action(AtmosphereResourceImpl actionEvent)  {
        aliveRequests.remove(actionEvent.getRequest());
    }

    /**
     * Return the {@link AtmosphereHandler} mapped to the passed servlet-path.
     *
     * @param req the {@link HttpServletResponse}
     * @return the {@link AtmosphereHandler} mapped to the passed servlet-path.
     */
    AtmosphereHandlerWrapper map(HttpServletRequest req) throws ServletException{
        String path = req.getServletPath();
        if (path == null || path.equals("")){
            path = "/";
        }
        
        AtmosphereHandlerWrapper g = config.handlers().get(path);
        if (g == null){
            // Try the /*
            if (!path.endsWith("/")){
                path += "/*";
            } else {
                path += "*";
            }
            g = config.handlers().get(path);
            if (g == null){
                g = config.handlers().get("/*");               
                if (g == null){
                    // Try appending the pathInfo
                    path = req.getServletPath() + req.getPathInfo();
                    g = config.handlers().get(path); 
                    if (g == null) {
                        // Last chance
                        if (!path.endsWith("/")){
                            path += "/*";
                        } else {
                            path += "*";
                        }
                        // Try appending the pathInfo
                        g = config.handlers().get(path);
                        if (g == null){
                            logger.warning("No AtmosphereHandler maps request for " + path);
                            for (String m: config.handlers().keySet()){
                                logger.warning("\tAtmosphereHandler registered: " + m);
                            }
                            throw new ServletException("No AtmosphereHandler maps request for " + path);
                        }
                    }
                }
            }
        }
        config.ah = g.atmosphereHandler;
        BroadcasterLookup.add(g.broadcaster,g.broadcaster.getID());
        return g;
    }
    
    /**
     * All proprietary Comet based {@link Servlet} must invoke the resume
     * method when the Atmosphere's application decide to resume the {@link HttpServletResponse}.
     * The returned value, of type
     * {@link AtmosphereServlet.Action}, tells the proprietary Comet {@link Servlet}
     * to resume (again), suspended or do nothing with the current {@link HttpServletResponse}.
     *
     * @param req the {@link HttpServletRequest}
     * @param res the {@link HttpServletResponse}
     * @return action the Action operation.
    */
    public Action resumed(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException{
        if (logger.isLoggable(Level.FINE)){
            logger.fine("(resumed) invoked:\n HttpServletRequest: " + req 
                    + "\n HttpServletResponse: " + res);
        }   
        return action(req, res);
    }
    
    /**
     * All proprietary Comet based {@link Servlet} must invoke the timedout
     * method when the underlying WebServer time out the {@link HttpServletResponse}.
     * The returned value, of type
     * {@link AtmosphereServlet.Action}, tells the proprietary Comet {@link Servlet}
     * to resume (again), suspended or do nothing with the current {@link HttpServletResponse}.
     *
     * @param req the {@link HttpServletRequest}
     * @param res the {@link HttpServletResponse}
     * @return action the Action operation.
     */
    public Action timedout(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException{

        AtmosphereResourceImpl re = null;
        // Something went wrong.
        if (req == null || res == null) {
            logger.warning("Invalid Request/Response: " + req + "/" +res);
            return timedoutAction;
        }

        // TODO: We could instead store the AtmosphereHandlerWrapper as a request attributes.
        AtmosphereHandlerWrapper aw = map(req);
        re = (AtmosphereResourceImpl) aliveRequests.remove(req);

        if (re != null){
            re.event().isResumedOnTimeout = true;
            if (re.getRequest().getAttribute(AtmosphereResourceImpl.RESUMED_ON_TIMEOUT) != null){
                re.event().isResumedOnTimeout = (Boolean) re.getRequest().getAttribute(AtmosphereResourceImpl.RESUMED_ON_TIMEOUT);
            }
            re.notifyListeners();
            re.getBroadcaster().removeAtmosphereResource(re);

            if (!re.getResponse().equals(res)){
                logger.warning("Invalid response: " + res);
            } else if (!re.getAtmosphereConfig().getInitParameter(AtmosphereServlet.DISABLE_ONSTATE_EVENT)
                        .equals(String.valueOf(true))){
                aw.atmosphereHandler.onStateChange(re.event());
            }
        }

        return timedoutAction;
    }

    /**
     * All proprietary Comet based {@link Servlet} must invoke the cancelled
     * method when the underlying WebServer detect that the client closed
     * the connection.
     *
     * @param req the {@link HttpServletRequest}
     * @param res the {@link HttpServletResponse}
     * @return action the Action operation.
     */
    public Action cancelled(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException{

        AtmosphereResourceImpl re = null;
        try{
            AtmosphereHandlerWrapper aw = map(req);
            re = (AtmosphereResourceImpl) aliveRequests.remove(req);

            if (re != null){
                re.event().setCancelled(true);
                re.getBroadcaster().removeAtmosphereResource(re);

                if (!re.getResponse().equals(res)){
                    logger.warning("Invalid response: " + res);
                } else if (!re.getAtmosphereConfig().getInitParameter(AtmosphereServlet.DISABLE_ONSTATE_EVENT)
                        .equals(String.valueOf(true))){
                    aw.atmosphereHandler.onStateChange(re.event());
                }
                re.notifyListeners();
            }
        } catch (Throwable ex){
            // Something wrong happenned, ignore the exception
            if (logger.isLoggable(Level.FINE)){
                logger.log(Level.FINE,"",ex);
            }
        } finally{
            if (re != null){
                re.isInScope(false);
            }
        }
        
        return cancelledAction;
    }

    void shutdown(){
        for (AtmosphereResource r: aliveRequests.values()){
            try{
                r.resume();
            } catch (Throwable t){
                
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy