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    
021    package org.granite.gravity.generic;
022    
023    import java.io.IOException;
024    
025    import javax.servlet.ServletConfig;
026    import javax.servlet.ServletException;
027    import javax.servlet.http.HttpServletRequest;
028    import javax.servlet.http.HttpServletResponse;
029    
030    import org.granite.gravity.AbstractGravityServlet;
031    import org.granite.gravity.AsyncHttpContext;
032    import org.granite.gravity.Gravity;
033    import org.granite.gravity.GravityManager;
034    import org.granite.logging.Logger;
035    
036    import flex.messaging.messages.AsyncMessage;
037    import flex.messaging.messages.Message;
038    
039    /**
040     * @author William DRAI
041     */
042    public class GravityGenericServlet extends AbstractGravityServlet {
043    
044        private static final long serialVersionUID = 1L;
045    
046        private static final Logger log = Logger.getLogger(GravityGenericServlet.class);
047    
048        @Override
049        public void init(ServletConfig config) throws ServletException {
050            super.init(config, new GenericChannelFactory());
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                    Gravity gravity = GravityManager.getGravity(getServletContext());
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 (new received messages or timeout).
067                            if (connect != null) {
068                                    try {
069                                            String channelId = (String)connect.getClientId();
070                                            GenericChannel channel = (GenericChannel)gravity.getChannel(channelId);
071                                            // Reset channel continuation instance and deliver pending messages.
072                                            synchronized (channel) {
073                                                    channel.reset();
074                                                    channel.runReceived(new AsyncHttpContext(request, response, connect));
075                                            }
076                                    }
077                                    finally {
078                                            removeConnectMessage(request);
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 for connect request from tunnel).
095                    Message amf3Response = gravity.handleMessage(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                            GenericChannel channel = (GenericChannel)gravity.getChannel(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                            // No pending messages, wait for new ones or timeout.
114                                setConnectMessage(request, amf3Request);
115                                    synchronized (channel) {
116                                            WaitingContinuation continuation = new WaitingContinuation(channel);
117                                            channel.setContinuation(continuation);
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 (IOException e) {
135                log.error(e, "Gravity message error");
136                throw e;
137            }
138            catch (ClassNotFoundException e) {
139                log.error(e, "Gravity message error");
140                throw new ServletException("Gravity message error", e);
141            }
142                    finally {
143                            // Cleanup context (thread local GraniteContext, etc.)
144                            cleanupRequest(request);
145                    }
146    
147            removeConnectMessage(request);
148        }
149    }