Examples of AtmosphereResponse


Examples of org.atmosphere.cpr.AtmosphereResponse

    }

    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

Examples of org.atmosphere.cpr.AtmosphereResponse

        padding = paddingText.getBytes();
    }

    @Override
    public void onPreSuspend(AtmosphereResourceEvent event) {
        AtmosphereResponse response = event.getResource().getResponse();
        response.setContentType("application/javascript");
        try {

            response.write(padding, true).flushBuffer();
            response.write("o\n".getBytes(), true).flushBuffer();
        } catch (IOException e) {
            logger.trace("", e);
        }
    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

public class JSONPTransport extends TransportBasedListener {
    private static final Logger logger = LoggerFactory.getLogger(JSONPTransport.class);
    @Override
    public void onSuspend(AtmosphereResourceEvent event) {
        AtmosphereResponse response = event.getResource().getResponse();
        try {
            response.write("o".getBytes()).flushBuffer();
        } catch (IOException e) {
            logger.trace("", e);
        }
    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

    }

    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();
        } catch (IOException e) {
            logger.trace("", e);
        }
    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

        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);
            finishSend(response);
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

    }

    @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)
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

    @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 {
                response.sendError(AtmosphereResponse.SC_BAD_REQUEST);
            }
        }

        return action;
    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

        }
        return Action.CONTINUE;
    }

    private Action iframe(AtmosphereResource r) {
        final AtmosphereResponse response = r.getResponse();
        response.setContentType("text/html");
        String origin = framework.getAtmosphereConfig().getInitParameter(SOCKS_JS_ORIGIN);
        if (origin == null) {
            origin = "http://localhost:8080/lib/sockjs.js";
        }
        try {
            response.write(IFrameUtils.generateIFrame(origin)).flushBuffer();
        } catch (IOException e) {
            logger.error("", e);
        }
        return Action.CANCELLED;
    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

        }
        return Action.CANCELLED;
    }

    protected Action info(AtmosphereResource r) {
        final AtmosphereResponse response = r.getResponse();
        final AtmosphereRequest request = r.getRequest();

        response.headers().put("Content-Type", "application/json; charset=UTF-8");
        ObjectNode json = new ObjectNode(JsonNodeFactory.instance);
        json.put("websocket", supportWebSocket);
        json.putArray("origins").add("*:*");
        json.put("entropy", new Random().nextInt());
        r.write(JsonCodec.encode(json));
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

        }
    }

    private void installWriter(final AtmosphereResource r, final String sessionId) {
        final AtmosphereResource.TRANSPORT transport = r.transport();
        final AtmosphereResponse response = r.getResponse();

        AsyncIOWriter writer = response.getAsyncIOWriter();
        if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
            AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() {
                @Override
                public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data) throws IOException {
                    String charEncoding = response.getCharacterEncoding() == null ? "UTF-8" : response.getCharacterEncoding();
                    String s = new String(responseDraft, charEncoding);

                    // Ugly.
                    if (s.equalsIgnoreCase("h") || s.equals("c") || (s.equals("o\n") && r.transport().equals(AtmosphereResource.TRANSPORT.WEBSOCKET))) {
                        return s.getBytes();
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.