Package org.atmosphere.cpr

Examples of org.atmosphere.cpr.Action


        }
       
        framework.setAsyncSupport(new NettyCometSupport(framework.getAtmosphereConfig()) {
            @Override
            public Action suspended(AtmosphereRequest request, AtmosphereResponse response) throws IOException, ServletException {
                Action a = super.suspended(request, response);
                if (framework.getAtmosphereConfig().isSupportSession()) {
                    AtmosphereResource r = request.resource();
                    HttpSession s = request.getSession(true);
                    if (s != null) {
                        sessions.put(r.uuid(), request.getSession(true));
View Full Code Here


    private void handleHttp(final ChannelHandlerContext ctx, final MessageEvent messageEvent) throws URISyntaxException, IOException {

        boolean skipClose = false;
        AtmosphereResponse response = null;
        AtmosphereRequest request = null;
        Action a = null;
        boolean resumeOnBroadcast = false;
        boolean keptOpen = false;
        ChannelWriter asyncWriter = null;
        String method = "GET";
        boolean writeHeader = false;
        boolean forceSuspend = false;
        boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory();

        try {
            if (messageEvent.getMessage() instanceof HttpRequest) {
                final HttpRequest hrequest = (HttpRequest) messageEvent.getMessage();
                boolean ka = HttpHeaders.isKeepAlive(hrequest);
                asyncWriter = config.supportChunking() ?
                        new ChunkedWriter(ctx.getChannel(), true, ka, channelBufferPool) :
                        new StreamWriter(ctx.getChannel(), true, ka);

                method = hrequest.getMethod().getName();

                // First let's try to see if it's a static resources
                if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) {
                    try {
                        hrequest.headers().add(STATIC_MAPPING, "true");
                        super.messageReceived(ctx, messageEvent);

                        if (HttpHeaders.getHeader(hrequest, SERVICED) != null) {
                            return;
                        }
                    } catch (Exception e) {
                        logger.debug("Unexpected State", e);
                    } finally {
                        hrequest.headers().set(STATIC_MAPPING, "false");
                    }
                }

                request = createAtmosphereRequest(ctx, hrequest);
                request.setAttribute(KEEP_ALIVE, new Boolean(ka));

                // Hacky. Is the POST doesn't contains a body, we must not close the connection yet.
                AtmosphereRequest.Body b = request.body();
                if (!aggregateBodyInMemory
                        && !hrequest.getMethod().equals(GET)
                        && !b.isEmpty()
                        && (b.hasString() && b.asString().isEmpty())
                        || (b.hasBytes() && b.asBytes().length == 0)) {
                    forceSuspend = true;
                }
            } else {
                request = State.class.cast(ctx.getAttachment()).request;
                boolean isLast = HttpChunk.class.cast(messageEvent.getMessage()).isLast();
                Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE);

                asyncWriter = config.supportChunking() ?
                        new ChunkedWriter(ctx.getChannel(), isLast, ka, channelBufferPool) :
                        new StreamWriter(ctx.getChannel(), isLast, ka);
                method = request.getMethod();
                ChannelBuffer internalBuffer = HttpChunk.class.cast(messageEvent.getMessage()).getContent();

                if (!aggregateBodyInMemory && internalBuffer.hasArray()) {
                    request.body(internalBuffer.array());
                } else {
                    logger.trace("Unable to read in memory the request's bytes. Using stream");
                    request.body(new ChannelBufferInputStream(internalBuffer));
                }

                if (!isLast) {
                    forceSuspend = true;
                }
            }

            response = new AtmosphereResponse.Builder()
                    .asyncIOWriter(asyncWriter)
                    .writeHeader(writeHeader)
                    .destroyable(false)
                    .header("Connection", "Keep-Alive")
                    .header("Server", "Nettosphere/2.0")
                    .request(request).build();

            if (config.supportChunking()) {
                response.setHeader("Transfer-Encoding", "chunked");
            }

            a = framework.doCometSupport(request, response);
            if (forceSuspend) {
                a.type(Action.TYPE.SUSPEND);
                // leave the stream open
                keptOpen = true;
            }

            String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE);
            if (transport == null) {
                transport = request.getHeader(X_ATMOSPHERE_TRANSPORT);
            }

            if (a.type() == Action.TYPE.SUSPEND) {
                if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT)
                        || transport.equalsIgnoreCase(SSE_TRANSPORT))) {
                    keptOpen = true;
                } else if (transport != null && (
                        transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT) ||
                                transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) {
                    resumeOnBroadcast = true;
                }
            }

            final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND);
            final State state = new State(request, action == null ? Action.CONTINUE : action);
            ctx.setAttachment(state);

            if (action != null && action.type() == Action.TYPE.SUSPEND) {
                if (action.timeout() != -1) {
                    final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter);
                    final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>();
                    f.set(suspendTimer.scheduleAtFixedRate(new Runnable() {
                        @Override
                        public void run() {
                            if (!w.get().isClosed() && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) {
                                AtmosphereResourceImpl impl = state.resource();
                                if (impl != null) {
                                    asynchronousProcessor.endRequest(impl, false);
                                    f.get().cancel(true);
                                }
                            }
                        }
                    }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
                }
            } else if (action != null && action.type() == Action.TYPE.RESUME) {
                resumeOnBroadcast = false;
            }
        } catch (AtmosphereMappingException ex) {
            if (method.equalsIgnoreCase("GET")) {
                logger.trace("Unable to map the request {}, trying static file", messageEvent.getMessage());
View Full Code Here

    /**
     * {@inheritDoc}
     */
    public Action service(AtmosphereRequest req, AtmosphereResponse res)
            throws IOException, ServletException {
        Action action = suspended(req, res);
        if (action.type() == Action.TYPE.SUSPEND) {
            logger.debug("Suspending response: {}", res);
        } else if (action.type() == Action.TYPE.RESUME) {
            logger.debug("Resuming response: {}", res);

            Action nextAction = resumed(req, res);
            if (nextAction.type() == Action.TYPE.SUSPEND) {
                logger.debug("Suspending after resuming response: {}", res);
            }
        }
        return action;
    }
View Full Code Here

                session = sessionFactory.getSession(sessionId);
            }
        }

        boolean isDisconnectRequest = isDisconnectRequest(request);
        Action action = Action.CONTINUE;
        if (session != null) {
            SocketIOSessionOutbound handler = session.getTransportHandler();
            if (handler != null) {
                if (!isDisconnectRequest) {
                    action = handler.handle(request, response, session);
View Full Code Here

     * {@inheritDoc}
     */
    @Override
    public Action service(AtmosphereRequest req, AtmosphereResponse res)
            throws IOException, ServletException {
        Action action = JettyWebSocketUtil.doService(this, req, res, webSocketFactory);
        return action == null ? super.service(req, res) : action;
    }
View Full Code Here

     * @throws javax.servlet.ServletException
     */
    protected boolean doRequest(RequestResponseKey rrk) throws IOException, ServletException {
        try {
            rrk.getRequest().getSession().setAttribute(WebLogicCometSupport.RRK, rrk);
            Action action = framework.doCometSupport(AtmosphereRequest.wrap(rrk.getRequest()), AtmosphereResponse.wrap(rrk.getResponse()));
            if (action.type() == Action.TYPE.SUSPEND) {
                if (action.timeout() == -1) {
                    rrk.setTimeout(Integer.MAX_VALUE);
                } else {
                    rrk.setTimeout((int) action.timeout());
                }
            }
            return action.type() == Action.TYPE.SUSPEND;
        } catch (IllegalStateException ex) {
            logger.error("AtmosphereServlet.doRequest exception", ex);
            throw ex;
        }
    }
View Full Code Here

                            response.request(ar);
                            attachWriter(r);
                            ssRequest.set(req);
                            request.setAttribute("swaggerSocketRequest", req);

                            Action action = framework.doCometSupport(ar, response);
                            if (action.type() == Action.TYPE.SUSPEND) {
                                ar.destroyable(false);
                                response.destroyable(false);
                            }
                        } catch (ServletException e) {
                            logger.warn("", e);
View Full Code Here

                    return delegate.doService(req, res);
                }

                if (!headerContainsToken(req, "sec-websocket-version", "13")) {
                    WebSocket.notSupported(req, res);
                    return new Action(Action.TYPE.CANCELLED);
                }
            }

            key = req.getHeader("Sec-WebSocket-Key");
            if (key == null) {
                return delegate.doService(req, res);
            }

            String requireSameOrigin = config.getInitParameter(ApplicationConfig.WEBSOCKET_REQUIRE_SAME_ORIGIN);

            if (!webSocketProcessor.handshake(req)) {
                res.sendError(HttpServletResponse.SC_FORBIDDEN, "WebSocket requests rejected.");
                return new Action(Action.TYPE.CANCELLED);
            }

            if (Boolean.valueOf(requireSameOrigin) && !verifyOrigin(req)) {
                res.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin header does not match expected value");
                return new Action(Action.TYPE.CANCELLED);
            }

            // If we got this far, all is good. Accept the connection.
            res.setHeader("Upgrade", "websocket");
            res.setHeader("Connection", "upgrade");
            res.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key));

            if (subProtocol != null) {
                res.setHeader("Sec-WebSocket-Protocol", subProtocol);
            }

            HttpServletRequest hsr = req.wrappedRequest();
            while (hsr instanceof HttpServletRequestWrapper)
                hsr = (HttpServletRequest) ((HttpServletRequestWrapper) hsr).getRequest();

            RequestFacade facade = (RequestFacade) hsr;
            boolean isDestroyable = false;
            s = config.getInitParameter(ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE);
            if (s != null && Boolean.valueOf(s)) {
                isDestroyable = true;
            }
            StreamInbound inbound = new TomcatWebSocketHandler(AtmosphereRequest.cloneRequest(req, true, useBuildInSession, isDestroyable),
                    config.framework(), webSocketProcessor);
            facade.doUpgrade(inbound);
            return new Action(Action.TYPE.CREATED);
        }

        try {
            Action action = delegate.suspended(req, res);
            if (action.type() == Action.TYPE.RESUME) {
                req.setAttribute(WebSocket.WEBSOCKET_RESUME, true);
            }
            return action;
        } catch (Exception ex) {
            logger.error("", ex);
View Full Code Here

                return doService(req, res);
            }

            if (!headerContainsToken(req, "sec-websocket-version", "13")) {
                WebSocket.notSupported(req, res);
                return new Action(Action.TYPE.CANCELLED);
            }
        }     
     
        try {
            Action action = suspended(req, res);
            if (action.type() == Action.TYPE.RESUME) {
                req.setAttribute(WebSocket.WEBSOCKET_RESUME, true);
            }
            return action;
        } catch (Exception ex) {
            logger.error("", ex);
View Full Code Here

     */
    @Override
    public Action service(AtmosphereRequest req, AtmosphereResponse res)
            throws IOException, ServletException {
        CometContext ctx = CometEngine.getEngine().getCometContext(atmosphereCtx);
        Action action = suspended(req, res);
        if (action.type() == Action.TYPE.SUSPEND) {
            suspend(ctx, action, req, res);
        } else if (action.type() == Action.TYPE.RESUME) {
            resume(req, ctx);
        }
        return action;
    }
View Full Code Here

TOP

Related Classes of org.atmosphere.cpr.Action

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.