Search in sources :

Example 1 with AtmosphereRequest

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

the class SimpleRestInterceptor method createResponse.

protected byte[] createResponse(AtmosphereResponse response, byte[] payload) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("createResponse for payload {}", new String(payload));
    }
    AtmosphereRequest request = response.request();
    String id = (String) request.getAttribute(REQUEST_ID);
    if (id == null) {
        // control response such as heartbeat or plain responses
        return payload;
    }
    //TODO find a nicer way to build the response entity
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (id != null) {
        try {
            baos.write(RESPONSE_TEMPLATE_HEAD);
            baos.write(id.getBytes());
            if (isDetached(request)) {
                // <payload>
                if (isLastResponse(request, response)) {
                    baos.write(RESPONSE_TEMPLATE_BELLY_DETACHED);
                } else {
                    baos.write(RESPONSE_TEMPLATE_BELLY_CONTINUE_DETACHED);
                }
                baos.write(RESPONSE_TEMPLATE_TAIL);
                baos.write(RESPONSE_TEMPLATE_NEWLINE);
                baos.write(payload);
            } else {
                // {"id":..., "data": <payload>}
                boolean isobj = isJSONObject(payload);
                if (isLastResponse(request, response)) {
                    baos.write(RESPONSE_TEMPLATE_BELLY);
                } else {
                    baos.write(RESPONSE_TEMPLATE_BELLY_CONTINUE);
                }
                if (!isobj) {
                    baos.write(quote(payload));
                } else {
                    baos.write(payload);
                }
                baos.write(RESPONSE_TEMPLATE_TAIL);
            }
        } catch (IOException e) {
        //ignore as it can't happen
        }
    }
    return baos.toByteArray();
}
Also used : AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 2 with AtmosphereRequest

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

the class SimpleRestInterceptor method createAtmosphereRequest.

protected AtmosphereRequest createAtmosphereRequest(AtmosphereRequest request, String body) throws IOException {
    //REVISIT find a more efficient way to read and extract the message data
    JSONEnvelopeReader jer = new JSONEnvelopeReader(new StringReader(body));
    final String id = jer.getHeader("id");
    if (id != null) {
        request.localAttributes().put(REQUEST_ID, id);
    }
    boolean skip = false;
    final boolean continued = Boolean.valueOf(jer.getHeader("continue"));
    Reader reader = readerPool.getReader(id, false);
    if (reader != null) {
        skip = true;
    } else if (continued) {
        reader = readerPool.getReader(id, true);
    }
    if (skip) {
        // add the request data to the prevously dispatched request and skip dispatching a new one
        final Reader data = jer.getReader();
        if (data != null) {
            readerPool.addChunk(id, data, continued);
        }
        return null;
    } else {
        // prepare a new request for dispatching
        final String method = jer.getHeader("method");
        String path = jer.getHeader("path");
        final String type = jer.getHeader("type");
        final String accept = jer.getHeader("accept");
        AtmosphereRequest.Builder b = new AtmosphereRequestImpl.Builder();
        b.method(method != null ? method : "GET").pathInfo(path != null ? path : "/");
        if (accept != null) {
            Map<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
            headers.put("Accept", accept);
            b.headers(headers);
        }
        b.contentType(type);
        final int qpos = path.indexOf('?');
        if (qpos > 0) {
            b.queryString(path.substring(qpos + 1));
            path = path.substring(0, qpos);
        }
        final Reader data = jer.getReader();
        if (data != null) {
            if (reader != null) {
                b.reader(reader);
                readerPool.addChunk(id, data, true);
            } else {
                b.reader(data);
            }
        }
        String requestURL = request.getRequestURL() + path.substring(request.getRequestURI().length());
        b.requestURI(path).requestURL(requestURL).request(request);
        return b.build();
    }
}
Also used : AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) StringReader(java.io.StringReader) Reader(java.io.Reader) StringReader(java.io.StringReader) TreeMap(java.util.TreeMap)

Example 3 with AtmosphereRequest

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

the class BlockingIOCometSupport method complete.

@Override
public AsyncSupport complete(AtmosphereResourceImpl r) {
    AtmosphereRequest req = r.getRequest(false);
    CountDownLatch latch = null;
    if (req.getAttribute(LATCH) != null) {
        latch = (CountDownLatch) req.getAttribute(LATCH);
    }
    if (latch != null) {
        latch.countDown();
    } else if (req.getAttribute(AtmosphereResourceImpl.PRE_SUSPEND) == null) {
        logger.trace("Unable to resume the suspended connection");
    }
    return this;
}
Also used : AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 4 with AtmosphereRequest

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

the class CacheHeadersInterceptor method inspect.

@Override
public Action inspect(AtmosphereResource r) {
    if (Utils.webSocketMessage(r))
        return Action.CONTINUE;
    final AtmosphereResponse response = r.getResponse();
    final AtmosphereRequest request = r.getRequest();
    // For extension that aren't supporting this interceptor (like Jersey)
    request.setAttribute(ApplicationConfig.NO_CACHE_HEADERS, injectCacheHeaders);
    if (writeHeaders && injectCacheHeaders) {
        // Set to expire far in the past.
        response.setHeader(EXPIRES, "-1");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader(CACHE_CONTROL, "no-store, no-cache, must-revalidate");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader(PRAGMA, "no-cache");
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest)

Example 5 with AtmosphereRequest

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

the class HeartbeatInterceptor method inspect.

@Override
public Action inspect(final AtmosphereResource r) {
    final AtmosphereResourceImpl impl = AtmosphereResourceImpl.class.cast(r);
    final AtmosphereRequest request = impl.getRequest(false);
    final AtmosphereResponse response = impl.getResponse(false);
    // Check heartbeat
    if (clientHeartbeatFrequencyInSeconds > 0) {
        byte[] body = new byte[0];
        try {
            if (!request.getMethod().equalsIgnoreCase("GET")) {
                body = IOUtils.readEntirelyAsByte(r);
            }
        } catch (IOException e) {
            logger.warn("", e);
            cancelF(request);
            return Action.CONTINUE;
        }
        if (Arrays.equals(paddingBytes, body)) {
            // Dispatch an event to notify that a heartbeat has been intercepted
            // TODO: see https://github.com/Atmosphere/atmosphere/issues/1561
            final AtmosphereResourceEvent event = new HeartbeatAtmosphereResourceEvent(AtmosphereResourceImpl.class.cast(r));
            if (AtmosphereResourceHeartbeatEventListener.class.isAssignableFrom(r.getAtmosphereHandler().getClass())) {
                r.addEventListener(new AtmosphereResourceEventListenerAdapter.OnHeartbeat() {

                    @Override
                    public void onHeartbeat(AtmosphereResourceEvent event) {
                        AtmosphereResourceHeartbeatEventListener.class.cast(r.getAtmosphereHandler()).onHeartbeat(event);
                    }
                });
            }
            // Fire event
            r.notifyListeners(event);
            return Action.CANCELLED;
        }
        request.body(body);
    }
    if (Utils.webSocketMessage(r))
        return Action.CONTINUE;
    final int interval = extractHeartbeatInterval(impl);
    if (interval != 0) {
        if (!(Utils.pollableTransport(r.transport()) || r.transport() == AtmosphereResource.TRANSPORT.UNDEFINED)) {
            super.inspect(r);
            final boolean wasSuspended = r.isSuspended();
            // Otherwise, the listener will do the job
            if (wasSuspended) {
                clock(interval, r, request, response);
            }
            r.addEventListener(new Clock() {

                @Override
                public void onSuspend(AtmosphereResourceEvent event) {
                    // We did not clocked when this listener was added because connection was not already suspended
                    if (!wasSuspended) {
                        clock(interval, r, request, response);
                    }
                }

                @Override
                public void onResume(AtmosphereResourceEvent event) {
                    cancelF(request);
                }

                @Override
                public void onDisconnect(AtmosphereResourceEvent event) {
                    cancelF(request);
                }

                @Override
                public void onClose(AtmosphereResourceEvent event) {
                    cancelF(request);
                }
            });
        } else {
            return Action.CONTINUE;
        }
        final AsyncIOWriter writer = response.getAsyncIOWriter();
        if (!Utils.resumableTransport(r.transport()) && AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass()) && request.getAttribute(INTERCEPTOR_ADDED) == null) {
            AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() {

                @Override
                public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data) throws IOException {
                    cancelF(request);
                    return responseDraft;
                }

                @Override
                public void postPayload(final AtmosphereResponse response, byte[] data, int offset, int length) {
                    logger.trace("Scheduling heartbeat for {}", r.uuid());
                    clock(interval, r, request, response);
                }
            });
            request.setAttribute(INTERCEPTOR_ADDED, Boolean.TRUE);
        }
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.runtime.AtmosphereResponse) AsyncIOWriter(org.atmosphere.runtime.AsyncIOWriter) IOException(java.io.IOException) HeartbeatAtmosphereResourceEvent(org.atmosphere.runtime.HeartbeatAtmosphereResourceEvent) AtmosphereRequest(org.atmosphere.runtime.AtmosphereRequest) AtmosphereResourceEventListenerAdapter(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) HeartbeatAtmosphereResourceEvent(org.atmosphere.runtime.HeartbeatAtmosphereResourceEvent) AtmosphereInterceptorWriter(org.atmosphere.runtime.AtmosphereInterceptorWriter) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) AsyncIOInterceptorAdapter(org.atmosphere.runtime.AsyncIOInterceptorAdapter)

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