Search in sources :

Example 21 with AtmosphereResponse

use of org.atmosphere.cpr.AtmosphereResponse 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 22 with AtmosphereResponse

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

the class NettyCometSupport method complete.

@Override
public AsyncSupport<AtmosphereResourceImpl> complete(AtmosphereResourceImpl r) {
    try {
        AtmosphereResponse response = r.getResponse(false);
        AsyncIOWriter a = response.getAsyncIOWriter();
        if (a != null) {
            a.close(response);
        }
    } catch (IOException e) {
        logger.trace("", e);
    }
    return this;
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) AsyncIOWriter(org.atmosphere.cpr.AsyncIOWriter) IOException(java.io.IOException)

Example 23 with AtmosphereResponse

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

the class AndroidAtmosphereInterceptor method inspect.

@Override
public Action inspect(final AtmosphereResource r) {
    if (!r.transport().equals(TRANSPORT.STREAMING))
        return Action.CONTINUE;
    final AtmosphereResponse response = AtmosphereResourceImpl.class.cast(r).getResponse(false);
    String userAgent = AtmosphereResourceImpl.class.cast(r).getRequest(false).getHeader("User-Agent");
    if (userAgent != null && (userAgent.indexOf("Android 2.") != -1 || userAgent.indexOf("Android 3.") != -1)) {
        super.inspect(r);
        AsyncIOWriter writer = response.getAsyncIOWriter();
        if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
            AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() {

                @Override
                public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                    response.write(padding, true);
                }

                @Override
                public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                    response.write(padding, true);
                }
            });
        } else {
            logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName());
        }
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) AsyncIOWriter(org.atmosphere.cpr.AsyncIOWriter) AtmosphereInterceptorWriter(org.atmosphere.cpr.AtmosphereInterceptorWriter) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) AsyncIOInterceptorAdapter(org.atmosphere.cpr.AsyncIOInterceptorAdapter)

Example 24 with AtmosphereResponse

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

the class CorsInterceptor method inspect.

@Override
public Action inspect(AtmosphereResource r) {
    if (Utils.webSocketMessage(r))
        return Action.CONTINUE;
    if (!enableAccessControl)
        return Action.CONTINUE;
    AtmosphereRequest req = r.getRequest();
    AtmosphereResponse res = r.getResponse();
    if (req.getHeader("Origin") != null && res.getHeader("Access-Control-Allow-Origin") == null) {
        res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        res.addHeader("Access-Control-Expose-Headers", EXPOSE_HEADERS);
        res.setHeader("Access-Control-Allow-Credentials", "true");
    }
    if ("OPTIONS".equals(req.getMethod())) {
        res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST");
        res.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, AuthToken, X-Atmosphere-Framework, X-Requested-With, " + EXPOSE_HEADERS + ", X-Atmosphere-Transport, X-Atmosphere-TrackMessageSize, X-atmo-protocol");
        res.setHeader("Access-Control-Max-Age", "-1");
        return Action.SKIP_ATMOSPHEREHANDLER;
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest)

Example 25 with AtmosphereResponse

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

the class JSONPAtmosphereInterceptor method inspect.

@Override
public Action inspect(AtmosphereResource r) {
    if (Utils.webSocketMessage(r))
        return Action.CONTINUE;
    final AtmosphereRequest request = r.getRequest();
    final AtmosphereResponse response = r.getResponse();
    // Shield from Broken server
    String uri = request.getRequestURI() == null ? "" : request.getRequestURI();
    final boolean contain = uri.contains("jsonp");
    if (r.transport().equals(AtmosphereResource.TRANSPORT.JSONP) || contain) {
        super.inspect(r);
        if (contain) {
            startChunk = "(\"";
            endChunk = "\");\r\n\r\n";
        }
        response.setContentType(CONTENT_TYPE);
        AsyncIOWriter writer = response.getAsyncIOWriter();
        if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
            AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() {

                String callbackName() {
                    String callback = escapeForJavaScript(request.getParameter(HeaderConfig.JSONP_CALLBACK_NAME)).replaceAll(PATTERN, "");
                    if (!callback.isEmpty()) {
                        // Look for extension
                        String jsonp = escapeForJavaScript((String) config.properties().get(HeaderConfig.JSONP_CALLBACK_NAME)).replaceAll(PATTERN, "");
                        if (!jsonp.isEmpty()) {
                            callback = request.getParameter(jsonp);
                        }
                    }
                    return callback;
                }

                @Override
                public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                    String callbackName = callbackName();
                    response.write(callbackName + startChunk);
                }

                @Override
                public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data) throws IOException {
                    String charEncoding = response.getCharacterEncoding() == null ? "UTF-8" : response.getCharacterEncoding();
                    return escapeForJavaScript(new String(responseDraft, charEncoding)).getBytes(charEncoding);
                }

                @Override
                public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) {
                    response.write(endChunk, true);
                }
            });
        } else {
            logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName());
        }
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AsyncIOWriter(org.atmosphere.cpr.AsyncIOWriter) AtmosphereInterceptorWriter(org.atmosphere.cpr.AtmosphereInterceptorWriter) IOException(java.io.IOException) AsyncIOInterceptorAdapter(org.atmosphere.cpr.AsyncIOInterceptorAdapter)

Aggregations

AtmosphereResponse (org.atmosphere.cpr.AtmosphereResponse)29 AtmosphereRequest (org.atmosphere.cpr.AtmosphereRequest)21 IOException (java.io.IOException)19 AsyncIOWriter (org.atmosphere.cpr.AsyncIOWriter)12 AtmosphereResourceImpl (org.atmosphere.cpr.AtmosphereResourceImpl)12 AtmosphereInterceptorWriter (org.atmosphere.cpr.AtmosphereInterceptorWriter)10 ServletException (jakarta.servlet.ServletException)9 AsynchronousProcessor (org.atmosphere.cpr.AsynchronousProcessor)7 AtmosphereFramework (org.atmosphere.cpr.AtmosphereFramework)7 BeforeMethod (org.testng.annotations.BeforeMethod)6 AsyncIOInterceptorAdapter (org.atmosphere.cpr.AsyncIOInterceptorAdapter)5 SimpleBroadcaster (org.atmosphere.util.SimpleBroadcaster)5 ServletConfig (jakarta.servlet.ServletConfig)4 ServletContext (jakarta.servlet.ServletContext)4 Enumeration (java.util.Enumeration)4 Action (org.atmosphere.cpr.Action)4 AtmosphereResource (org.atmosphere.cpr.AtmosphereResource)3 AtmosphereResourceEvent (org.atmosphere.cpr.AtmosphereResourceEvent)3 Test (org.testng.annotations.Test)3 List (java.util.List)2