Search in sources :

Example 26 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project joynr by bmwcarit.

the class LongPollingMessagingDelegate method createChannel.

/**
 * 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);
    }
    // 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());
    return "/channels/" + ccid + "/";
}
Also used : BroadcasterFactory(org.atmosphere.cpr.BroadcasterFactory) JoynrHttpException(io.joynr.communications.exceptions.JoynrHttpException) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) Broadcaster(org.atmosphere.cpr.Broadcaster) UUIDBroadcasterCache(org.atmosphere.cache.UUIDBroadcasterCache)

Example 27 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project scheduling by ow2-proactive.

the class SchedulerStateRest method subscribe.

/*
     * Atmosphere 2.0 framework based implementation of Scheduler Eventing mechanism for REST
     * clients. It is configured to use WebSocket as the underneath protocol between the client and
     * the server.
     */
/**
 * 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;
}
Also used : AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) HttpSession(javax.servlet.http.HttpSession) Broadcaster(org.atmosphere.cpr.Broadcaster)

Example 28 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project scheduling by ow2-proactive.

the class SchedulerStateRest method publish.

/**
 * Accepts an {@link EventSubscription} instance which specifies the types
 * of SchedulerEvents which interest the client. When such Scheduler event
 * occurs, it will be communicated to the client in the form of
 * {@link EventNotification} utilizing the WebSocket channel initialized
 * previously.
 */
@POST
@Path("/events")
@Produces("application/json")
public EventNotification publish(@Context HttpServletRequest req, EventSubscription subscription) throws RestException {
    HttpSession session = req.getSession();
    String broadcasterId = (String) session.getAttribute(ATM_BROADCASTER_ID);
    final SchedulerProxyUserInterface scheduler = checkAccess(broadcasterId);
    SchedulerEventBroadcaster eventListener = new SchedulerEventBroadcaster(broadcasterId);
    try {
        final SchedulerEventBroadcaster activedEventListener = PAActiveObject.turnActive(eventListener);
        scheduler.addEventListener(activedEventListener, subscription.isMyEventsOnly(), EventUtil.toSchedulerEvents(subscription.getEvents()));
        AtmosphereResource atmResource = getAtmosphereResourceFactory().find((String) session.getAttribute(ATM_RESOURCE_ID));
        atmResource.addEventListener(new WebSocketEventListenerAdapter() {

            @Override
            public void onDisconnect(@SuppressWarnings("rawtypes") WebSocketEvent event) {
                try {
                    logger.info("#### websocket disconnected remove listener ####");
                    scheduler.removeEventListener();
                } catch (Exception e) {
                    logger.error(e);
                }
                PAActiveObject.terminateActiveObject(activedEventListener, true);
            }
        });
    } catch (SchedulerException e) {
        throw RestException.wrapExceptionToRest(e);
    } catch (ActiveObjectCreationException | NodeException e) {
        throw new RuntimeException(e);
    }
    return new EventNotification(EventNotification.Action.NONE, null, null);
}
Also used : EventNotification(org.ow2.proactive_grid_cloud_portal.scheduler.dto.eventing.EventNotification) WebSocketEventListenerAdapter(org.atmosphere.websocket.WebSocketEventListenerAdapter) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) HttpSession(javax.servlet.http.HttpSession) SchedulerProxyUserInterface(org.ow2.proactive.scheduler.common.util.SchedulerProxyUserInterface) NodeException(org.objectweb.proactive.core.node.NodeException) LoginException(javax.security.auth.login.LoginException) ActiveObjectCreationException(org.objectweb.proactive.ActiveObjectCreationException) KeyException(java.security.KeyException) URISyntaxException(java.net.URISyntaxException) LogForwardingException(org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingException) NodeException(org.objectweb.proactive.core.node.NodeException) ActiveObjectCreationException(org.objectweb.proactive.ActiveObjectCreationException)

Example 29 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project flow by vaadin.

the class PushHandlerTest method onConnect_devMode_websocket_refreshConnection_onConnectIsCalled_callWithUIIsNotCalled.

@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);
    deploymentConfiguration.setDevModeGizmoEnabled(true);
    ApplicationConfiguration applicationConfiguration = Mockito.mock(ApplicationConfiguration.class);
    Mockito.when(applicationConfiguration.isProductionMode()).thenReturn(false);
    VaadinContext context = service.getContext();
    context.setAttribute(ApplicationConfiguration.class, applicationConfiguration);
    BrowserLiveReload liveReload = mockBrowserLiveReloadImpl(context);
    AtomicReference<AtmosphereResource> res = new AtomicReference<>();
    runTest(service, (handler, resource) -> {
        AtmosphereRequest request = resource.getRequest();
        Mockito.when(request.getParameter(ApplicationConstants.DEBUG_WINDOW_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());
}
Also used : VaadinContext(com.vaadin.flow.server.VaadinContext) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) MockDeploymentConfiguration(com.vaadin.tests.util.MockDeploymentConfiguration) BrowserLiveReload(com.vaadin.flow.internal.BrowserLiveReload) AtomicReference(java.util.concurrent.atomic.AtomicReference) ApplicationConfiguration(com.vaadin.flow.server.startup.ApplicationConfiguration) Test(org.junit.Test)

Example 30 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project flow by vaadin.

the class PushHandlerTest method mockConnectionLost.

private void mockConnectionLost(VaadinSession session, boolean setSession) {
    AtomicBoolean sessionIsSet = new AtomicBoolean();
    MockVaadinServletService service = new MockVaadinServletService() {

        @Override
        public com.vaadin.flow.server.VaadinSession findVaadinSession(VaadinRequest request) throws SessionExpiredException {
            VaadinSession.setCurrent(session);
            sessionIsSet.set(true);
            Assert.assertNotNull(VaadinSession.getCurrent());
            return session;
        }

        @Override
        public UI findUI(VaadinRequest request) {
            return null;
        }
    };
    if (setSession) {
        VaadinSession.setCurrent(session);
    }
    PushHandler handler = new PushHandler(service);
    AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
    AtmosphereRequest request = Mockito.mock(AtmosphereRequest.class);
    Mockito.when(resource.getRequest()).thenReturn(request);
    AtmosphereResourceEvent event = Mockito.mock(AtmosphereResourceEvent.class);
    Mockito.when(event.getResource()).thenReturn(resource);
    handler.connectionLost(event);
    Assert.assertTrue(sessionIsSet.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) AtmosphereResourceEvent(org.atmosphere.cpr.AtmosphereResourceEvent) VaadinRequest(com.vaadin.flow.server.VaadinRequest)

Aggregations

AtmosphereResource (org.atmosphere.cpr.AtmosphereResource)37 AtmosphereRequest (org.atmosphere.cpr.AtmosphereRequest)14 IOException (java.io.IOException)10 AtmosphereResourceImpl (org.atmosphere.cpr.AtmosphereResourceImpl)9 Broadcaster (org.atmosphere.cpr.Broadcaster)8 Test (org.junit.Test)7 UI (com.vaadin.flow.component.UI)5 SessionExpiredException (com.vaadin.flow.server.SessionExpiredException)4 VaadinServletRequest (com.vaadin.flow.server.VaadinServletRequest)4 VaadinSession (com.vaadin.flow.server.VaadinSession)4 InvalidUIDLSecurityKeyException (com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException)4 JsonException (elemental.json.JsonException)4 AsynchronousProcessor (org.atmosphere.cpr.AsynchronousProcessor)4 AtmosphereResourceEvent (org.atmosphere.cpr.AtmosphereResourceEvent)4 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)3 ServletException (jakarta.servlet.ServletException)3 HashSet (java.util.HashSet)3 Future (java.util.concurrent.Future)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 AtmosphereResourceEventImpl (org.atmosphere.cpr.AtmosphereResourceEventImpl)3