Search in sources :

Example 6 with AtmosphereResourceImpl

use of org.atmosphere.runtime.AtmosphereResourceImpl 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 7 with AtmosphereResourceImpl

use of org.atmosphere.runtime.AtmosphereResourceImpl 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 8 with AtmosphereResourceImpl

use of org.atmosphere.runtime.AtmosphereResourceImpl 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.runtime.AtmosphereResponse) Enumeration(java.util.Enumeration) ServletConfig(javax.servlet.ServletConfig) IOException(java.io.IOException) SimpleBroadcaster(org.atmosphere.util.SimpleBroadcaster) ServletException(javax.servlet.ServletException) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AsynchronousProcessor(org.atmosphere.runtime.AsynchronousProcessor) AtmosphereFramework(org.atmosphere.runtime.AtmosphereFramework) ServletContext(javax.servlet.ServletContext) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 9 with AtmosphereResourceImpl

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

the class JavaScriptProtocol method inspect.

@Override
public Action inspect(final AtmosphereResource ar) {
    if (Utils.webSocketMessage(ar))
        return Action.CONTINUE;
    final AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(ar);
    final AtmosphereRequest request = r.getRequest(false);
    final AtmosphereResponse response = r.getResponse(false);
    String uuid = request.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);
    String handshakeUUID = request.getHeader(HeaderConfig.X_ATMO_PROTOCOL);
    if (uuid != null && uuid.equals("0") && handshakeUUID != null) {
        if (enforceAtmosphereVersion) {
            String javascriptVersion = request.getHeader(HeaderConfig.X_ATMOSPHERE_FRAMEWORK);
            int version = 0;
            if (javascriptVersion != null) {
                version = parseVersion(javascriptVersion.split("-")[0]);
            }
            if (version < 221) {
                logger.error("Invalid Atmosphere Version {}", javascriptVersion);
                response.setStatus(501);
                response.addHeader(X_ATMOSPHERE_ERROR, "Atmosphere Protocol version not supported.");
                try {
                    response.flushBuffer();
                } catch (IOException e) {
                }
                return Action.CANCELLED;
            }
        }
        request.header(HeaderConfig.X_ATMO_PROTOCOL, null);
        // Extract heartbeat data
        int heartbeatInterval = 0;
        String heartbeatData = "";
        for (final AtmosphereInterceptor interceptor : framework.interceptors()) {
            if (HeartbeatInterceptor.class.isAssignableFrom(interceptor.getClass())) {
                final HeartbeatInterceptor heartbeatInterceptor = HeartbeatInterceptor.class.cast(interceptor);
                heartbeatInterval = heartbeatInterceptor.clientHeartbeatFrequencyInSeconds() * 1000;
                heartbeatData = new String(heartbeatInterceptor.getPaddingBytes());
                break;
            }
        }
        String message;
        if (enforceAtmosphereVersion) {
            // UUID since 1.0.10
            message = new StringBuilder(r.uuid()).append(wsDelimiter).append(heartbeatInterval).append(wsDelimiter).append(heartbeatData).append(wsDelimiter).toString();
        } else {
            // UUID since 1.0.10
            message = r.uuid();
        }
        // https://github.com/Atmosphere/atmosphere/issues/993
        final AtomicReference<String> protocolMessage = new AtomicReference<String>(message);
        if (r.getBroadcaster().getBroadcasterConfig().hasFilters()) {
            for (BroadcastFilter bf : r.getBroadcaster().getBroadcasterConfig().filters()) {
                if (TrackMessageSizeFilter.class.isAssignableFrom(bf.getClass())) {
                    protocolMessage.set((String) f.filter(r.getBroadcaster().getID(), r, protocolMessage.get(), protocolMessage.get()).message());
                    break;
                }
            }
        }
        if (!Utils.resumableTransport(r.transport())) {
            OnSuspend a = new OnSuspend() {

                @Override
                public void onSuspend(AtmosphereResourceEvent event) {
                    response.write(protocolMessage.get());
                    try {
                        response.flushBuffer();
                    } catch (IOException e) {
                        logger.trace("", e);
                    }
                    r.removeEventListener(this);
                }
            };
            // Pass the information to Servlet Based Framework
            request.setAttribute(CALLBACK_JAVASCRIPT_PROTOCOL, a);
            r.addEventListener(a);
        } else {
            response.write(protocolMessage.get());
        }
        // We don't need to reconnect here
        if (r.transport() == AtmosphereResource.TRANSPORT.WEBSOCKET || r.transport() == AtmosphereResource.TRANSPORT.STREAMING || r.transport() == AtmosphereResource.TRANSPORT.SSE) {
            return Action.CONTINUE;
        } else {
            return Action.CANCELLED;
        }
    }
    return Action.CONTINUE;
}
Also used : AtmosphereInterceptor(org.atmosphere.runtime.AtmosphereInterceptor) AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) OnSuspend(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter.OnSuspend) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) BroadcastFilter(org.atmosphere.runtime.BroadcastFilter)

Example 10 with AtmosphereResourceImpl

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

the class ManagedAtmosphereHandler method onStateChange.

@Override
@SuppressWarnings("unchecked")
public void onStateChange(AtmosphereResourceEvent event) throws IOException {
    Object msg = event.getMessage();
    // Original Value
    AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(event.getResource());
    Boolean resumeOnBroadcast = r.resumeOnBroadcast();
    if (!resumeOnBroadcast) {
        // For legacy reason, check the attribute as well
        Object o = r.getRequest(false).getAttribute(ApplicationConfig.RESUME_ON_BROADCAST);
        if (o != null && Boolean.class.isAssignableFrom(o.getClass())) {
            resumeOnBroadcast = Boolean.class.cast(o);
        }
    }
    // Disable resume so cached message can be send in one chunk.
    if (resumeOnBroadcast) {
        r.resumeOnBroadcast(false);
        r.getRequest(false).setAttribute(ApplicationConfig.RESUME_ON_BROADCAST, false);
    }
    if (event.isCancelled() || event.isClosedByClient()) {
        invoke(onDisconnectMethod, event);
    } else if (event.isResumedOnTimeout() || event.isResuming()) {
        invoke(onTimeoutMethod, event);
    } else {
        Object o;
        if (msg != null) {
            if (Managed.class.isAssignableFrom(msg.getClass())) {
                Object newMsg = Managed.class.cast(msg).o;
                event.setMessage(newMsg);
                // TODO: This could be problematic with String + method
                if (r.getBroadcaster().getBroadcasterConfig().hasFilters()) {
                    for (MethodInfo m : onRuntimeMethod) {
                        o = Invoker.encode(encoders.get(m.method), newMsg);
                        if (o != null) {
                            event.setMessage(o);
                            break;
                        }
                    }
                }
            } else {
                logger.trace("BroadcasterFactory has been used, this may produce recursion if encoder/decoder match the broadcasted message");
                final MethodInfo.EncoderObject e = message(r, msg);
                o = e == null ? null : e.encodedObject;
                if (o != null) {
                    event.setMessage(o);
                }
            }
        }
        super.onStateChange(event);
    }
    if (resumeOnBroadcast && r.isSuspended()) {
        r.resume();
    }
}
Also used : AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl)

Aggregations

AtmosphereResourceImpl (org.atmosphere.runtime.AtmosphereResourceImpl)21 AtmosphereRequest (org.atmosphere.runtime.AtmosphereRequest)15 IOException (java.io.IOException)13 AtmosphereResponse (org.atmosphere.runtime.AtmosphereResponse)11 ServletException (javax.servlet.ServletException)8 AsynchronousProcessor (org.atmosphere.runtime.AsynchronousProcessor)7 AtmosphereFramework (org.atmosphere.runtime.AtmosphereFramework)7 BeforeMethod (org.testng.annotations.BeforeMethod)6 SimpleBroadcaster (org.atmosphere.util.SimpleBroadcaster)5 ArrayList (java.util.ArrayList)4 Enumeration (java.util.Enumeration)4 ServletConfig (javax.servlet.ServletConfig)4 ServletContext (javax.servlet.ServletContext)4 Action (org.atmosphere.runtime.Action)3 AtmosphereResource (org.atmosphere.runtime.AtmosphereResource)3 AtmosphereResourceEvent (org.atmosphere.runtime.AtmosphereResourceEvent)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 AtmosphereInterceptor (org.atmosphere.runtime.AtmosphereInterceptor)2 AtmosphereMappingException (org.atmosphere.runtime.AtmosphereMappingException)2 AtmosphereResourceEventImpl (org.atmosphere.runtime.AtmosphereResourceEventImpl)2