Search in sources :

Example 6 with AtmosphereResponse

use of org.atmosphere.runtime.AtmosphereResponse in project atmosphere by Atmosphere.

the class SSEAtmosphereInterceptor method inspect.

@Override
public Action inspect(final AtmosphereResource r) {
    if (Utils.webSocketMessage(r))
        return Action.CONTINUE;
    final AtmosphereResponse response = r.getResponse();
    final AtmosphereRequest request = r.getRequest();
    String accept = request.getHeader("Accept") == null ? "text/plain" : request.getHeader("Accept").trim();
    if (r.transport().equals(AtmosphereResource.TRANSPORT.SSE) || contentType.equalsIgnoreCase(accept)) {
        super.inspect(r);
        r.addEventListener(new P(response));
        AsyncIOWriter writer = response.getAsyncIOWriter();
        if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
            AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() {

                private boolean padding() {
                    if (!r.isSuspended()) {
                        return writePadding(response);
                    }
                    return false;
                }

                @Override
                public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                    boolean noPadding = padding();
                    // In that case, we must pad/protocol indenendently of the state of the AtmosphereResource
                    if (!noPadding || r.getRequest().getAttribute(CALLBACK_JAVASCRIPT_PROTOCOL) != null) {
                        // write other meta info such as (id, event, etc)?
                        response.write(DATA, true);
                    }
                }

                @Override
                public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data) throws IOException {
                    boolean noPadding = padding();
                    // In that case, we must pad/protocol indenendently of the state of the AtmosphereResource
                    if (!noPadding || r.getRequest().getAttribute(CALLBACK_JAVASCRIPT_PROTOCOL) != null) {
                        if (isMultilineData(responseDraft)) {
                            // return a padded multiline-data
                            return encodeMultilineData(responseDraft);
                        }
                    }
                    return responseDraft;
                }

                @Override
                public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                    // In that case, we must pad/protocol indenendently of the state of the AtmosphereResource
                    if (r.isSuspended() || r.getRequest().getAttribute(CALLBACK_JAVASCRIPT_PROTOCOL) != null || r.getRequest().getAttribute(CONTAINER_RESPONSE) != null) {
                        response.write(END, true);
                    }
                    /**
                         * When used with https://github.com/remy/polyfills/blob/master/EventSource.js , we
                         * resume after every message.
                         */
                    String ua = r.getRequest().getHeader("User-Agent");
                    if (ua != null && ua.contains("MSIE")) {
                        try {
                            response.flushBuffer();
                        } catch (IOException e) {
                            logger.trace("", e);
                        }
                        r.resume();
                    }
                }
            });
        } else {
            logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName());
        }
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AsyncIOWriter(org.atmosphere.runtime.AsyncIOWriter) AtmosphereInterceptorWriter(org.atmosphere.runtime.AtmosphereInterceptorWriter) IOException(java.io.IOException) AsyncIOInterceptorAdapter(org.atmosphere.runtime.AsyncIOInterceptorAdapter)

Example 7 with AtmosphereResponse

use of org.atmosphere.runtime.AtmosphereResponse in project atmosphere by Atmosphere.

the class DefaultWebSocketProcessor method close.

@Override
public void close(final WebSocket webSocket, int closeCode) {
    WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
    // A message might be in the process of being processed and the websocket gets closed. In that corner
    // case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
    // We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
    // synchronized (webSocket) {
    final AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
    if (resource == null) {
        logger.trace("Already closed {}", webSocket);
    } else {
        final boolean allowedToClose = allowedCloseCode(closeCode);
        final AtmosphereRequest r = resource.getRequest(false);
        final AtmosphereResponse s = resource.getResponse(false);
        boolean ff = r.getAttribute("firefox") != null;
        boolean completeLifecycle = true;
        try {
            webSocketProtocol.onClose(webSocket);
            if (webSocketHandler != null) {
                webSocketHandler.onClose(webSocket);
            }
            logger.trace("About to close AtmosphereResource for {} with code {}", resource, closeCode);
            if (!resource.getAtmosphereResourceEvent().isClosedByClient() && !resource.getAtmosphereResourceEvent().isClosedByApplication() && !resource.isCancelled()) {
                // Better to call onDisconnect that onResume.
                if (allowedToClose) {
                    if (ff || closingTime > 0) {
                        completeLifecycle = false;
                        logger.debug("Delaying closing operation for firefox and resource {}", resource.uuid());
                        ExecutorsFactory.getScheduler(framework.getAtmosphereConfig()).schedule(new Callable<Object>() {

                            @Override
                            public Object call() throws Exception {
                                executeClose(webSocket, 1005);
                                finish(webSocket, resource, r, s, !allowedToClose);
                                return null;
                            }
                        }, ff ? (closingTime == 0 ? 1000 : closingTime) : closingTime, TimeUnit.MILLISECONDS);
                        resource.getAndSetPendingClose();
                    } else {
                        executeClose(webSocket, closeCode);
                    }
                } else {
                    logger.debug("Timeout {}", resource.uuid());
                    asynchronousProcessor.endRequest(AtmosphereResourceImpl.class.cast(webSocket.resource()), false);
                }
            } else {
                logger.trace("Unable to properly complete {}", resource == null ? "null" : resource.uuid());
                completeLifecycle = false;
            }
        } finally {
            if (completeLifecycle) {
                finish(webSocket, resource, r, s, !allowedToClose);
            }
        }
    }
}
Also used : AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) ServletException(javax.servlet.ServletException) AtmosphereMappingException(org.atmosphere.runtime.AtmosphereMappingException) IOException(java.io.IOException)

Example 8 with AtmosphereResponse

use of org.atmosphere.runtime.AtmosphereResponse in project atmosphere by Atmosphere.

the class AnnotationScanningTest method create.

@BeforeMethod
public void create() throws Throwable {
    framework = new AtmosphereFramework();
    framework.setDefaultBroadcasterClassName(SimpleBroadcaster.class.getName());
    framework.addAnnotationPackage(AnnotationScanningTest.class);
    framework.setAsyncSupport(new AsynchronousProcessor(framework.getAtmosphereConfig()) {

        @Override
        public Action service(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
            return suspended(req, res);
        }

        public void action(AtmosphereResourceImpl r) {
            try {
                resumed(r.getRequest(), r.getResponse());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }).init().addAtmosphereHandler("/a", new AtmosphereHandlerAdapter() {

        @Override
        public void onRequest(AtmosphereResource resource) throws IOException {
            resource.suspend();
        }
    });
}
Also used : SimpleBroadcaster(org.atmosphere.util.SimpleBroadcaster) ServletException(javax.servlet.ServletException) AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) Action(org.atmosphere.runtime.Action) AtmosphereHandlerAdapter(org.atmosphere.handler.AtmosphereHandlerAdapter) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) AsynchronousProcessor(org.atmosphere.runtime.AsynchronousProcessor) AtmosphereFramework(org.atmosphere.runtime.AtmosphereFramework) IOException(java.io.IOException) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 9 with AtmosphereResponse

use of org.atmosphere.runtime.AtmosphereResponse in project atmosphere by Atmosphere.

the class SSEAtmosphereInterceptorTest method testDataWriter.

@Test
public void testDataWriter() throws Exception {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ServletResponse resp = Mockito.mock(HttpServletResponse.class);
    Mockito.when(resp.getOutputStream()).thenReturn(new ServletOutputStream() {

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            baos.write(b);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            baos.write(b, off, len);
        }
    });
    AtmosphereRequest request = AtmosphereRequestImpl.newInstance();
    request.header(HeaderConfig.X_ATMOSPHERE_TRANSPORT, "SSE");
    AtmosphereResponse response = AtmosphereResponseImpl.newInstance(request);
    response.request(request);
    response.setResponse(resp);
    AtmosphereResourceImpl resource = new AtmosphereResourceImpl();
    resource.initialize(framework.getAtmosphereConfig(), framework.getBroadcasterFactory().get(), request, response, Mockito.mock(AsyncSupport.class), null);
    resource.suspend();
    SSEAtmosphereInterceptor interceptor = new SSEAtmosphereInterceptor();
    interceptor.configure(config);
    interceptor.inspect(resource);
    // no newline
    response.write("Good Morning".getBytes());
    assertEquals(baos.toString(), "data:Good Morning\r\n\r\n");
    baos.reset();
    // \n
    response.write("Hello World!\nHave a nice day!".getBytes());
    assertEquals(baos.toString(), "data:Hello World!\r\ndata:Have a nice day!\r\n\r\n");
    baos.reset();
    // \r
    response.write("Hello World!\rHave a nice day!".getBytes());
    assertEquals(baos.toString(), "data:Hello World!\r\ndata:Have a nice day!\r\n\r\n");
    baos.reset();
    // \r\n
    response.write("Hello World!\r\nHave a nice day!".getBytes());
    assertEquals(baos.toString(), "data:Hello World!\r\ndata:Have a nice day!\r\n\r\n");
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) ServletOutputStream(javax.servlet.ServletOutputStream) AsyncSupport(org.atmosphere.runtime.AsyncSupport) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) WriteListener(javax.servlet.WriteListener) Test(org.testng.annotations.Test)

Example 10 with AtmosphereResponse

use of org.atmosphere.runtime.AtmosphereResponse in project atmosphere by Atmosphere.

the class EncoderDecoderTest method testEncoder.

@Test
public void testEncoder() throws IOException, ServletException, InterruptedException {
    AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/h").method("GET").build();
    AtmosphereResponse response = AtmosphereResponseImpl.newInstance();
    final AtomicReference<String> ref = new AtomicReference();
    response.asyncIOWriter(new AsyncIOWriterAdapter() {

        @Override
        public AsyncIOWriter write(AtmosphereResponse r, byte[] data) throws IOException {
            ref.set(new String(data));
            return this;
        }
    });
    framework.doCometSupport(request, response);
    assertNotNull(r.get());
    latch.get().await(5, TimeUnit.SECONDS);
    r.get().resume();
    assertNotNull(message.get());
    assertEquals(message.get(), "message");
    assertEquals(ref.get(), "message-yo!");
}
Also used : AtmosphereRequestImpl(org.atmosphere.runtime.AtmosphereRequestImpl) AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncIOWriterAdapter(org.atmosphere.runtime.AsyncIOWriterAdapter) AsyncIOWriter(org.atmosphere.runtime.AsyncIOWriter) IOException(java.io.IOException) Test(org.testng.annotations.Test)

Aggregations

AtmosphereResponse (org.atmosphere.runtime.AtmosphereResponse)25 AtmosphereRequest (org.atmosphere.runtime.AtmosphereRequest)18 IOException (java.io.IOException)16 AtmosphereResourceImpl (org.atmosphere.runtime.AtmosphereResourceImpl)12 AsyncIOWriter (org.atmosphere.runtime.AsyncIOWriter)11 AtmosphereInterceptorWriter (org.atmosphere.runtime.AtmosphereInterceptorWriter)9 ServletException (javax.servlet.ServletException)8 AsynchronousProcessor (org.atmosphere.runtime.AsynchronousProcessor)6 AtmosphereFramework (org.atmosphere.runtime.AtmosphereFramework)6 BeforeMethod (org.testng.annotations.BeforeMethod)6 AsyncIOInterceptorAdapter (org.atmosphere.runtime.AsyncIOInterceptorAdapter)5 SimpleBroadcaster (org.atmosphere.util.SimpleBroadcaster)5 Enumeration (java.util.Enumeration)4 ServletConfig (javax.servlet.ServletConfig)4 ServletContext (javax.servlet.ServletContext)4 AtmosphereResourceEvent (org.atmosphere.runtime.AtmosphereResourceEvent)3 Test (org.testng.annotations.Test)3 List (java.util.List)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Action (org.atmosphere.runtime.Action)2