Search in sources :

Example 1 with AtmosphereResponse

use of org.atmosphere.cpr.AtmosphereResponse in project cxf by apache.

the class SseAtmosphereEventSinkImpl method close.

@Override
public void close() {
    if (!closed) {
        closed = true;
        LOG.fine("Closing Atmosphere SSE event output");
        if (resource.isSuspended()) {
            LOG.fine("Atmosphere resource is suspended, resuming");
            resource.resume();
        }
        final Broadcaster broadcaster = resource.getBroadcaster();
        resource.removeFromAllBroadcasters();
        try {
            final AtmosphereResponse response = resource.getResponse();
            try {
                // or stream.
                if (usingStream) {
                    response.getOutputStream().close();
                } else {
                    response.getWriter().close();
                }
            } catch (final IOException ex) {
                LOG.warning("Failed to flush AtmosphereResponse buffer: " + ex.getMessage());
            }
        } finally {
            try {
                resource.close();
            } catch (IOException ex) {
            // ignore
            }
            broadcaster.destroy();
            LOG.fine("Atmosphere SSE event output is closed");
        }
    }
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) Broadcaster(org.atmosphere.cpr.Broadcaster) IOException(java.io.IOException)

Example 2 with AtmosphereResponse

use of org.atmosphere.cpr.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.cpr.AtmosphereResponse) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AsyncIOWriter(org.atmosphere.cpr.AsyncIOWriter) AtmosphereInterceptorWriter(org.atmosphere.cpr.AtmosphereInterceptorWriter) IOException(java.io.IOException) AsyncIOInterceptorAdapter(org.atmosphere.cpr.AsyncIOInterceptorAdapter)

Example 3 with AtmosphereResponse

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

the class OnMessage method onStateChange.

@Override
public final void onStateChange(AtmosphereResourceEvent event) throws IOException {
    AtmosphereResponse response = ((AtmosphereResourceImpl) event.getResource()).getResponse(false);
    logger.trace("{} with event {}", event.getResource().uuid(), event);
    if (event.isCancelled() || event.isClosedByApplication() || event.isClosedByClient()) {
        onDisconnect(response);
    } else if (event.getMessage() != null && List.class.isAssignableFrom(event.getMessage().getClass())) {
        List<T> messages = List.class.cast(event.getMessage());
        for (T t : messages) {
            onMessage(response, t);
        }
    } else if (event.isResuming()) {
        onResume(response);
    } else if (event.isResumedOnTimeout()) {
        onTimeout(response);
    } else if (event.isSuspended()) {
        onMessage(response, (T) event.getMessage());
    }
    postStateChange(event);
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) List(java.util.List) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl)

Example 4 with AtmosphereResponse

use of org.atmosphere.cpr.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 false;
        }

        @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 : ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) ServletOutputStream(jakarta.servlet.ServletOutputStream) AsyncSupport(org.atmosphere.cpr.AsyncSupport) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) WriteListener(jakarta.servlet.WriteListener) Test(org.testng.annotations.Test)

Example 5 with AtmosphereResponse

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

the class WebSocketTest method testTransformWithConcurrency.

@Test
public void testTransformWithConcurrency() throws Exception {
    WebSocket ws = new WebSocket(framework.getAtmosphereConfig()) {

        @Override
        public boolean isOpen() {
            return false;
        }

        @Override
        public WebSocket write(String s) throws IOException {
            return null;
        }

        @Override
        public WebSocket write(byte[] b, int offset, int length) throws IOException {
            return null;
        }

        @Override
        public void close() {
        }
    };
    ws.interceptor(new DummyInterceptor(500));
    ws.interceptor(new DummyInterceptor(10));
    AtmosphereResponse response1 = AtmosphereResponseImpl.newInstance();
    AtmosphereResponse response2 = AtmosphereResponseImpl.newInstance();
    Worker worker1 = new Worker(ws, response1);
    Worker worker2 = new Worker(ws, response2);
    Thread t1 = new Thread(worker1);
    Thread t2 = new Thread(worker2);
    t1.start();
    t2.start();
    t1.join(2000);
    t2.join(2000);
    assertFalse(worker1.isCorrupted(), "corrupted");
    assertFalse(worker2.isCorrupted(), "corrupted");
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) Test(org.testng.annotations.Test)

Aggregations

AtmosphereResponse (org.atmosphere.cpr.AtmosphereResponse)29 AtmosphereRequest (org.atmosphere.cpr.AtmosphereRequest)21 IOException (java.io.IOException)19 AsyncIOWriter (org.atmosphere.cpr.AsyncIOWriter)12 AtmosphereResourceImpl (org.atmosphere.cpr.AtmosphereResourceImpl)12 AtmosphereInterceptorWriter (org.atmosphere.cpr.AtmosphereInterceptorWriter)10 ServletException (jakarta.servlet.ServletException)9 AsynchronousProcessor (org.atmosphere.cpr.AsynchronousProcessor)7 AtmosphereFramework (org.atmosphere.cpr.AtmosphereFramework)7 BeforeMethod (org.testng.annotations.BeforeMethod)6 AsyncIOInterceptorAdapter (org.atmosphere.cpr.AsyncIOInterceptorAdapter)5 SimpleBroadcaster (org.atmosphere.util.SimpleBroadcaster)5 ServletConfig (jakarta.servlet.ServletConfig)4 ServletContext (jakarta.servlet.ServletContext)4 Enumeration (java.util.Enumeration)4 Action (org.atmosphere.cpr.Action)4 AtmosphereResource (org.atmosphere.cpr.AtmosphereResource)3 AtmosphereResourceEvent (org.atmosphere.cpr.AtmosphereResourceEvent)3 Test (org.testng.annotations.Test)3 List (java.util.List)2