org.atmosphere.cpr.AtmosphereRequest Java Examples

The following examples show how to use org.atmosphere.cpr.AtmosphereRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PushAtmosphereHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public void onRequest(AtmosphereResource resource) {
    if (pushHandler == null) {
        getLogger().warn(
                "AtmosphereHandler.onRequest called before PushHandler has been set. This should really not happen");
        return;
    }

    AtmosphereRequest req = resource.getRequest();

    if (req.getMethod().equalsIgnoreCase("GET")) {
        onConnect(resource);
    } else if (req.getMethod().equalsIgnoreCase("POST")) {
        onMessage(resource);
    }
}
 
Example #2
Source File: PushHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void onConnect_productionMode_websocket_refreshConnection_delegteCallWithUI()
        throws ServiceException {
    MockVaadinServletService service = Mockito
            .spy(MockVaadinServletService.class);
    MockDeploymentConfiguration deploymentConfiguration = (MockDeploymentConfiguration) service
            .getDeploymentConfiguration();
    deploymentConfiguration.setProductionMode(true);
    runTest(service, (handler, resource) -> {
        AtmosphereRequest request = resource.getRequest();
        Mockito.when(request
                .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION))
                .thenReturn("");
        Mockito.when(resource.transport()).thenReturn(TRANSPORT.WEBSOCKET);
        handler.onConnect(resource);
    });
    Mockito.verify(service).requestStart(Mockito.any(), Mockito.any());
}
 
Example #3
Source File: PushHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void onConnect_devMode_websocket_noRefreshConnection_delegteCallWithUI()
        throws ServiceException {
    MockVaadinServletService service = Mockito
            .spy(MockVaadinServletService.class);
    MockDeploymentConfiguration deploymentConfiguration = (MockDeploymentConfiguration) service
            .getDeploymentConfiguration();
    deploymentConfiguration.setProductionMode(false);
    runTest(service, (handler, resource) -> {
        AtmosphereRequest request = resource.getRequest();
        Mockito.when(request
                .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION))
                .thenReturn(null);
        Mockito.when(resource.transport()).thenReturn(TRANSPORT.WEBSOCKET);
        handler.onConnect(resource);
    });
    Mockito.verify(service).requestStart(Mockito.any(), Mockito.any());
}
 
Example #4
Source File: PushHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void onConnect_devMode_notWebsocket_refreshConnection_delegteCallWithUI()
        throws ServiceException, SessionExpiredException {
    MockVaadinServletService service = Mockito
            .spy(MockVaadinServletService.class);
    MockDeploymentConfiguration deploymentConfiguration = (MockDeploymentConfiguration) service
            .getDeploymentConfiguration();
    deploymentConfiguration.setProductionMode(false);
    runTest(service, (handler, resource) -> {
        AtmosphereRequest request = resource.getRequest();
        Mockito.when(request
                .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION))
                .thenReturn("");
        Mockito.when(resource.transport()).thenReturn(TRANSPORT.AJAX);
        handler.onConnect(resource);
    });
    Mockito.verify(service).findVaadinSession(Mockito.any());
}
 
Example #5
Source File: PushAtmosphereHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException {
    request = Mockito.mock(AtmosphereRequest.class);
    response = Mockito.mock(AtmosphereResponse.class);
    printWriter = Mockito.mock(PrintWriter.class);
    Mockito.when(response.getWriter()).thenReturn(printWriter);

    resource = Mockito.mock(AtmosphereResource.class);
    Mockito.when(resource.getRequest()).thenReturn(request);
    Mockito.when(resource.getResponse()).thenReturn(response);

    VaadinServletService service = new VaadinServletService(null,
            new DefaultDeploymentConfiguration(getClass(),
                    new Properties()));

    PushHandler handler = new PushHandler(service);

    atmosphereHandler = new PushAtmosphereHandler();
    atmosphereHandler.setPushHandler(handler);
}
 
Example #6
Source File: PushHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void onConnect_devMode_websocket_refreshConnection_onConnectIsCalled_callWithUIIsNotCalled()
        throws ServiceException {
    MockVaadinServletService service = Mockito
            .spy(MockVaadinServletService.class);
    MockDeploymentConfiguration deploymentConfiguration = (MockDeploymentConfiguration) service
            .getDeploymentConfiguration();
    deploymentConfiguration.setProductionMode(false);
    deploymentConfiguration.setDevModeLiveReloadEnabled(true);

    VaadinContext context = service.getContext();
    BrowserLiveReload liveReload = BrowserLiveReloadAccessTest
            .mockBrowserLiveReloadImpl(context);

    AtomicReference<AtmosphereResource> res = new AtomicReference<>();
    runTest(service, (handler, resource) -> {
        AtmosphereRequest request = resource.getRequest();
        Mockito.when(request
                .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION))
                .thenReturn("");
        Mockito.when(resource.transport()).thenReturn(TRANSPORT.WEBSOCKET);
        handler.onConnect(resource);
        res.set(resource);
    });
    Mockito.verify(service, Mockito.times(0)).requestStart(Mockito.any(),
            Mockito.any());
    Mockito.verify(liveReload).onConnect(res.get());
}
 
Example #7
Source File: PushHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void onMessage_devMode_websocket_refreshConnection_callWithUIIsNotCalled()
        throws ServiceException {
    MockVaadinServletService service = Mockito
            .spy(MockVaadinServletService.class);
    MockDeploymentConfiguration deploymentConfiguration = (MockDeploymentConfiguration) service
            .getDeploymentConfiguration();
    deploymentConfiguration.setProductionMode(false);
    deploymentConfiguration.setDevModeLiveReloadEnabled(true);

    VaadinContext context = service.getContext();
    BrowserLiveReload liveReload = BrowserLiveReloadAccessTest
            .mockBrowserLiveReloadImpl(context);

    AtomicReference<AtmosphereResource> res = new AtomicReference<>();
    runTest(service, (handler, resource) -> {
        AtmosphereRequest request = resource.getRequest();
        Mockito.when(request
                .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION))
                .thenReturn("");
        Mockito.when(resource.transport()).thenReturn(TRANSPORT.WEBSOCKET);
        handler.onMessage(resource);
        res.set(resource);
    });
    Mockito.verify(service, Mockito.times(0)).requestStart(Mockito.any(),
            Mockito.any());
}
 
Example #8
Source File: PushHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private VaadinServletService runTest(VaadinServletService service,
        BiConsumer<PushHandler, AtmosphereResource> testExec)
        throws ServiceException {
    service.init();
    PushHandler handler = new PushHandler(service);

    AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
    AtmosphereRequest request = Mockito.mock(AtmosphereRequest.class);
    Mockito.when(resource.getRequest()).thenReturn(request);

    testExec.accept(handler, resource);

    return service;
}
 
Example #9
Source File: DefaultProtocolInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * 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 queryString = "";
    int index = path.indexOf('?');
    if (index != -1) {
        queryString = path.substring(index + 1);
        path = path.substring(0, index);
    }

    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)
            .queryString(queryString)
            .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();
}
 
Example #10
Source File: DefaultProtocolInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #11
Source File: DefaultProtocolInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public byte[] transformPayload(AtmosphereResponse response, byte[] responseDraft, byte[] data)
    throws IOException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "transformPayload with draft={0}", new String(responseDraft));
    }
    AtmosphereRequest request = response.request();
    if (request.attributes().get(RESPONSE_PARENT) == null) {
        request.attributes().put(RESPONSE_PARENT, "true");
        return createResponse(response, responseDraft, true);
    }
    return createResponse(response, responseDraft, false);
}
 
Example #12
Source File: DefaultProtocolInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
WrappedAtmosphereResponse(AtmosphereResponse resp, AtmosphereRequest req) throws IOException {
    super((HttpServletResponse)resp.getResponse(), null, req, resp.isDestroyable());
    response = resp;
    response.request(req);
}
 
Example #13
Source File: DefaultProtocolInterceptorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@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);
}