Search in sources :

Example 6 with AtmosphereResourceEvent

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

the class SimpleRestInterceptor method inspect.

@Override
public Action inspect(final AtmosphereResource r) {
    if (AtmosphereResource.TRANSPORT.WEBSOCKET != r.transport() && AtmosphereResource.TRANSPORT.SSE != r.transport() && AtmosphereResource.TRANSPORT.POLLING != r.transport()) {
        LOG.debug("Skipping for non websocket request");
        return Action.CONTINUE;
    }
    if (AtmosphereResource.TRANSPORT.POLLING == r.transport()) {
        final String saruuid = (String) r.getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
        final AtmosphereResponse suspendedResponse = suspendedResponses.get(saruuid);
        LOG.debug("Attaching a proxy writer to suspended response");
        r.getResponse().asyncIOWriter(new AtmosphereInterceptorWriter() {

            @Override
            public AsyncIOWriter write(AtmosphereResponse r, String data) throws IOException {
                suspendedResponse.write(data);
                suspendedResponse.flushBuffer();
                return this;
            }

            @Override
            public AsyncIOWriter write(AtmosphereResponse r, byte[] data) throws IOException {
                suspendedResponse.write(data);
                suspendedResponse.flushBuffer();
                return this;
            }

            @Override
            public AsyncIOWriter write(AtmosphereResponse r, byte[] data, int offset, int length) throws IOException {
                suspendedResponse.write(data, offset, length);
                suspendedResponse.flushBuffer();
                return this;
            }

            @Override
            public void close(AtmosphereResponse response) throws IOException {
            }
        });
        // REVISIT we need to keep this response's asyncwriter alive so that data can be written to the
        //   suspended response, but investigate if there is a better alternative.
        r.getResponse().destroyable(false);
        return Action.CONTINUE;
    }
    r.addEventListener(new AtmosphereResourceEventListenerAdapter() {

        @Override
        public void onSuspend(AtmosphereResourceEvent event) {
            final String srid = (String) event.getResource().getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
            LOG.debug("Registrering suspended resource: {}", srid);
            suspendedResponses.put(srid, event.getResource().getResponse());
            AsyncIOWriter writer = event.getResource().getResponse().getAsyncIOWriter();
            if (writer == null) {
                writer = new AtmosphereInterceptorWriter();
                r.getResponse().asyncIOWriter(writer);
            }
            if (writer instanceof AtmosphereInterceptorWriter) {
                ((AtmosphereInterceptorWriter) writer).interceptor(interceptor);
            }
        }

        @Override
        public void onDisconnect(AtmosphereResourceEvent event) {
            super.onDisconnect(event);
            final String srid = (String) event.getResource().getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
            LOG.debug("Unregistrering suspended resource: {}", srid);
            suspendedResponses.remove(srid);
        }
    });
    AtmosphereRequest request = r.getRequest();
    if (request.getAttribute(REQUEST_DISPATCHED) == null) {
        try {
            //REVISIT use a more efficient approach for the detached mode (i.e.,avoid reading the message into a string)
            // read the message entity and dispatch a service call
            String body = IOUtils.readEntirelyAsString(r).toString();
            LOG.debug("Request message: '{}'", body);
            if (body.length() == 0) {
                //TODO we might want to move this heartbeat scheduling after the handshake phase (if that is added)
                if ((AtmosphereResource.TRANSPORT.WEBSOCKET == r.transport() || AtmosphereResource.TRANSPORT.SSE == r.transport()) && request.getAttribute(HEARTBEAT_SCHEDULED) == null) {
                    r.suspend();
                    scheduleHeartbeat(r);
                    request.setAttribute(HEARTBEAT_SCHEDULED, "true");
                    return Action.SUSPEND;
                }
                return Action.CANCELLED;
            }
            AtmosphereRequest ar = createAtmosphereRequest(request, body);
            if (ar == null) {
                return Action.CANCELLED;
            }
            AtmosphereResponse response = r.getResponse();
            ar.localAttributes().put(REQUEST_DISPATCHED, "true");
            request.removeAttribute(FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE);
            response.request(ar);
            attachWriter(r);
            Action action = r.getAtmosphereConfig().framework().doCometSupport(ar, response);
            if (action.type() == Action.TYPE.SUSPEND) {
                ar.destroyable(false);
                response.destroyable(false);
            }
            return Action.CANCELLED;
        } catch (IOException | ServletException e) {
            LOG.error("Failed to process", e);
        }
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) Action(org.atmosphere.runtime.Action) AsyncIOWriter(org.atmosphere.runtime.AsyncIOWriter) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) AtmosphereResourceEventListenerAdapter(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) AtmosphereInterceptorWriter(org.atmosphere.runtime.AtmosphereInterceptorWriter)

Example 7 with AtmosphereResourceEvent

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

the class SuspendTrackerInterceptor method inspect.

@Override
public Action inspect(final AtmosphereResource r) {
    if (Utils.webSocketMessage(r))
        return Action.CONTINUE;
    final AtmosphereRequest request = AtmosphereResourceImpl.class.cast(r).getRequest(false);
    boolean connecting = request.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID) != null && request.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID).equals("0");
    if (!connecting && !Utils.pollableTransport(r.transport())) {
        if (!trackedUUID.add(r.uuid())) {
            logger.trace("Blocking {} from suspend", r.uuid());
            AtmosphereResourceImpl.class.cast(r).disableSuspendEvent(true);
        }
        r.addEventListener(new AtmosphereResourceEventListenerAdapter() {

            @Override
            public void onDisconnect(AtmosphereResourceEvent event) {
                logger.trace("Untracking {}", r.uuid());
                trackedUUID.remove(r.uuid());
            }

            @Override
            public void onClose(AtmosphereResourceEvent event) {
                onDisconnect(event);
            }
        });
    }
    return Action.CONTINUE;
}
Also used : AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResourceEventListenerAdapter(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl)

Example 8 with AtmosphereResourceEvent

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

the class ManagedAtmosphereHandler method onRequest.

@Override
public void onRequest(final AtmosphereResource resource) throws IOException {
    AtmosphereRequest request = resource.getRequest();
    String method = request.getMethod();
    boolean polling = Utils.pollableTransport(resource.transport());
    boolean webSocketMessage = Utils.webSocketMessage(resource);
    if (!webSocketMessage && !polling) {
        if (onReadyMethod != null) {
            resource.addEventListener(new OnSuspend() {

                @Override
                public void onSuspend(AtmosphereResourceEvent event) {
                    processReady(event.getResource());
                    resource.removeEventListener(this);
                }
            });
        }
        if (onResumeMethod != null) {
            resource.addEventListener(new OnResume() {

                @Override
                public void onResume(AtmosphereResourceEvent event) {
                    invoke(onResumeMethod, event);
                    resource.removeEventListener(this);
                }
            });
        }
        resource.addEventListener(new OnClose() {

            @Override
            public void onClose(AtmosphereResourceEvent event) {
                invoke(onDisconnectMethod, event);
            }
        });
    }
    if (method.equalsIgnoreCase("get")) {
        invoke(onGetMethod, resource);
    } else if (method.equalsIgnoreCase("post")) {
        Object body = null;
        if (onPostMethod != null) {
            body = readEntirely(resource);
            if (body != null && String.class.isAssignableFrom(body.getClass())) {
                resource.getRequest().body((String) body);
            } else if (body != null) {
                resource.getRequest().body((byte[]) body);
            }
            invoke(onPostMethod, resource);
        }
        MethodInfo.EncoderObject e = message(resource, body);
        if (e != null && e.encodedObject != null) {
            AtmosphereResource r = resource;
            if (e.methodInfo.deliverTo == DeliverTo.DELIVER_TO.RESOURCE && !resource.transport().equals(AtmosphereResource.TRANSPORT.WEBSOCKET)) {
                r = resourcesFactory.find(resource.uuid());
            }
            IOUtils.deliver(new Managed(e.encodedObject), null, e.methodInfo.deliverTo, r);
        }
    } else if (method.equalsIgnoreCase("delete")) {
        invoke(onDeleteMethod, resource);
    } else if (method.equalsIgnoreCase("put")) {
        invoke(onPutMethod, resource);
    }
}
Also used : OnResume(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter.OnResume) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) OnSuspend(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter.OnSuspend) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) OnClose(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter.OnClose)

Example 9 with AtmosphereResourceEvent

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

the class AtmosphereResourceLifecycleInterceptor method postInspect.

@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) {
                switch(r.transport()) {
                    case JSONP:
                    case AJAX:
                    case LONG_POLLING:
                        break;
                    default:
                        try {
                            r.getResponse().flushBuffer();
                        } catch (IOException e) {
                            logger.trace("", e);
                        }
                        break;
                }
            }
        }).suspend(timeoutInMilli);
    }
}
Also used : OnBroadcast(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter.OnBroadcast) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) IOException(java.io.IOException)

Aggregations

AtmosphereResourceEvent (org.atmosphere.runtime.AtmosphereResourceEvent)9 AtmosphereResourceImpl (org.atmosphere.runtime.AtmosphereResourceImpl)6 AtmosphereRequest (org.atmosphere.runtime.AtmosphereRequest)5 IOException (java.io.IOException)4 AtmosphereResourceEventListenerAdapter (org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter)4 AtmosphereResource (org.atmosphere.runtime.AtmosphereResource)3 AtmosphereResponse (org.atmosphere.runtime.AtmosphereResponse)3 LinkedList (java.util.LinkedList)2 AsyncIOWriter (org.atmosphere.runtime.AsyncIOWriter)2 AtmosphereInterceptor (org.atmosphere.runtime.AtmosphereInterceptor)2 AtmosphereInterceptorWriter (org.atmosphere.runtime.AtmosphereInterceptorWriter)2 OnSuspend (org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter.OnSuspend)2 List (java.util.List)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 ServletException (javax.servlet.ServletException)1 AtmosphereService (org.atmosphere.config.service.AtmosphereService)1 ReflectorServletProcessor (org.atmosphere.handler.ReflectorServletProcessor)1 Action (org.atmosphere.runtime.Action)1