org.atmosphere.cpr.AtmosphereResource Java Examples

The following examples show how to use org.atmosphere.cpr.AtmosphereResource. 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: SocketIOHandler.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void onDisconnect(AtmosphereResource r, SocketIOSessionOutbound outbound, DisconnectReason reason) {
    log.debug("ondisconnect, reason is :" + reason);

    String sessionId = outbound.getSessionId();

    Collection<String> termIds = sessions.get(sessionId);

    for (String termId : termIds) {
        String key = makeConnectorKey(sessionId, termId);

        TerminalEmulator emulator = connectors.get(key);
        if (emulator != null) {
            emulator.close();
            connectors.remove(key);
        }
    }

    sessions.removeAll(sessionId);
}
 
Example #2
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 #3
Source File: SchedulerStateRest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Initialize WebSocket based communication channel between the client and
 * the server.
 */
@GET
@Path("/events")
public String subscribe(@Context HttpServletRequest req, @HeaderParam("sessionid") String sessionId)
        throws NotConnectedRestException {
    checkAccess(sessionId);
    HttpSession session = checkNotNull(req.getSession(),
                                       "HTTP session object is null. HTTP session support is requried for REST Scheduler eventing.");
    AtmosphereResource atmosphereResource = checkNotNull((AtmosphereResource) req.getAttribute(AtmosphereResource.class.getName()),
                                                         "No AtmosphereResource is attached with current request.");
    // use session id as the 'topic' (or 'id') of the broadcaster
    session.setAttribute(ATM_BROADCASTER_ID, sessionId);
    session.setAttribute(ATM_RESOURCE_ID, atmosphereResource.uuid());
    Broadcaster broadcaster = lookupBroadcaster(sessionId, true);
    if (broadcaster != null) {
        atmosphereResource.setBroadcaster(broadcaster).suspend();
    }
    return null;
}
 
Example #4
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 #5
Source File: PushHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to send a critical notification to the client and close the
 * connection. Does nothing if the connection is already closed.
 */
private static void sendNotificationAndDisconnect(
        AtmosphereResource resource, String notificationJson) {
    // TODO Implemented differently from sendRefreshAndDisconnect
    try {
        if (resource instanceof AtmosphereResourceImpl
                && !((AtmosphereResourceImpl) resource).isInScope()) {
            // The resource is no longer valid so we should not write
            // anything to it
            getLogger().debug(
                    "sendNotificationAndDisconnect called for resource no longer in scope");
            return;
        }
        resource.getResponse()
                .setContentType(JsonConstants.JSON_CONTENT_TYPE);
        resource.getResponse().getWriter().write(notificationJson);
        resource.resume();
    } catch (Exception e) {
        getLogger().trace("Failed to send critical notification to client",
                e);
    }
}
 
Example #6
Source File: AtmospherePushConnection.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Associates this {@code AtmospherePushConnection} with the given
 * {@link AtmosphereResource} representing an established push connection.
 * If already connected, calls {@link #disconnect()} first. If there is a
 * deferred push, carries it out via the new connection.
 *
 * @param resource
 *            the resource to associate this connection with
 */
public void connect(AtmosphereResource resource) {

    assert resource != null;
    assert resource != this.resource;

    if (isConnected()) {
        disconnect();
    }

    this.resource = resource;
    State oldState = state;
    state = State.CONNECTED;

    if (oldState == State.PUSH_PENDING
            || oldState == State.RESPONSE_PENDING) {
        // Sending a "response" message (async=false) also takes care of a
        // pending push, but not vice versa
        push(oldState == State.PUSH_PENDING);
    }
}
 
Example #7
Source File: BrowserLiveReloadImplTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void reload_twoConnections_sendReloadCommand() {
    AtmosphereResource resource1 = Mockito.mock(AtmosphereResource.class);
    AtmosphereResource resource2 = Mockito.mock(AtmosphereResource.class);
    Broadcaster broadcaster = Mockito.mock(Broadcaster.class);
    Mockito.when(resource1.getBroadcaster()).thenReturn(broadcaster);
    Mockito.when(resource2.getBroadcaster()).thenReturn(broadcaster);
    reload.onConnect(resource1);
    reload.onConnect(resource2);
    Assert.assertTrue(reload.isLiveReload(resource1));
    Assert.assertTrue(reload.isLiveReload(resource2));

    reload.reload();

    Mockito.verify(broadcaster).broadcast("{\"command\": \"reload\"}",
            resource1);
    Mockito.verify(broadcaster).broadcast("{\"command\": \"reload\"}",
            resource2);
}
 
Example #8
Source File: BrowserLiveReloadImplTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void reload_resourceIsNotSet_reloadCommandIsNotSent() {
    AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
    Broadcaster broadcaster = Mockito.mock(Broadcaster.class);
    Mockito.when(resource.getBroadcaster()).thenReturn(broadcaster);
    Assert.assertFalse(reload.isLiveReload(resource));

    reload.reload();

    Mockito.verifyZeroInteractions(broadcaster);
}
 
Example #9
Source File: BrowserLiveReloadImpl.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void reload() {
    atmosphereResources.forEach(resourceRef -> {
        AtmosphereResource resource = resourceRef.get();
        if (resource != null) {
            resource.getBroadcaster().broadcast("{\"command\": \"reload\"}",
                    resource);
        }
    });
}
 
Example #10
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 #11
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 #12
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 #13
Source File: PushHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private VaadinServletService runTest(
        BiConsumer<PushHandler, AtmosphereResource> testExec) {
    MockVaadinServletService service = Mockito
            .spy(MockVaadinServletService.class);
    try {
        runTest(service, testExec);
        return service;
    } catch (ServiceException exception) {
        throw new RuntimeException(exception);
    }
}
 
Example #14
Source File: BrowserLiveReloadImplTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void onConnect_suspend_sayHello() {
    AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
    Broadcaster broadcaster = Mockito.mock(Broadcaster.class);
    Mockito.when(resource.getBroadcaster()).thenReturn(broadcaster);

    reload.onConnect(resource);

    Assert.assertTrue(reload.isLiveReload(resource));
    Mockito.verify(resource).suspend(-1);
    Mockito.verify(broadcaster).broadcast("{\"command\": \"hello\"}",
            resource);
}
 
Example #15
Source File: SocketIOHandler.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void onMessage(AtmosphereResource r, SocketIOSessionOutbound outbound, String message) {
    if (outbound == null || message == null || message.length() == 0) {
        return;
    }

    try {
        Message msg = gson.fromJson(message, Message.class);

        String name = msg.getName();

        String spaceHome = r.getAtmosphereConfig().getInitParameter("SPACE_HOME", null);

        if (spaceHome == null) {
            log.error("SocketIOHandler on message error: SPACE_HOME must be setted in env");
            return;
        }

        Message.Arg arg = msg.getArgs().get(0);

        switch (name) {
            case "term.open":
                itermOpen(outbound, spaceHome, arg);
                break;
            case "term.input":
                itermInput(outbound, arg);
                break;
            case "term.resize":
                itermResize(outbound, arg);
                break;
            case "term.close":
                itermClose(outbound, arg);
                break;
            default:
                System.out.println("command " + name + " not found.");
                break;
        }
    } catch (Exception e) {
        log.error("SocketIOHandler onMessage error, message => {}, error => {}", message, e.getMessage());
    }
}
 
Example #16
Source File: BrowserLiveReloadImplTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void reload_resourceIsDisconnected_reloadCommandIsNotSent() {
    AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
    Broadcaster broadcaster = Mockito.mock(Broadcaster.class);
    Mockito.when(resource.getBroadcaster()).thenReturn(broadcaster);
    reload.onConnect(resource);
    Assert.assertTrue(reload.isLiveReload(resource));
    Mockito.reset(broadcaster);
    reload.onDisconnect(resource);
    Assert.assertFalse(reload.isLiveReload(resource));

    reload.reload();

    Mockito.verifyZeroInteractions(broadcaster);
}
 
Example #17
Source File: AtmosphereWebSocketUndertowDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequest(final AtmosphereResource resource) throws IOException {
    LOG.fine("onRequest");
    try {
        invokeInternal(null, resource.getRequest().getServletContext(), resource.getRequest(),
                       resource.getResponse());
    } catch (Exception e) {
        LOG.log(Level.WARNING, "Failed to invoke service", e);
    }
}
 
Example #18
Source File: AtmosphereWebSocketJettyDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequest(final AtmosphereResource resource) throws IOException {
    LOG.fine("onRequest");
    try {
        invokeInternal(null,
            resource.getRequest().getServletContext(), resource.getRequest(), resource.getResponse());
    } catch (Exception e) {
        LOG.log(Level.WARNING, "Failed to invoke service", e);
    }
}
 
Example #19
Source File: DefaultProtocolInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void attachWriter(final AtmosphereResource r) {
    AtmosphereResponse res = r.getResponse();
    AsyncIOWriter writer = res.getAsyncIOWriter();

    if (writer instanceof AtmosphereInterceptorWriter) {
        AtmosphereInterceptorWriter.class.cast(writer).interceptor(interceptor, 0);
    }
}
 
Example #20
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 #21
Source File: AtmosphereWebSocketServletDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void onRequest(final AtmosphereResource resource) throws IOException {
    LOG.fine("onRequest");
    try {
        invokeInternal(null,
            resource.getRequest().getServletContext(), resource.getRequest(), resource.getResponse());
    } catch (Exception e) {
        LOG.log(Level.WARNING, "Failed to invoke service", e);
    }
}
 
Example #22
Source File: LongPollingMessagingDelegate.java    From joynr with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a long polling channel.
 *
 * @param ccid
 *            the identifier of the channel
 * @param atmosphereTrackingId
 *            the tracking ID of the channel
 * @return the path segment for the channel. The path, appended to the base
 *         URI of the channel service, can be used to post messages to the
 *         channel.
 */
public String createChannel(String ccid, String atmosphereTrackingId) {

    throwExceptionIfTrackingIdnotSet(atmosphereTrackingId);

    log.info("CREATE channel for cluster controller: {} trackingId: {} ", ccid, atmosphereTrackingId);
    Broadcaster broadcaster = null;
    // look for an existing broadcaster

    BroadcasterFactory defaultBroadcasterFactory = BroadcasterFactory.getDefault();
    if (defaultBroadcasterFactory == null) {
        throw new JoynrHttpException(500, 10009, "broadcaster was null");
    }

    broadcaster = defaultBroadcasterFactory.lookup(Broadcaster.class, ccid, false);
    // create a new one if none already exists
    if (broadcaster == null) {
        broadcaster = defaultBroadcasterFactory.get(BounceProxyBroadcaster.class, ccid);

    }

    // avoids error where previous long poll from browser got message
    // destined for new long poll
    // especially as seen in js, where every second refresh caused a fail
    for (AtmosphereResource resource : broadcaster.getAtmosphereResources()) {
        if (resource.uuid() != null && resource.uuid().equals(atmosphereTrackingId)) {
            resource.resume();
        }
    }

    UUIDBroadcasterCache broadcasterCache = (UUIDBroadcasterCache) broadcaster.getBroadcasterConfig()
                                                                              .getBroadcasterCache();
    broadcasterCache.activeClients().put(atmosphereTrackingId, System.currentTimeMillis());

    // BroadcasterCacheInspector is not implemented corrected in Atmosphere
    // 1.1.0RC4
    // broadcasterCache.inspector(new MessageExpirationInspector());

    return "/channels/" + ccid + "/";
}
 
Example #23
Source File: PushHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean isLiveReloadConnection(AtmosphereResource resource) {
    String refreshConnection = resource.getRequest()
            .getParameter(ApplicationConstants.LIVE_RELOAD_CONNECTION);
    return service.getDeploymentConfiguration().isDevModeLiveReloadEnabled()
            && refreshConnection != null
            && TRANSPORT.WEBSOCKET.equals(resource.transport());
}
 
Example #24
Source File: PushHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Suspends the given resource
 *
 * @param resource
 *            the resource to suspend
 */
protected void suspend(AtmosphereResource resource) {
    if (resource.transport() == TRANSPORT.LONG_POLLING) {
        resource.suspend(getLongPollingSuspendTimeout());
    } else {
        resource.suspend(-1);
    }
}
 
Example #25
Source File: SpringSecurityAtmosphereInterceptor.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Action inspect(final AtmosphereResource r) {
    final SecurityContext context = (SecurityContext) r.getRequest().getSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    SecurityContextHolder.setContext(context);
    return Action.CONTINUE;
}
 
Example #26
Source File: PushHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private static UI findUiUsingResource(AtmosphereResource resource,
        Collection<UI> uIs) {
    for (UI ui : uIs) {
        PushConnection pushConnection = ui.getInternals()
                .getPushConnection();
        if (pushConnection instanceof AtmospherePushConnection) {
            if (((AtmospherePushConnection) pushConnection)
                    .getResource() == resource) {
                return ui;
            }
        }
    }
    return null;
}
 
Example #27
Source File: PushHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a new push connection is requested to be opened by the client
 *
 * @param resource
 *            The related atmosphere resources
 */
void onConnect(AtmosphereResource resource) {
    if (isLiveReloadConnection(resource)) {
        BrowserLiveReloadAccess access = service.getInstantiator()
                .getOrCreate(BrowserLiveReloadAccess.class);
        BrowserLiveReload liveReload = access.getLiveReload(service);
        liveReload.onConnect(resource);
    } else {
        callWithUi(resource, establishCallback);
    }
}
 
Example #28
Source File: PushHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a message is received through the push connection
 *
 * @param resource
 *            The related atmosphere resources
 */
void onMessage(AtmosphereResource resource) {
    if (isLiveReloadConnection(resource)) {
        getLogger().debug("Received live reload heartbeat");
    } else {
        callWithUi(resource, receiveCallback);
    }
}
 
Example #29
Source File: BrowserLiveReloadImpl.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnect(AtmosphereResource resource) {
    resource.suspend(-1);
    atmosphereResources.add(new WeakReference<>(resource));
    resource.getBroadcaster().broadcast("{\"command\": \"hello\"}",
            resource);
}
 
Example #30
Source File: BrowserLiveReloadImpl.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void onDisconnect(AtmosphereResource resource) {
    if (!atmosphereResources
            .removeIf(resourceRef -> resource.equals(resourceRef.get()))) {
        String uuid = resource.uuid();
        getLogger().warn(
                "Push connection {} is not a live-reload connection or already closed",
                uuid);
    }
}