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