Search in sources :

Example 11 with AtmosphereInterceptor

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

the class AtmosphereWebSocketServletDestinationTest method testUseCustomAtmoosphereInterceptors.

@Test
public void testUseCustomAtmoosphereInterceptors() throws Exception {
    Bus bus = new ExtensionManagerBus();
    bus.setProperty("atmosphere.interceptors", Arrays.asList(new CustomInterceptor1(), new CustomInterceptor2()));
    DestinationRegistry registry = new HTTPTransportFactory().getRegistry();
    EndpointInfo endpoint = new EndpointInfo();
    endpoint.setAddress(ENDPOINT_ADDRESS);
    endpoint.setName(ENDPOINT_NAME);
    AtmosphereWebSocketServletDestination dest = new AtmosphereWebSocketServletDestination(bus, registry, endpoint, ENDPOINT_ADDRESS);
    List<AtmosphereInterceptor> ais = dest.getAtmosphereFramework().interceptors();
    int added = 0;
    for (AtmosphereInterceptor a : ais) {
        if (CustomInterceptor1.class.equals(a.getClass())) {
            added++;
        } else if (CustomInterceptor2.class.equals(a.getClass())) {
            added++;
            break;
        }
    }
    assertEquals(2, added);
}
Also used : AtmosphereInterceptor(org.atmosphere.cpr.AtmosphereInterceptor) Bus(org.apache.cxf.Bus) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) DestinationRegistry(org.apache.cxf.transport.http.DestinationRegistry) EndpointInfo(org.apache.cxf.service.model.EndpointInfo) HTTPTransportFactory(org.apache.cxf.transport.http.HTTPTransportFactory) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) Test(org.junit.Test)

Example 12 with AtmosphereInterceptor

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

the class DefaultWebSocketProcessor method invokeInterceptors.

private void invokeInterceptors(WebSocketHandlerProxy webSocketHandler, WebSocket webSocket, Object webSocketMessageAsBody, int offset, int length) throws IOException {
    AtmosphereResourceImpl resource = AtmosphereResourceImpl.class.cast(webSocket.resource());
    if (resource == null) {
        return;
    }
    AtmosphereRequest request = resource.getRequest(false);
    if (String.class.isAssignableFrom(webSocketMessageAsBody.getClass())) {
        request.body(String.class.cast(webSocketMessageAsBody));
    } else if (Reader.class.isAssignableFrom(webSocketMessageAsBody.getClass())) {
        request.body(Reader.class.cast(webSocketMessageAsBody));
    } else if (InputStream.class.isAssignableFrom(webSocketMessageAsBody.getClass())) {
        request.body(InputStream.class.cast(webSocketMessageAsBody));
    } else {
        request.body(new ByteArrayInputStream((byte[]) webSocketMessageAsBody, offset, length));
    }
    String path = webSocketHandler.proxied.getClass().isAnnotationPresent(WebSocketHandlerService.class) ? webSocketHandler.proxied.getClass().getAnnotation(WebSocketHandlerService.class).path() : "/";
    AtmosphereFramework.AtmosphereHandlerWrapper w = framework.getAtmosphereHandlers().get(framework.normalizePath(path));
    List<AtmosphereInterceptor> l;
    if (w == null) {
        l = framework.interceptors();
    } else {
        l = w.interceptors;
    }
    // Globally defined
    int tracing = 0;
    Action a = asynchronousProcessor.invokeInterceptors(l, resource, tracing);
    if (a.type() != Action.TYPE.CONTINUE && a.type() != Action.TYPE.SKIP_ATMOSPHEREHANDLER) {
        return;
    }
    try {
        // Unit test mock the request and will throw NPE.
        boolean skipAtmosphereHandler = request.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) != null ? (Boolean) request.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) : Boolean.FALSE;
        if (!skipAtmosphereHandler) {
            try {
                if (String.class.isAssignableFrom(webSocketMessageAsBody.getClass())) {
                    webSocketHandler.onTextMessage(webSocket, String.class.cast(webSocketMessageAsBody));
                } else if (Reader.class.isAssignableFrom(webSocketMessageAsBody.getClass())) {
                    WebSocketStreamingHandler.class.cast(webSocketHandler.proxied).onTextStream(webSocket, Reader.class.cast(webSocketMessageAsBody));
                } else if (InputStream.class.isAssignableFrom(webSocketMessageAsBody.getClass())) {
                    WebSocketStreamingHandler.class.cast(webSocketHandler.proxied()).onBinaryStream(webSocket, InputStream.class.cast(webSocketMessageAsBody));
                } else {
                    webSocketHandler.onByteMessage(webSocket, (byte[]) webSocketMessageAsBody, offset, length);
                }
            } catch (IOException t) {
                resource.onThrowable(t);
                throw t;
            }
        }
        request.setAttribute(SKIP_ATMOSPHEREHANDLER.name(), Boolean.FALSE);
    } finally {
        asynchronousProcessor.postInterceptors(l, resource);
    }
}
Also used : AtmosphereInterceptor(org.atmosphere.cpr.AtmosphereInterceptor) Action(org.atmosphere.cpr.Action) WebSocketHandlerService(org.atmosphere.config.service.WebSocketHandlerService) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Reader(java.io.Reader) StringReader(java.io.StringReader) IOException(java.io.IOException) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) AtmosphereFramework(org.atmosphere.cpr.AtmosphereFramework) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl)

Example 13 with AtmosphereInterceptor

use of org.atmosphere.cpr.AtmosphereInterceptor 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) {
                    if (delayProtocolInMilliseconds > 0) {
                        executorService.schedule(new Runnable() {

                            @Override
                            public void run() {
                                response.write(protocolMessage.get());
                            }
                        }, delayProtocolInMilliseconds, TimeUnit.MILLISECONDS);
                    } else {
                        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.cpr.AtmosphereInterceptor) AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) OnSuspend(org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter.OnSuspend) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResourceEvent(org.atmosphere.cpr.AtmosphereResourceEvent) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) BroadcastFilter(org.atmosphere.cpr.BroadcastFilter)

Example 14 with AtmosphereInterceptor

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

the class WebSocketHandlerServiceProcessor method handle.

@Override
public void handle(AtmosphereFramework framework, Class<WebSocketHandler> annotatedClass) {
    try {
        WebSocketHandlerService m = annotatedClass.getAnnotation(WebSocketHandlerService.class);
        atmosphereConfig(m.atmosphereConfig(), framework);
        framework.addAtmosphereHandler(m.path(), AtmosphereFramework.REFLECTOR_ATMOSPHEREHANDLER).initWebSocket();
        framework.setDefaultBroadcasterClassName(m.broadcaster().getName());
        filters(m.broadcastFilters(), framework);
        final LinkedList<AtmosphereInterceptor> l = new LinkedList<>();
        AtmosphereInterceptor aa = listeners(m.listeners(), framework);
        if (aa != null) {
            l.add(aa);
        }
        AnnotationUtil.interceptorsForHandler(framework, Arrays.asList(m.interceptors()), l);
        framework.setBroadcasterCacheClassName(m.broadcasterCache().getName());
        WebSocketProcessor p = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(framework);
        framework.addAtmosphereHandler(m.path(), REFLECTOR_ATMOSPHEREHANDLER, l);
        p.registerWebSocketHandler(m.path(), new WebSocketProcessor.WebSocketHandlerProxy(broadcasterClass(framework, m.broadcaster()), framework.newClassInstance(WebSocketHandler.class, annotatedClass)));
    } catch (Throwable e) {
        logger.warn("", e);
    }
}
Also used : AtmosphereInterceptor(org.atmosphere.cpr.AtmosphereInterceptor) WebSocketHandlerService(org.atmosphere.config.service.WebSocketHandlerService) WebSocketProcessor(org.atmosphere.websocket.WebSocketProcessor) LinkedList(java.util.LinkedList)

Example 15 with AtmosphereInterceptor

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

the class ManagedServiceProcessor method handle.

@Override
public void handle(AtmosphereFramework framework, Class<Object> annotatedClass) {
    try {
        ManagedService a = annotatedClass.getAnnotation(ManagedService.class);
        framework.setBroadcasterCacheClassName(a.broadcasterCache().getName());
        List<AtmosphereInterceptor> l = new LinkedList<>();
        AnnotationUtil.defaultManagedServiceInterceptors(framework, l);
        atmosphereConfig(a.atmosphereConfig(), framework);
        filters(a.broadcastFilters(), framework);
        AtmosphereInterceptor aa = listeners(a.listeners(), framework);
        if (aa != null) {
            l.add(aa);
        }
        Object c = framework.newClassInstance(Object.class, annotatedClass);
        AtmosphereHandler handler = framework.newClassInstance(ManagedAtmosphereHandler.class, ManagedAtmosphereHandler.class).configure(framework.getAtmosphereConfig(), c);
        framework.filterManipulator(new BroadcasterConfig.FilterManipulator() {

            @Override
            public Object unwrap(Object o) {
                if (o != null && ManagedAtmosphereHandler.Managed.class.isAssignableFrom(o.getClass())) {
                    o = ((ManagedAtmosphereHandler.Managed) o).object();
                }
                return o;
            }

            @Override
            public BroadcastFilter.BroadcastAction wrap(BroadcastFilter.BroadcastAction a, boolean wasWrapped) {
                if (wasWrapped) {
                    return new BroadcastFilter.BroadcastAction(a.action(), new ManagedAtmosphereHandler.Managed(a.message()));
                } else {
                    return a;
                }
            }
        });
        AnnotationUtil.interceptorsForManagedService(framework, Arrays.asList(a.interceptors()), l);
        framework.addAtmosphereHandler(a.path(), handler, broadcaster(framework, a.broadcaster(), a.path()), l);
    } catch (Throwable e) {
        logger.warn("", e);
    }
}
Also used : ManagedService(org.atmosphere.config.service.ManagedService) AtmosphereInterceptor(org.atmosphere.cpr.AtmosphereInterceptor) BroadcasterConfig(org.atmosphere.cpr.BroadcasterConfig) LinkedList(java.util.LinkedList) ManagedAtmosphereHandler(org.atmosphere.config.managed.ManagedAtmosphereHandler) ManagedAtmosphereHandler(org.atmosphere.config.managed.ManagedAtmosphereHandler) AtmosphereHandler(org.atmosphere.cpr.AtmosphereHandler) BroadcastFilter(org.atmosphere.cpr.BroadcastFilter)

Aggregations

AtmosphereInterceptor (org.atmosphere.cpr.AtmosphereInterceptor)15 Bus (org.apache.cxf.Bus)6 ExtensionManagerBus (org.apache.cxf.bus.extension.ExtensionManagerBus)6 EndpointInfo (org.apache.cxf.service.model.EndpointInfo)6 DestinationRegistry (org.apache.cxf.transport.http.DestinationRegistry)6 HTTPTransportFactory (org.apache.cxf.transport.http.HTTPTransportFactory)6 Test (org.junit.Test)6 LinkedList (java.util.LinkedList)5 AtmosphereHandler (org.atmosphere.cpr.AtmosphereHandler)3 IOException (java.io.IOException)2 WebSocketHandlerService (org.atmosphere.config.service.WebSocketHandlerService)2 AtmosphereRequest (org.atmosphere.cpr.AtmosphereRequest)2 AtmosphereResourceEvent (org.atmosphere.cpr.AtmosphereResourceEvent)2 AtmosphereResourceImpl (org.atmosphere.cpr.AtmosphereResourceImpl)2 BroadcastFilter (org.atmosphere.cpr.BroadcastFilter)2 ReflectorServletProcessor (org.atmosphere.handler.ReflectorServletProcessor)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1