Search in sources :

Example 36 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource 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.cpr.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.cpr.AtmosphereResponse) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException)

Example 37 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource 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.cpr.AtmosphereResourceEventListenerAdapter.OnResume) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) OnSuspend(org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter.OnSuspend) AtmosphereResourceEvent(org.atmosphere.cpr.AtmosphereResourceEvent) OnClose(org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter.OnClose)

Aggregations

AtmosphereResource (org.atmosphere.cpr.AtmosphereResource)37 AtmosphereRequest (org.atmosphere.cpr.AtmosphereRequest)14 IOException (java.io.IOException)10 AtmosphereResourceImpl (org.atmosphere.cpr.AtmosphereResourceImpl)9 Broadcaster (org.atmosphere.cpr.Broadcaster)8 Test (org.junit.Test)7 UI (com.vaadin.flow.component.UI)5 SessionExpiredException (com.vaadin.flow.server.SessionExpiredException)4 VaadinServletRequest (com.vaadin.flow.server.VaadinServletRequest)4 VaadinSession (com.vaadin.flow.server.VaadinSession)4 InvalidUIDLSecurityKeyException (com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException)4 JsonException (elemental.json.JsonException)4 AsynchronousProcessor (org.atmosphere.cpr.AsynchronousProcessor)4 AtmosphereResourceEvent (org.atmosphere.cpr.AtmosphereResourceEvent)4 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)3 ServletException (jakarta.servlet.ServletException)3 HashSet (java.util.HashSet)3 Future (java.util.concurrent.Future)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 AtmosphereResourceEventImpl (org.atmosphere.cpr.AtmosphereResourceEventImpl)3