Search in sources :

Example 6 with AtmosphereResponse

use of org.atmosphere.cpr.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.cpr.AtmosphereRequestImpl) AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncIOWriterAdapter(org.atmosphere.cpr.AsyncIOWriterAdapter) AsyncIOWriter(org.atmosphere.cpr.AsyncIOWriter) IOException(java.io.IOException) Test(org.testng.annotations.Test)

Example 7 with AtmosphereResponse

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

the class ManagedAtmosphereHandlerTest method create.

@BeforeMethod
public void create() throws Throwable {
    framework = new AtmosphereFramework();
    framework.setDefaultBroadcasterClassName(SimpleBroadcaster.class.getName());
    framework.addAnnotationPackage(ManagedGet.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(new ServletConfig() {

        @Override
        public String getServletName() {
            return "void";
        }

        @Override
        public ServletContext getServletContext() {
            return mock(ServletContext.class);
        }

        @Override
        public String getInitParameter(String name) {
            return ApplicationConfig.CLIENT_HEARTBEAT_INTERVAL_IN_SECONDS.equals(name) ? "10" : null;
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return null;
        }
    });
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) Enumeration(java.util.Enumeration) ServletConfig(jakarta.servlet.ServletConfig) IOException(java.io.IOException) SimpleBroadcaster(org.atmosphere.util.SimpleBroadcaster) ServletException(jakarta.servlet.ServletException) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AsynchronousProcessor(org.atmosphere.cpr.AsynchronousProcessor) AtmosphereFramework(org.atmosphere.cpr.AtmosphereFramework) ServletContext(jakarta.servlet.ServletContext) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 8 with AtmosphereResponse

use of org.atmosphere.cpr.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(jakarta.servlet.ServletException) AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) Action(org.atmosphere.cpr.Action) AtmosphereHandlerAdapter(org.atmosphere.handler.AtmosphereHandlerAdapter) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) AsynchronousProcessor(org.atmosphere.cpr.AsynchronousProcessor) AtmosphereFramework(org.atmosphere.cpr.AtmosphereFramework) IOException(java.io.IOException) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 9 with AtmosphereResponse

use of org.atmosphere.cpr.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 {
                                AtmosphereResource currentResource = framework.atmosphereFactory().find(resource.uuid());
                                if (currentResource != null && currentResource.isSuspended()) {
                                    // Do not close if the resource has reconnected already
                                    executeClose(webSocket, 1005);
                                    finish(webSocket, currentResource, 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.cpr.AtmosphereResponse) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) ServletException(jakarta.servlet.ServletException) AtmosphereMappingException(org.atmosphere.cpr.AtmosphereMappingException) IOException(java.io.IOException)

Example 10 with AtmosphereResponse

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

the class PaddingAtmosphereInterceptor 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 uuid = request.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);
    boolean padding = r.transport().equals(TRANSPORT.STREAMING) || r.transport().equals(TRANSPORT.LONG_POLLING);
    if (uuid != null && !uuid.equals("0") && r.transport().equals(TRANSPORT.WEBSOCKET) && request.getAttribute(INJECTED_ATMOSPHERE_RESOURCE) != null) {
        padding = true;
    }
    if (padding) {
        r.addEventListener(new ForcePreSuspend(response));
        super.inspect(r);
        AsyncIOWriter writer = response.getAsyncIOWriter();
        if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
            AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() {

                private void padding() {
                    if (!r.isSuspended()) {
                        writePadding(response);
                        request.setAttribute("paddingWritten", "true");
                    }
                }

                @Override
                public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                    padding();
                }

                @Override
                public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                }
            });
        } 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) AsyncIOInterceptorAdapter(org.atmosphere.cpr.AsyncIOInterceptorAdapter)

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