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     */
022    package org.granite.gravity.jetty8;
023    
024    import java.io.IOException;
025    
026    import javax.servlet.ServletException;
027    import javax.servlet.http.HttpServletRequest;
028    import javax.servlet.http.HttpServletResponse;
029    
030    import org.eclipse.jetty.continuation.Continuation;
031    import org.eclipse.jetty.continuation.ContinuationSupport;
032    import org.eclipse.jetty.continuation.ContinuationThrowable;
033    import org.granite.gravity.AbstractGravityServlet;
034    import org.granite.gravity.AsyncHttpContext;
035    import org.granite.gravity.Gravity;
036    import org.granite.gravity.GravityManager;
037    import org.granite.gravity.GravityServletUtil;
038    import org.granite.logging.Logger;
039    
040    import flex.messaging.messages.AsyncMessage;
041    import flex.messaging.messages.Message;
042    
043    /**
044     * @author William DRAI
045     */
046    public class GravityJettyServlet extends AbstractGravityServlet {
047    
048        private static final long serialVersionUID = 1L;
049    
050        private static final Logger log = Logger.getLogger(GravityJettyServlet.class);
051    
052    
053        @Override
054        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
055            
056            log.debug("doPost: from %s:%d", request.getRemoteAddr(), request.getRemotePort());
057    
058            rejectJMFContentType(request);
059    
060            Gravity gravity = GravityManager.getGravity(getServletContext());
061                    ContinuationChannelFactory channelFactory = new ContinuationChannelFactory(gravity);
062                    
063                    try {
064                            // Setup context (thread local GraniteContext, etc.)
065                            initializeRequest(gravity, request, response);
066                            
067                            AsyncMessage connect = getConnectMessage(request);
068                            
069                            // Resumed request (pending messages or timeout).
070                            if (connect != null) {
071                                    String channelId = (String)connect.getClientId();
072                                    ContinuationChannel channel = gravity.getChannel(channelFactory, channelId);
073    
074                                    // Reset channel continuation instance and deliver pending messages.
075                                    synchronized (channel) {
076                                            channel.close();
077                                            channel.runReceived(new AsyncHttpContext(request, response, connect));
078                                    }
079                                    
080                                    return;
081                            }
082                            
083                            // New Request.
084                            Message[] amf3Requests = deserialize(gravity, request);
085    
086                log.debug(">> [AMF3 REQUESTS] %s", (Object)amf3Requests);
087    
088                Message[] amf3Responses = null;
089                
090                boolean accessed = false;
091                for (int i = 0; i < amf3Requests.length; i++) {
092                    Message amf3Request = amf3Requests[i];
093                    
094                    // Ask gravity to create a specific response (will be null with a connect request from tunnel).
095                    Message amf3Response = gravity.handleMessage(channelFactory, amf3Request);
096                    String channelId = (String)amf3Request.getClientId();
097                    
098                    // Mark current channel (if any) as accessed.
099                    if (!accessed)
100                            accessed = gravity.access(channelId);
101                    
102                    // (Re)Connect message from tunnel.
103                    if (amf3Response == null) {
104                        if (amf3Requests.length > 1)
105                            throw new IllegalArgumentException("Only one request is allowed on tunnel.");
106    
107                            ContinuationChannel channel = gravity.getChannel(channelFactory, channelId);
108                            if (channel == null)
109                                    throw new NullPointerException("No channel on tunnel connect");
110                            
111                        // Try to send pending messages if any (using current container thread).
112                            if (!channel.runReceived(new AsyncHttpContext(request, response, amf3Request))) {
113                            
114                                    // No pending messages, wait for new ones or timeout.
115                                    synchronized (channel) {
116                                            Continuation continuation = ContinuationSupport.getContinuation(request);
117                                            continuation.setTimeout(getLongPollingTimeout());
118                                            continuation.setAttribute(GravityServletUtil.CONNECT_MESSAGE_KEY, amf3Request);
119                                            channel.setContinuation(continuation);
120                                            
121                                            // Suspend the current resquest/response processing and free the thread
122                                            continuation.suspend(response);
123                                    }
124                            }
125                            
126                            return;
127                    }
128    
129                    if (amf3Responses == null)
130                            amf3Responses = new Message[amf3Requests.length];
131                    amf3Responses[i] = amf3Response;
132                }
133    
134                log.debug("<< [AMF3 RESPONSES] %s", (Object)amf3Responses);
135    
136                serialize(gravity, response, amf3Responses);
137                    }
138            catch (ContinuationThrowable e) {
139                throw e;
140            }
141            catch (IOException e) {
142                log.error(e, "Gravity message error");
143                throw e;
144            }
145            catch (Exception e) {
146                log.error(e, "Gravity message error");
147                throw new ServletException(e);
148            }
149                    finally {
150                            // Cleanup context (thread local GraniteContext, etc.)
151                            cleanupRequest(request);
152                    }
153        }
154    }