Search in sources :

Example 1 with AtmosphereRequest

use of org.atmosphere.cpr.AtmosphereRequest in project cxf by apache.

the class DefaultProtocolInterceptor method inspect.

@Override
public Action inspect(final AtmosphereResource r) {
    LOG.log(Level.FINE, "inspect");
    if (AtmosphereResource.TRANSPORT.WEBSOCKET != r.transport() && AtmosphereResource.TRANSPORT.SSE != r.transport() && AtmosphereResource.TRANSPORT.POLLING != r.transport()) {
        LOG.fine("Skipping ignorable 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.fine("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.log(Level.FINE, "Registrering suspended resource: {}", srid);
            suspendedResponses.put(srid, event.getResource().getResponse());
            AsyncIOWriter writer = event.getResource().getResponse().getAsyncIOWriter();
            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.log(Level.FINE, "Unregistrering suspended resource: {}", srid);
            suspendedResponses.remove(srid);
        }
    });
    AtmosphereRequest request = r.getRequest();
    if (request.getAttribute(REQUEST_DISPATCHED) == null) {
        AtmosphereResponse response = null;
        AtmosphereFramework framework = r.getAtmosphereConfig().framework();
        try {
            byte[] data = WebSocketUtils.readBody(request.getInputStream());
            if (data.length == 0) {
                if (AtmosphereResource.TRANSPORT.WEBSOCKET == r.transport() || AtmosphereResource.TRANSPORT.SSE == r.transport()) {
                    r.suspend();
                    return Action.SUSPEND;
                }
                return Action.CANCELLED;
            }
            if (LOG.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "inspecting data {0}", new String(data));
            }
            try {
                AtmosphereRequest ar = createAtmosphereRequest(request, data);
                response = new WrappedAtmosphereResponse(r.getResponse(), ar);
                ar.localAttributes().put(REQUEST_DISPATCHED, "true");
                String refid = ar.getHeader(WebSocketConstants.DEFAULT_REQUEST_ID_KEY);
                if (refid != null) {
                    ar.localAttributes().put(WebSocketConstants.DEFAULT_REQUEST_ID_KEY, refid);
                }
                // This is a new request, we must clean the Websocket AtmosphereResource.
                request.removeAttribute(FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE);
                response.request(ar);
                attachWriter(r);
                Action action = framework.doCometSupport(ar, response);
                if (action.type() == Action.TYPE.SUSPEND) {
                    ar.destroyable(false);
                    response.destroyable(false);
                }
            } catch (Exception e) {
                LOG.log(Level.WARNING, "Error during request dispatching", e);
                if (response == null) {
                    response = new WrappedAtmosphereResponse(r.getResponse(), request);
                }
                if (e instanceof InvalidPathException) {
                    response.setIntHeader(WebSocketUtils.SC_KEY, 400);
                } else {
                    response.setIntHeader(WebSocketUtils.SC_KEY, 500);
                }
                OutputStream out = response.getOutputStream();
                out.write(createResponse(response, null, true));
                out.close();
            }
            return Action.CANCELLED;
        } catch (IOException e) {
            LOG.log(Level.WARNING, "Error during protocol processing", e);
        }
    } else {
        request.destroyable(false);
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) Action(org.atmosphere.cpr.Action) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) AsyncIOWriter(org.atmosphere.cpr.AsyncIOWriter) IOException(java.io.IOException) InvalidPathException(org.apache.cxf.transport.websocket.InvalidPathException) IOException(java.io.IOException) InvalidPathException(org.apache.cxf.transport.websocket.InvalidPathException) AtmosphereResourceEventListenerAdapter(org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereFramework(org.atmosphere.cpr.AtmosphereFramework) AtmosphereResourceEvent(org.atmosphere.cpr.AtmosphereResourceEvent) AtmosphereInterceptorWriter(org.atmosphere.cpr.AtmosphereInterceptorWriter)

Example 2 with AtmosphereRequest

use of org.atmosphere.cpr.AtmosphereRequest in project cxf by apache.

the class DefaultProtocolInterceptor method createAtmosphereRequest.

/**
 * Creates a virtual request using the specified parent request and the actual data.
 *
 * @param r
 * @param data
 * @return
 * @throws IOException
 */
protected AtmosphereRequest createAtmosphereRequest(AtmosphereRequest r, byte[] data) throws IOException {
    AtmosphereRequest.Builder b = new AtmosphereRequestImpl.Builder();
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    Map<String, String> hdrs = WebSocketUtils.readHeaders(in);
    String path = hdrs.get(WebSocketUtils.URI_KEY);
    String origin = r.getRequestURI();
    if (!path.startsWith(origin)) {
        LOG.log(Level.WARNING, "invalid path: {0} not within {1}", new Object[] { path, origin });
        throw new InvalidPathException();
    }
    String requestURI = path;
    String requestURL = r.getRequestURL() + requestURI.substring(r.getRequestURI().length());
    String contentType = hdrs.get("Content-Type");
    String method = hdrs.get(WebSocketUtils.METHOD_KEY);
    b.pathInfo(path).contentType(contentType).headers(hdrs).method(method).requestURI(requestURI).requestURL(requestURL).request(r);
    // add the body only if it is present
    byte[] body = WebSocketUtils.readBody(in);
    if (body.length > 0) {
        b.body(body);
    }
    return b.build();
}
Also used : AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) InvalidPathException(org.apache.cxf.transport.websocket.InvalidPathException)

Example 3 with AtmosphereRequest

use of org.atmosphere.cpr.AtmosphereRequest in project atmosphere-play by Atmosphere.

the class AtmosphereUtils method request.

public static final AtmosphereRequest request(final Http.Request request, final Map<String, Object> additionalAttributes) throws Throwable {
    final String base = getBaseUri(request);
    final URI requestUri = new URI(base.substring(0, base.length() - 1) + request.uri());
    String ct = "text/plain";
    if (request.getHeader("Content-Type") != null) {
        ct = request.getHeader("Content-Type");
    }
    String method = request.method();
    String queryString = requestUri.getQuery();
    Map<String, String[]> qs = new HashMap<String, String[]>();
    if (queryString != null) {
        parseQueryString(qs, queryString);
    }
    if (ct.equalsIgnoreCase("application/x-www-form-urlencoded")) {
        parseQueryString(qs, request.body().asText());
    }
    String u = requestUri.toURL().toString();
    int last = u.indexOf("?") == -1 ? u.length() : u.indexOf("?");
    String url = u.substring(0, last);
    int l = requestUri.getAuthority().length() + requestUri.getScheme().length() + 3;
    final Map<String, Object> attributes = new HashMap<String, Object>(additionalAttributes);
    boolean hasBody = request.body() != null;
    byte[] body = {};
    // TODO: char encoding issue, needs to decode from content-type.
    if (hasBody) {
        if (request.body().asText() != null) {
            body = request.body().asText().getBytes("utf-8");
        } else if (request.body().asRaw() != null) {
            body = request.body().asBytes().toArray();
        } else if (request.body().asJson() != null) {
            body = request.body().asJson().asText().getBytes("utf-8");
            if (body.length == 0) {
                body = request.body().asJson().toString().getBytes("utf-8");
            }
        } else if (request.body().asXml() != null) {
            body = request.body().asXml().getTextContent().getBytes("utf-8");
        }
    }
    URI uri = null;
    try {
        URI.create(request.remoteAddress());
    } catch (IllegalArgumentException e) {
        logger.trace("", e);
    }
    int port = uri == null ? 0 : uri.getPort();
    String uriString = uri == null ? request.remoteAddress() : uri.toString();
    String host = uri == null ? request.remoteAddress() : uri.getHost();
    AtmosphereRequest.Builder requestBuilder = new AtmosphereRequestImpl.Builder();
    AtmosphereRequest r = requestBuilder.requestURI(url.substring(l)).requestURL(u).pathInfo(url.substring(l)).headers(getHeaders(request)).method(method).contentType(ct).destroyable(false).attributes(attributes).servletPath("").queryStrings(qs).remotePort(port).remoteAddr(uriString).remoteHost(host).inputStream(hasBody ? new ByteArrayInputStream(body) : new ByteArrayInputStream(new byte[] {})).build();
    return r;
}
Also used : HashMap(java.util.HashMap) URI(java.net.URI) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 4 with AtmosphereRequest

use of org.atmosphere.cpr.AtmosphereRequest in project cxf by apache.

the class DefaultProtocolInterceptor method createResponse.

/**
 * Creates a response data based on the specified payload.
 *
 * @param response
 * @param payload
 * @param parent
 * @return
 */
protected byte[] createResponse(AtmosphereResponse response, byte[] payload, boolean parent) {
    AtmosphereRequest request = response.request();
    String refid = (String) request.getAttribute(WebSocketConstants.DEFAULT_REQUEST_ID_KEY);
    if (AtmosphereResource.TRANSPORT.WEBSOCKET != response.resource().transport()) {
        return payload;
    }
    Map<String, String> headers = new HashMap<>();
    if (refid != null) {
        response.addHeader(WebSocketConstants.DEFAULT_RESPONSE_ID_KEY, refid);
        headers.put(WebSocketConstants.DEFAULT_RESPONSE_ID_KEY, refid);
    }
    if (parent) {
        // include the status code and content-type and those matched headers
        String sc = response.getHeader(WebSocketUtils.SC_KEY);
        if (sc == null) {
            sc = Integer.toString(response.getStatus());
        }
        headers.put(WebSocketUtils.SC_KEY, sc);
        if (payload != null && payload.length > 0) {
            headers.put("Content-Type", response.getContentType());
        }
        for (Map.Entry<String, String> hv : response.headers().entrySet()) {
            if (!"Content-Type".equalsIgnoreCase(hv.getKey()) && includedheaders != null && includedheaders.matcher(hv.getKey()).matches() && !(excludedheaders != null && excludedheaders.matcher(hv.getKey()).matches())) {
                headers.put(hv.getKey(), hv.getValue());
            }
        }
    }
    return WebSocketUtils.buildResponse(headers, payload, 0, payload == null ? 0 : payload.length);
}
Also used : AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with AtmosphereRequest

use of org.atmosphere.cpr.AtmosphereRequest in project cxf by apache.

the class DefaultProtocolInterceptorTest method testCreateResponseWithHeadersFiltering.

@Test
public void testCreateResponseWithHeadersFiltering() throws Exception {
    DefaultProtocolInterceptor dpi = new DefaultProtocolInterceptor();
    AtmosphereRequest request = AtmosphereRequestImpl.newInstance();
    AtmosphereResponse response = AtmosphereResponseImpl.newInstance();
    AtmosphereResourceImpl resource = new AtmosphereResourceImpl();
    resource.transport(AtmosphereResource.TRANSPORT.WEBSOCKET);
    request.localAttributes().put(FrameworkConfig.ATMOSPHERE_RESOURCE, resource);
    response.request(request);
    String payload = "hello cxf";
    String contentType = "text/plain";
    response.headers().put("Content-Type", contentType);
    byte[] transformed = dpi.createResponse(response, payload.getBytes(), true);
    verifyTransformed("200", new String[] { "Content-Type", contentType }, payload, transformed);
    response.headers().put("X-fruit", "peach");
    response.headers().put("X-vegetable", "tomato");
    transformed = dpi.createResponse(response, payload.getBytes(), true);
    verifyTransformed("200", new String[] { "Content-Type", contentType }, payload, transformed);
    dpi.includedheaders("X-f.*");
    transformed = dpi.createResponse(response, payload.getBytes(), true);
    verifyTransformed("200", new String[] { "Content-Type", contentType, "X-Fruit", "peach" }, payload, transformed);
    dpi.includedheaders("X-.*");
    transformed = dpi.createResponse(response, payload.getBytes(), true);
    verifyTransformed("200", new String[] { "Content-Type", contentType, "X-Fruit", "peach", "X-vegetable", "tomato" }, payload, transformed);
    dpi.excludedheaders(".*able");
    transformed = dpi.createResponse(response, payload.getBytes(), true);
    verifyTransformed("200", new String[] { "Content-Type", contentType, "X-Fruit", "peach" }, payload, transformed);
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResourceImpl(org.atmosphere.cpr.AtmosphereResourceImpl) Test(org.junit.Test)

Aggregations

AtmosphereRequest (org.atmosphere.cpr.AtmosphereRequest)6 AtmosphereResponse (org.atmosphere.cpr.AtmosphereResponse)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 InvalidPathException (org.apache.cxf.transport.websocket.InvalidPathException)2 AsyncIOWriter (org.atmosphere.cpr.AsyncIOWriter)2 AtmosphereInterceptorWriter (org.atmosphere.cpr.AtmosphereInterceptorWriter)2 OutputStream (java.io.OutputStream)1 URI (java.net.URI)1 Map (java.util.Map)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 CachedOutputStream (org.apache.cxf.io.CachedOutputStream)1 Action (org.atmosphere.cpr.Action)1 AsyncIOInterceptorAdapter (org.atmosphere.cpr.AsyncIOInterceptorAdapter)1 AtmosphereFramework (org.atmosphere.cpr.AtmosphereFramework)1 AtmosphereResourceEvent (org.atmosphere.cpr.AtmosphereResourceEvent)1 AtmosphereResourceEventListenerAdapter (org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter)1 AtmosphereResourceImpl (org.atmosphere.cpr.AtmosphereResourceImpl)1 Test (org.junit.Test)1