001/**
002 *   GRANITE DATA SERVICES
003 *   Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 *   This file is part of the Granite Data Services Platform.
006 *
007 *   Granite Data Services is free software; you can redistribute it and/or
008 *   modify it under the terms of the GNU Lesser General Public
009 *   License as published by the Free Software Foundation; either
010 *   version 2.1 of the License, or (at your option) any later version.
011 *
012 *   Granite Data Services is distributed in the hope that it will be useful,
013 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
014 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
015 *   General Public License for more details.
016 *
017 *   You should have received a copy of the GNU Lesser General Public
018 *   License along with this library; if not, write to the Free Software
019 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
020 *   USA, or see <http://www.gnu.org/licenses/>.
021 */
022package org.granite.gravity.jetty;
023
024import java.io.IOException;
025
026import javax.servlet.ServletException;
027import javax.servlet.http.HttpServletRequest;
028import javax.servlet.http.HttpServletResponse;
029
030import org.granite.gravity.AbstractGravityServlet;
031import org.granite.gravity.AsyncHttpContext;
032import org.granite.gravity.Gravity;
033import org.granite.gravity.GravityManager;
034import org.granite.logging.Logger;
035import org.mortbay.jetty.RetryRequest;
036import org.mortbay.util.ajax.Continuation;
037import org.mortbay.util.ajax.ContinuationSupport;
038
039import flex.messaging.messages.AsyncMessage;
040import flex.messaging.messages.Message;
041
042/**
043 * @author William DRAI
044 */
045public class GravityJettyServlet extends AbstractGravityServlet {
046
047    private static final long serialVersionUID = 1L;
048
049    private static final Logger log = Logger.getLogger(GravityJettyServlet.class);
050
051
052    @Override
053    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
054        
055        log.debug("doPost: from %s:%d", request.getRemoteAddr(), request.getRemotePort());
056
057                Gravity gravity = GravityManager.getGravity(getServletContext());
058                ContinuationChannelFactory channelFactory = new ContinuationChannelFactory(gravity);
059                
060                try {
061                        // Setup context (thread local GraniteContext, etc.)
062                        initializeRequest(gravity, request, response);
063                        
064                        AsyncMessage connect = getConnectMessage(request);
065                        
066                        // Resumed request (pending messages or timeout).
067                        if (connect != null) {
068                                String channelId = (String)connect.getClientId();
069                                ContinuationChannel channel = gravity.getChannel(channelFactory, channelId);
070
071                                // Reset channel continuation instance and deliver pending messages.
072                                synchronized (channel) {
073                                        channel.close();
074                                        channel.runReceived(new AsyncHttpContext(request, response, connect));
075                                }
076                                
077                                return;
078                        }
079                        
080                        // New Request.
081                        Message[] amf3Requests = deserialize(gravity, request);
082
083            log.debug(">> [AMF3 REQUESTS] %s", (Object)amf3Requests);
084
085            Message[] amf3Responses = null;
086            
087            boolean accessed = false;
088            for (int i = 0; i < amf3Requests.length; i++) {
089                Message amf3Request = amf3Requests[i];
090                
091                // Ask gravity to create a specific response (will be null with a connect request from tunnel).
092                Message amf3Response = gravity.handleMessage(channelFactory, amf3Request);
093                String channelId = (String)amf3Request.getClientId();
094                
095                // Mark current channel (if any) as accessed.
096                if (!accessed)
097                        accessed = gravity.access(channelId);
098                
099                // (Re)Connect message from tunnel.
100                if (amf3Response == null) {
101                    if (amf3Requests.length > 1)
102                        throw new IllegalArgumentException("Only one request is allowed on tunnel.");
103
104                        ContinuationChannel channel = gravity.getChannel(channelFactory, channelId);
105                        if (channel == null)
106                                throw new NullPointerException("No channel on tunnel connect");
107                        
108                    // Try to send pending messages if any (using current container thread).
109                        if (!channel.runReceived(new AsyncHttpContext(request, response, amf3Request))) {
110                        
111                                // No pending messages, wait for new ones or timeout.
112                            setConnectMessage(request, amf3Request);
113                                synchronized (channel) {
114                                        Continuation continuation = ContinuationSupport.getContinuation(request, channel);
115                                        channel.setContinuation(continuation);
116                                        
117                                        // This call throws a RetryRequest exception, so we'll never reach return below...
118                                        continuation.suspend(getLongPollingTimeout());
119                                }
120                        }
121                        
122                        return;
123                }
124
125                if (amf3Responses == null)
126                        amf3Responses = new Message[amf3Requests.length];
127                amf3Responses[i] = amf3Response;
128            }
129
130            log.debug("<< [AMF3 RESPONSES] %s", (Object)amf3Responses);
131
132            serialize(gravity, response, amf3Responses);
133                }
134        catch (RetryRequest e) {
135            throw e;
136        }
137        catch (IOException e) {
138            log.error(e, "Gravity message error");
139            throw e;
140        }
141        catch (Exception e) {
142            log.error(e, "Gravity message error");
143            throw new ServletException(e);
144        }
145                finally {
146                        // Cleanup context (thread local GraniteContext, etc.)
147                        cleanupRequest(request);
148                }
149    }
150}