Package org.atmosphere.cpr

Examples of org.atmosphere.cpr.AtmosphereRequest$LazyComputation


                    if (!future.isSuccess()) {
                        future.getChannel().close();
                    } else {
                        websocketChannels.add(ctx.getChannel());

                        AtmosphereRequest r = createAtmosphereRequest(ctx, request);
                        WebSocket webSocket = new NettyWebSocket(ctx.getChannel(), framework.getAtmosphereConfig());

                        ctx.setAttachment(webSocket);
                        if (request.headers().contains("X-wakeUpNIO")) {
                            /**
 
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());
                try {
                    skipClose = true;
                    super.messageReceived(ctx, messageEvent);
                } catch (Exception e) {
                    logger.error("Unable to process request", e);
                    throw new IOException(e);
                }
            }
        } catch (Throwable e) {
            logger.error("Unable to process request", e);
            throw new IOException(e);
        } finally {
            try {
                if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) {
                    if (!skipClose && response != null) {
                        asyncWriter.close(response);
                    } else {
                        httpChannels.add(ctx.getChannel());
                    }
                }
            } finally {
                if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) {
                    request.destroy();
                    response.destroy();
                    framework.notify(Action.TYPE.DESTROYED, request, response);
                }
            }
        }
View Full Code Here

    private static final Logger logger = LoggerFactory.getLogger(SSETransport.class);
    @Override
    public void onPreSuspend(AtmosphereResourceEvent event) {
        AtmosphereResponse response = event.getResource().getResponse();
        AtmosphereRequest request = event.getResource().getRequest();

        String callback = request.getParameter("c");
        // TODO: Configurable
        response.setContentType("text/html; charset=UTF-8");
        response.write(IFrameUtils.generateHtmlFile(callback)).write(padding);
        try {
            response.write(("<script>\n" + "p(\"o\")" "\n</script>\n").getBytes()).flushBuffer();
View Full Code Here

        protected abstract void customConnect(AtmosphereRequest request, AtmosphereResponse response) throws IOException;

        public void connect(AtmosphereResourceImpl resource) throws IOException {

            AtmosphereRequest request = resource.getRequest();
            AtmosphereResponse response = resource.getResponse();

            request.setAttribute(SESSION_KEY, session);
            response.setBufferSize(bufferSize);

            customConnect(request, response);
            is_open = true;
            session.onConnect(resource, this);
View Full Code Here

                            SocketIOAtmosphereHandler.class.cast(atmosphereHandler).onMessage(resource, outbound, message);
                        } else {
                            SocketIOProtocol p = mapper.readValue(message, SocketIOProtocol.class);

                            for (String msg : p.getArgs()) {
                                AtmosphereRequest r = resource.getRequest();
                                r.setAttribute(SocketIOProtocol.class.getName(), p);
                                r.body(msg).method("POST");
                                resource.disableSuspend(true);
                                atmosphereHandler.onRequest(resource);
                            }
                        }
                    }
View Full Code Here

        return "SocketIO-Support";
    }

    @Override
    public Action inspect(AtmosphereResource r) {
        final AtmosphereRequest request = r.getRequest();
        final AtmosphereResponse response = r.getResponse();

        final AtmosphereHandler atmosphereHandler = r.getAtmosphereHandler();
        try {
            // find the transport
            String path = request.getPathInfo();
            if (path == null || path.length() == 0 || "/".equals(path)) {
                logger.debug("Not a SocketIO client");
                return Action.CONTINUE;
            }

            if (path.startsWith("/")) {
                path = path.substring(1);
            }

            String[] parts = path.split("/");

            String protocol = null;
            String version = null;

            // find protocol's version
            if (parts.length == 0) {
                logger.debug("Not a SocketIO protocol supported");
                return Action.CONTINUE;
            } else if (parts.length == 1) {

                // is protocol's version ?
                if (parts[0].length() == 1) {
                    version = parts[0];
                    // must be a digit
                    if (!Character.isDigit(version.charAt(0))) {
                        version = null;
                    }
                } else {
                    protocol = parts[0];
                }

            } else {
                // ex  :[1, xhr-polling, 7589995670715459]
                version = parts[0];
                protocol = parts[1];

                // must be a digit
                if (!Character.isDigit(version.charAt(0))) {
                    version = null;
                    protocol = null;
                }

            }

            if (protocol == null && version == null) {
                logger.debug("Not a SocketIO protocol supported");
                return Action.CONTINUE;
            } else if (protocol == null && version != null) {
                // create a session and send the available transports to the client
                response.setStatus(200);
               
                response.setContentType("plain/text");
               
                SocketIOSession session = getSessionManager(version).createSession((AtmosphereResourceImpl) r, atmosphereHandler);
                response.getWriter().print(session.getSessionId() + ":" + (heartbeatTimeout/1000) + ":" + (timeout/1000) + ":" + availableTransports);

                return Action.CANCELLED;
            } else if (protocol != null && version == null) {
                version = "0";
            }

            final Transport transport = transports.get(protocol + "-" + version);
            if (transport != null) {
                if (!SocketIOAtmosphereHandler.class.isAssignableFrom(atmosphereHandler.getClass())) {
                    response.asyncIOWriter(new AsyncIOWriterAdapter() {
                        @Override
                        public AsyncIOWriter write(AtmosphereResponse r, String data) throws IOException {
                            SocketIOSessionOutbound outbound = (SocketIOSessionOutbound)
                                    request.getAttribute(SocketIOAtmosphereHandler.SOCKETIO_SESSION_OUTBOUND);
                            SocketIOSessionManagerImpl.SocketIOProtocol p = (SocketIOSessionManagerImpl.SocketIOProtocol)
                                    r.request().getAttribute(SOCKETIO_PACKET);

                            String msg = p == null ? data : mapper.writeValueAsString(p.clearArgs().addArgs(data));
View Full Code Here

    }

    @Override
    public Action handle(AtmosphereResourceImpl resource, AtmosphereHandler atmosphereHandler, SocketIOSessionFactory sessionFactory) throws IOException {

        AtmosphereRequest request = resource.getRequest();

        Object obj = request.getAttribute(SESSION_KEY);
        SocketIOSession session = null;
        String sessionId = null;
        if (obj != null) {
            session = (SocketIOSession) obj;
        } else {
            sessionId = extractSessionId(request);
            if (sessionId != null && sessionId.length() > 0) {
                session = sessionFactory.getSession(sessionId);
            }
        }

        boolean isDisconnectRequest = isDisconnectRequest(request);
        if (!isDisconnectRequest) {
            if ("GET".equals(request.getMethod()) && "WebSocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
                session = sessionFactory.getSession(sessionId);
               
                request.setAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID, session.getSessionId());
                request.setAttribute(SocketIOAtmosphereHandler.SOCKETIO_SESSION_ID, session.getSessionId());

                // add a default websocketListener
                SocketIOWebSocketEventListener socketioEventListener = new SocketIOWebSocketEventListener();
                resource.addEventListener(socketioEventListener);

                SocketIOWebSocketSessionWrapperImpl sessionWrapper = new SocketIOWebSocketSessionWrapperImpl(session, socketioEventListener);
                socketioEventListener.setSessionWrapper(sessionWrapper);
                request.setAttribute(SocketIOAtmosphereHandler.SOCKETIO_SESSION_OUTBOUND, sessionWrapper);
                resource.suspend(-1);
            }
        } else {
            session = sessionFactory.getSession(sessionId);
            session.getTransportHandler().disconnect();
View Full Code Here

        if (event.isResuming() || event.isResumedOnTimeout()) {
            return;
        }

        AtmosphereRequest request = event.getResource().getRequest();
        logger.trace("onStateChange on SessionID=" + request.getAttribute(SocketIOAtmosphereHandler.SOCKETIO_SESSION_ID) + "  Method=" + request.getMethod());
        SocketIOSessionOutbound outbound = (org.atmosphere.socketio.SocketIOSessionOutbound) request.getAttribute(SocketIOAtmosphereHandler.SOCKETIO_SESSION_OUTBOUND);

        if (outbound != null && event.getMessage() != null) {
            try {

                if (event.getMessage().getClass().isArray()) {
View Full Code Here

    }

    @Override
    public Action handle(AtmosphereResourceImpl resource, AtmosphereHandler atmosphereHandler, SocketIOSessionFactory sessionFactory) throws IOException {

        AtmosphereRequest request = resource.getRequest();
        AtmosphereResponse response = resource.getResponse();

        Object obj = request.getAttribute(SESSION_KEY);
        SocketIOSession session = null;
        String sessionId = null;
        if (obj != null) {
            session = (SocketIOSession) obj;
        } else {
            sessionId = extractSessionId(request);
            if (sessionId != null && sessionId.length() > 0) {
                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);
                } else {
                    handler.disconnect();
                    response.setStatus(200);
                }
            } else {
                if (!isDisconnectRequest) {
                    // handle the Connect
                    session = connect(session, resource, atmosphereHandler, sessionFactory);
                    if (session == null) {
                        response.sendError(AtmosphereResponse.SC_SERVICE_UNAVAILABLE);
                    }
                } else {
                    response.setStatus(200);
                }
            }
        } else if (sessionId != null && sessionId.length() > 0) {
            logger.trace("Session NULL but not sessionId : wrong session id or the connection was DISCONNECTED");
            response.sendError(AtmosphereResponse.SC_BAD_REQUEST);
        } else {
            if ("GET".equals(request.getMethod())) {
                session = connect(resource, atmosphereHandler, sessionFactory);
                if (session == null) {
                    response.sendError(AtmosphereResponse.SC_SERVICE_UNAVAILABLE);
                }
            } else {
View Full Code Here

        }
    }

    @Override
    public Action inspect(final AtmosphereResource r) {
        final AtmosphereRequest request = r.getRequest();

        if (request.getAttribute("sockjs.skipInterceptor") != null) {
            return Action.CONTINUE;
        }

        boolean info = request.getRequestURI().endsWith("/info");
        if (info) {
            return info(r);
        }

        boolean iframe = request.getRequestURI().endsWith("/iframe.html");
        if (iframe) {
            return iframe(r);
        }

        if (!baseURL.get().isEmpty() && request.getRequestURI().startsWith(baseURL.get())) {
            super.inspect(r);

            final String sessionId = param(request.getRequestURI(), 2);
            String transport = param(request.getRequestURI(), 4);

            SockjsSession s = sessions.get(sessionId);
            configureTransport(AtmosphereResourceImpl.class.cast(r), transport, s != null);
            boolean longPolling = org.atmosphere.util.Utils.resumableTransport(r.transport());
View Full Code Here

TOP

Related Classes of org.atmosphere.cpr.AtmosphereRequest$LazyComputation

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.