Package org.atmosphere.cpr

Examples of org.atmosphere.cpr.AtmosphereResourceImpl


    @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 = 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;
                }
            }

            // Since 1.0.10
            final StringBuffer message = new StringBuffer(r.uuid()).append(wsDelimiter);

            // since 2.2
            if (enforceAtmosphereVersion) {
                message.append(heartbeatInterval)
                    .append(wsDelimiter)
                    .append(heartbeatData)
                    .append(wsDelimiter);
            }

            // https://github.com/Atmosphere/atmosphere/issues/993
            final AtomicReference<String> protocolMessage = new AtomicReference<String>(message.toString());
            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;
            }
        }
View Full Code Here


        rewriteUri = Boolean.valueOf(config.getInitParameter(ApplicationConfig.REWRITE_WEBSOCKET_REQUESTURI, "true"));
    }

    @Override
    public List<AtmosphereRequest> onMessage(WebSocket webSocket, String message) {
        AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
        if (resource == null) {
            logger.trace("The WebSocket has been closed before the message was processed.");
            return null;
        }
        AtmosphereRequest request = resource.getRequest(false);

        if (!resource.isInScope()) return Collections.emptyList();

        String pathInfo = request.getPathInfo();
        String requestURI = request.getRequestURI();

        // This confuse some JAXRS servers like RestEasy
View Full Code Here

    @Override
    public List<AtmosphereRequest> onMessage(WebSocket webSocket, byte[] d, final int offset, final int length) {

        //Converting to a string and delegating to onMessage(WebSocket webSocket, String d) causes issues because the binary data may not be a valid string.
        AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
        if (resource == null) {
            logger.trace("The WebSocket has been closed before the message was processed.");
            return null;
        }

        AtmosphereRequest request = resource.getRequest(false);

        if (!resource.isInScope()) return Collections.emptyList();

        List<AtmosphereRequest> list = new ArrayList<AtmosphereRequest>();
        list.add(constructRequest(resource, request.getPathInfo(), request.getRequestURI(), methodType, contentType.equalsIgnoreCase(TEXT) ? null : contentType, destroyable).body(d, offset, length).build());

        return list;
View Full Code Here

    }

    @Override
    public List<AtmosphereRequest> onTextStream(WebSocket webSocket, Reader r) {
        //Converting to a string and delegating to onMessage(WebSocket webSocket, String d) causes issues because the binary data may not be a valid string.
        AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
        if (resource == null) {
            logger.trace("The WebSocket has been closed before the message was processed.");
            return null;
        }

        AtmosphereRequest request = resource.getRequest();
        List<AtmosphereRequest> list = new ArrayList<AtmosphereRequest>();
        list.add(constructRequest(resource, request.getPathInfo(), request.getRequestURI(), methodType, contentType.equalsIgnoreCase(TEXT) ? null : contentType, destroyable).reader(r).build());

        return list;
    }
View Full Code Here

    }

    @Override
    public List<AtmosphereRequest> onBinaryStream(WebSocket webSocket, InputStream stream) {
        //Converting to a string and delegating to onMessage(WebSocket webSocket, String d) causes issues because the binary data may not be a valid string.
        AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
        if (resource == null) {
            logger.trace("The WebSocket has been closed before the message was processed.");
            return null;
        }

        AtmosphereRequest request = resource.getRequest();
        List<AtmosphereRequest> list = new ArrayList<AtmosphereRequest>();
        list.add(constructRequest(resource, request.getPathInfo(), request.getRequestURI(), methodType, contentType.equalsIgnoreCase(TEXT) ? null : contentType, destroyable).inputStream(stream).build());

        return list;
    }
View Full Code Here

            }
        }
    }

    private WebSocketHandlerProxy webSocketHandlerForMessage(WebSocket webSocket) {
        AtmosphereResourceImpl impl = AtmosphereResourceImpl.class.cast(webSocket.resource());
        if (impl != null) {
            impl.getRequest(false).setAttribute(FrameworkConfig.WEBSOCKET_MESSAGE, "true");
        }
        return WebSocketHandlerProxy.class.cast(webSocket.webSocketHandler());
    }
View Full Code Here

    }

    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));
        }

        // Globally defined
        int tracing = 0;
        Action a = asynchronousProcessor.invokeInterceptors(framework.interceptors(), resource, tracing);
        if (a.type() != Action.TYPE.CONTINUE && a.type() != Action.TYPE.SKIP_ATMOSPHEREHANDLER) {
            return;
        }

        WebSocketHandlerProxy proxy = WebSocketHandlerProxy.class.cast(webSocketHandler);
        if (a.type() != Action.TYPE.SKIP_ATMOSPHEREHANDLER) {
            // Per AtmosphereHandler
            a = asynchronousProcessor.invokeInterceptors(proxy.interceptors(), resource, tracing);
            if (a.type() != Action.TYPE.CONTINUE) {
                return;
            }
        }

        //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;
            }
            asynchronousProcessor.postInterceptors(proxy.interceptors(), resource);
        }
        request.setAttribute(SKIP_ATMOSPHEREHANDLER.name(), Boolean.FALSE);
View Full Code Here

        // 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()) {
                    // See https://github.com/Atmosphere/atmosphere/issues/1590
                    // 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);
                        } else {
                            executeClose(webSocket, closeCode);
                        }
                    } else {
                        logger.debug("Timeout {}", resource.uuid());
                        asynchronousProcessor.endRequest(AtmosphereResourceImpl.class.cast(webSocket.resource()), false);
                    }
                } else {
                    logger.debug("Unable to properly complete {}", resource == null ? "null" : resource.uuid());
                    completeLifecycle = false;
                }
            } finally {
                if (completeLifecycle) {
                    finish(webSocket, resource, r, s, !allowedToClose);
View Full Code Here

    @Override
    public void notifyListener(WebSocket webSocket, WebSocketEventListener.WebSocketEvent event) {
        AtmosphereResource resource = webSocket.resource();
        if (resource == null) return;

        AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(resource);
        for (AtmosphereResourceEventListener l : r.atmosphereResourceEventListener()) {
            if (WebSocketEventListener.class.isAssignableFrom(l.getClass())) {
                try {
                    switch (event.type()) {
                        case CONNECT:
                            WebSocketEventListener.class.cast(l).onConnect(event);
                            break;
                        case DISCONNECT:
                            WebSocketEventListener.class.cast(l).onDisconnect(event);
                            break;
                        case CONTROL:
                            WebSocketEventListener.class.cast(l).onControl(event);
                            break;
                        case MESSAGE:
                            WebSocketEventListener.class.cast(l).onMessage(event);
                            break;
                        case HANDSHAKE:
                            WebSocketEventListener.class.cast(l).onHandshake(event);
                            break;
                        case CLOSE:
                            boolean isClosedByClient = r.getAtmosphereResourceEvent().isClosedByClient();
                            l.onDisconnect(new AtmosphereResourceEventImpl(r, !isClosedByClient, false, isClosedByClient, null));
                            WebSocketEventListener.class.cast(l).onDisconnect(event);
                            WebSocketEventListener.class.cast(l).onClose(event);
                            break;
                    }
                } catch (Throwable t) {
                    logger.debug("Listener error {}", t);
                    try {
                        WebSocketEventListener.class.cast(l).onThrowable(new AtmosphereResourceEventImpl(r, false, false, t));
                    } catch (Throwable t2) {
                        logger.warn("Listener error {}", t2);
                    }
                }
            } else {
                switch (event.type()) {
                    case CLOSE:
                        boolean isClosedByClient = r.getAtmosphereResourceEvent().isClosedByClient();
                        l.onDisconnect(new AtmosphereResourceEventImpl(r, !isClosedByClient, false, isClosedByClient, null));
                        break;
                }
            }
        }
View Full Code Here

    @Override
    public void postInspect(final AtmosphereResource r) {

        if (r.transport().equals(UNDEFINED) || Utils.webSocketMessage(r) || r.transport().equals(POLLING)) return;

        AtmosphereResourceImpl impl = AtmosphereResourceImpl.class.cast(r);
        if ( (force || impl.getRequest(false).getMethod().equalsIgnoreCase(method))
            && !impl.action().equals(Action.CANCELLED)
            && impl.isInScope()) {

            logger.trace("Marking AtmosphereResource {} for suspend operation", r.uuid());
            r.addEventListener(new OnBroadcast() {
                @Override
                public void onBroadcast(AtmosphereResourceEvent event) {
View Full Code Here

TOP

Related Classes of org.atmosphere.cpr.AtmosphereResourceImpl

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.