Search in sources :

Example 46 with AtmosphereRequest

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

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

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

the class ManagedAtmosphereHandler method message.

private MethodInfo.EncoderObject message(AtmosphereResource resource, Object o) {
    AtmosphereRequest request = AtmosphereResourceImpl.class.cast(resource).getRequest(false);
    try {
        for (MethodInfo m : onRuntimeMethod) {
            if (m.useReader) {
                o = request.getReader();
            } else if (m.useStream) {
                o = request.getInputStream();
            } else if (o == null) {
                o = readEntirely(resource);
                if (isBodyEmpty(o)) {
                    logger.warn("{} received an empty body", request);
                    return null;
                }
            }
            Object decoded = Invoker.decode(decoders.get(m.method), o);
            if (decoded == null) {
                decoded = o;
            }
            Object objectToEncode = null;
            if (m.method.getParameterTypes().length > 2) {
                logger.warn("Injection of more than 2 parameters not supported {}", m);
            }
            if (m.method.getParameterTypes().length == 2) {
                objectToEncode = Invoker.invokeMethod(m.method, proxiedInstance, resource, decoded);
            } else {
                objectToEncode = Invoker.invokeMethod(m.method, proxiedInstance, decoded);
            }
            if (objectToEncode != null) {
                return m.encode(encoders, objectToEncode);
            }
        }
    } catch (Throwable t) {
        logger.error("", t);
    }
    return null;
}
Also used : AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl)

Example 49 with AtmosphereRequest

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

the class AbstractReflectorAtmosphereHandler method onStateChange.

/**
     * Write the {@link AtmosphereResourceEvent#getMessage()} back to the client using
     * the {@link AtmosphereResponseImpl#getOutputStream()} or {@link AtmosphereResponseImpl#getWriter()}.
     * If a {@link org.atmosphere.runtime.Serializer} is defined, it will be invoked and the write operation
     * will be delegated to it.
     * <p/>
     * By default, this method will try to use {@link AtmosphereResponseImpl#getWriter()}.
     *
     * @param event the {@link AtmosphereResourceEvent#getMessage()}
     * @throws java.io.IOException
     */
@Override
public void onStateChange(AtmosphereResourceEvent event) throws IOException {
    Object message = event.getMessage();
    AtmosphereResource resource = event.getResource();
    AtmosphereResponse r = resource.getResponse();
    AtmosphereRequest request = resource.getRequest();
    boolean writeAsBytes = IOUtils.isBodyBinary(request);
    if (message == null) {
        logger.trace("Message was null for AtmosphereEvent {}", event);
        return;
    }
    if (resource.getSerializer() != null) {
        try {
            if (message instanceof List) {
                for (Object s : (List<Object>) message) {
                    resource.getSerializer().write(resource.getResponse().getOutputStream(), s);
                }
            } else {
                resource.getSerializer().write(resource.getResponse().getOutputStream(), message);
            }
        } catch (Throwable ex) {
            logger.warn("Serializer exception: message: {}", message, ex);
            throw new IOException(ex);
        }
    } else {
        boolean isUsingStream = true;
        Object o = resource.getRequest().getAttribute(PROPERTY_USE_STREAM);
        if (o != null) {
            isUsingStream = (Boolean) o;
        }
        if (!isUsingStream) {
            try {
                r.getWriter();
            } catch (IllegalStateException e) {
                isUsingStream = true;
            }
            if (writeAsBytes) {
                throw new IllegalStateException("Cannot write bytes using PrintWriter");
            }
        }
        if (message instanceof List) {
            Iterator<Object> i = ((List) message).iterator();
            try {
                Object s;
                while (i.hasNext()) {
                    s = i.next();
                    if (String.class.isAssignableFrom(s.getClass())) {
                        if (isUsingStream) {
                            r.getOutputStream().write(s.toString().getBytes(r.getCharacterEncoding()));
                        } else {
                            r.getWriter().write(s.toString());
                        }
                    } else if (byte[].class.isAssignableFrom(s.getClass())) {
                        if (isUsingStream) {
                            r.getOutputStream().write((byte[]) s);
                        } else {
                            r.getWriter().write(s.toString());
                        }
                    } else {
                        if (isUsingStream) {
                            r.getOutputStream().write(s.toString().getBytes(r.getCharacterEncoding()));
                        } else {
                            r.getWriter().write(s.toString());
                        }
                    }
                    i.remove();
                }
            } catch (IOException ex) {
                event.setMessage(new ArrayList<String>().addAll((List) message));
                throw ex;
            }
            if (isUsingStream) {
                r.getOutputStream().flush();
            } else {
                r.getWriter().flush();
            }
        } else {
            if (isUsingStream) {
                r.getOutputStream().write(writeAsBytes ? (byte[]) message : message.toString().getBytes(r.getCharacterEncoding()));
                r.getOutputStream().flush();
            } else {
                r.getWriter().write(message.toString());
                r.getWriter().flush();
            }
        }
    }
    postStateChange(event);
}
Also used : AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException)

Example 50 with AtmosphereRequest

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

the class TrackMessageSizeFilter method filter.

@Override
public BroadcastAction filter(String broadcasterId, AtmosphereResource r, Object originalMessage, Object message) {
    AtmosphereRequest request = r.getRequest();
    if (r.uuid().equals(BroadcastFilter.VOID_ATMOSPHERE_RESOURCE_UUID) || "true".equalsIgnoreCase(request.getHeader(X_ATMOSPHERE_TRACKMESSAGESIZE)) && message != null && String.class.isAssignableFrom(message.getClass())) {
        String msg = message.toString().trim();
        msg = msg.length() + "|" + msg;
        return new BroadcastAction(BroadcastAction.ACTION.CONTINUE, msg);
    }
    return new BroadcastAction(BroadcastAction.ACTION.CONTINUE, message);
}
Also used : AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest)

Aggregations

AtmosphereRequest (org.atmosphere.runtime.AtmosphereRequest)76 Test (org.testng.annotations.Test)39 AtmosphereRequestImpl (org.atmosphere.runtime.AtmosphereRequestImpl)38 IOException (java.io.IOException)23 AtmosphereResourceImpl (org.atmosphere.runtime.AtmosphereResourceImpl)20 AtmosphereResponse (org.atmosphere.runtime.AtmosphereResponse)18 ServletException (javax.servlet.ServletException)10 AsynchronousProcessor (org.atmosphere.runtime.AsynchronousProcessor)8 AtmosphereFramework (org.atmosphere.runtime.AtmosphereFramework)7 AtmosphereResource (org.atmosphere.runtime.AtmosphereResource)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 AsyncIOWriter (org.atmosphere.runtime.AsyncIOWriter)6 SimpleBroadcaster (org.atmosphere.util.SimpleBroadcaster)6 BeforeMethod (org.testng.annotations.BeforeMethod)6 ArrayList (java.util.ArrayList)5 AtmosphereInterceptorWriter (org.atmosphere.runtime.AtmosphereInterceptorWriter)5 AtmosphereResourceEvent (org.atmosphere.runtime.AtmosphereResourceEvent)5 Reader (java.io.Reader)4 Enumeration (java.util.Enumeration)4 ServletConfig (javax.servlet.ServletConfig)4