Search in sources :

Example 16 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project atmosphere by Atmosphere.

the class LifecycleHandler method on.

public LifecycleHandler on(final DefaultBroadcaster broadcaster) {
    final BroadcasterLifeCyclePolicy lifeCyclePolicy = broadcaster.getBroadcasterLifeCyclePolicy();
    final Collection<AtmosphereResource> resources = broadcaster.getAtmosphereResources();
    if (broadcaster.getID().contains("{") && broadcaster.getID().contains("}")) {
        logger.trace("Ignoring wildcard {} with lifecycle policy: {}", broadcaster.getID(), lifeCyclePolicy.getLifeCyclePolicy().name());
        return this;
    }
    final BroadcasterConfig bc = broadcaster.getBroadcasterConfig();
    final AtomicBoolean recentActivity = broadcaster.recentActivity();
    if (logger.isTraceEnabled()) {
        logger.trace("{} new lifecycle policy: {}", broadcaster.getID(), lifeCyclePolicy.getLifeCyclePolicy().name());
    }
    if (broadcaster.currentLifecycleTask() != null) {
        broadcaster.currentLifecycleTask().cancel(false);
    }
    ScheduledExecutorService scheduler = bc.getScheduledExecutorService();
    if (scheduler == null) {
        logger.error("No Broadcaster's SchedulerExecutorService has been configured on {}. BroadcasterLifeCyclePolicy won't work.", broadcaster.getID());
        return this;
    }
    if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE || lifeCyclePolicy.getLifeCyclePolicy() == IDLE_RESUME || lifeCyclePolicy.getLifeCyclePolicy() == IDLE_DESTROY || lifeCyclePolicy.getLifeCyclePolicy() == IDLE_EMPTY_DESTROY) {
        recentActivity.set(false);
        int time = lifeCyclePolicy.getTimeout();
        if (time == -1) {
            throw new IllegalStateException("BroadcasterLifeCyclePolicy time is not set");
        }
        logger.debug("{} new lifecycle policy: {} [expire {} in {}]", broadcaster.getID(), lifeCyclePolicy.getLifeCyclePolicy().name(), time, lifeCyclePolicy.getLifeCyclePolicy());
        Future<?> currentLifecycleTask = scheduler.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                try {
                    // Check for activity since the last execution.
                    if (recentActivity.getAndSet(false)) {
                        return;
                    } else if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE) {
                        notifyIdleListener(broadcaster);
                        broadcaster.releaseExternalResources();
                        logger.debug("Applying BroadcasterLifeCyclePolicy IDLE policy to Broadcaster {}", broadcaster.getID());
                        if (broadcaster.currentLifecycleTask() != null) {
                            broadcaster.currentLifecycleTask().cancel(true);
                        }
                    } else if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE_DESTROY) {
                        notifyIdleListener(broadcaster);
                        destroy(false);
                        logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_DESTROY policy to Broadcaster {}", broadcaster.getID());
                    } else if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE_RESUME) {
                        notifyIdleListener(broadcaster);
                        destroy(true);
                        logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_RESUME policy to Broadcaster {}", broadcaster.getID());
                    } else if (resources.isEmpty() && lifeCyclePolicy.getLifeCyclePolicy() == IDLE_EMPTY_DESTROY) {
                        notifyIdleListener(broadcaster);
                        destroy(false);
                        logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_EMPTY_DESTROY policy to Broadcaster {}", broadcaster.getID());
                    }
                } catch (Throwable t) {
                    if (broadcaster.isDestroyed()) {
                        logger.trace("Scheduled BroadcasterLifeCyclePolicy exception", t);
                    } else {
                        logger.warn("Scheduled BroadcasterLifeCyclePolicy exception", t);
                    }
                }
            }

            void destroy(boolean resume) {
                if (resume) {
                    logger.info("All AtmosphereResource will now be resumed from Broadcaster {}", broadcaster.getID());
                    broadcaster.resumeAll();
                } else {
                    broadcaster.getAtmosphereResources().parallelStream().forEach(f -> {
                        try {
                            f.close();
                        } catch (IOException e) {
                            logger.trace("", e);
                        }
                    });
                }
                broadcaster.destroy();
                /**
                 * The value may be null if the timeout is too low. Hopefully next execution will
                 * cancel the task properly.
                 */
                if (broadcaster.currentLifecycleTask() != null) {
                    broadcaster.currentLifecycleTask().cancel(true);
                }
            }
        }, time, time, lifeCyclePolicy.getTimeUnit());
        broadcaster.currentLifecycleTask(currentLifecycleTask);
    }
    return this;
}
Also used : BroadcasterLifeCyclePolicy(org.atmosphere.cpr.BroadcasterLifeCyclePolicy) Logger(org.slf4j.Logger) Broadcaster(org.atmosphere.cpr.Broadcaster) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) BroadcasterConfig(org.atmosphere.cpr.BroadcasterConfig) DefaultBroadcaster(org.atmosphere.cpr.DefaultBroadcaster) EMPTY_DESTROY(org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY_DESTROY) Future(java.util.concurrent.Future) IDLE(org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) IDLE_RESUME(org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_RESUME) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) BroadcasterLifeCyclePolicyListener(org.atmosphere.cpr.BroadcasterLifeCyclePolicyListener) IDLE_DESTROY(org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_DESTROY) IDLE_EMPTY_DESTROY(org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_EMPTY_DESTROY) EMPTY(org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BroadcasterLifeCyclePolicy(org.atmosphere.cpr.BroadcasterLifeCyclePolicy) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) BroadcasterConfig(org.atmosphere.cpr.BroadcasterConfig) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 17 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project atmosphere by Atmosphere.

the class ExcludeSessionBroadcaster method broadcast.

/**
 * session will be exclude for this broadcast
 *
 * @param msg
 * @param s
 * @return
 */
public Future<Object> broadcast(Object msg, HttpSession s) {
    if (destroyed.get()) {
        return futureDone(msg);
    }
    Set<AtmosphereResource> subset = new HashSet<AtmosphereResource>();
    subset.addAll(resources);
    for (AtmosphereResource r : resources) {
        if (!r.getAtmosphereResourceEvent().isCancelled() && s.equals(r.getRequest().getSession())) {
            subset.remove(r);
        }
    }
    start();
    Object newMsg = filter(msg);
    if (newMsg == null) {
        return futureDone(msg);
    }
    BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, subset.size());
    dispatchMessages(new Deliver(newMsg, subset, f, msg));
    return f;
}
Also used : Deliver(org.atmosphere.cpr.Deliver) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) BroadcasterFuture(org.atmosphere.cpr.BroadcasterFuture) HashSet(java.util.HashSet)

Example 18 with AtmosphereResource

use of org.atmosphere.cpr.AtmosphereResource in project atmosphere by Atmosphere.

the class ExcludeSessionBroadcaster method broadcast.

/**
 * the AtmosphereResource r will be exclude for this broadcast
 *
 * @param msg
 * @param r
 * @return
 */
@Override
public Future<Object> broadcast(Object msg, AtmosphereResource r) {
    if (destroyed.get()) {
        throw new IllegalStateException("This Broadcaster has been destroyed and cannot be used");
    }
    Set<AtmosphereResource> sub = new HashSet<AtmosphereResource>();
    sub.addAll(resources);
    sub.remove(r);
    start();
    Object newMsg = filter(msg);
    if (newMsg == null) {
        return null;
    }
    BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, sub.size());
    dispatchMessages(new Deliver(newMsg, sub, f, msg));
    return f;
}
Also used : Deliver(org.atmosphere.cpr.Deliver) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) BroadcasterFuture(org.atmosphere.cpr.BroadcasterFuture) HashSet(java.util.HashSet)

Example 19 with AtmosphereResource

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

the class AtmospherePushConnectionTest method testSerialization.

@Test
public void testSerialization() throws Exception {
    UI ui = Mockito.mock(UI.class);
    AtmosphereResource resource = Mockito.mock(AtmosphereResource.class);
    AtmospherePushConnection connection = new AtmospherePushConnection(ui);
    connection.connect(resource);
    Assert.assertEquals(State.CONNECTED, connection.getState());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new ObjectOutputStream(baos).writeObject(connection);
    connection = (AtmospherePushConnection) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
    Assert.assertEquals(State.DISCONNECTED, connection.getState());
}
Also used : UI(com.vaadin.flow.component.UI) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 20 with AtmosphereResource

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

the class PushHandler method callWithUi.

/**
 * Find the UI for the atmosphere resource, lock it and invoke the callback.
 *
 * @param resource
 *            the atmosphere resource for the current request
 * @param callback
 *            the push callback to call when a UI is found and locked
 */
void callWithUi(final AtmosphereResource resource, final PushEventCallback callback) {
    AtmosphereRequest req = resource.getRequest();
    VaadinServletRequest vaadinRequest = new VaadinServletRequest(req, service);
    VaadinSession session = null;
    boolean isWebsocket = resource.transport() == TRANSPORT.WEBSOCKET;
    if (isWebsocket) {
        // For any HTTP request we have already started the request in the
        // servlet
        service.requestStart(vaadinRequest, null);
    }
    try {
        try {
            session = service.findVaadinSession(vaadinRequest);
            assert VaadinSession.getCurrent() == session;
        } catch (SessionExpiredException e) {
            sendNotificationAndDisconnect(resource, VaadinService.createSessionExpiredJSON(true));
            return;
        }
        UI ui = null;
        session.lock();
        try {
            ui = service.findUI(vaadinRequest);
            assert UI.getCurrent() == ui;
            if (ui == null) {
                sendNotificationAndDisconnect(resource, VaadinService.createUINotFoundJSON(true));
            } else {
                callback.run(resource, ui);
            }
        } catch (final IOException e) {
            callErrorHandler(session, e);
        } catch (final Exception e) {
            SystemMessages msg = service.getSystemMessages(HandlerHelper.findLocale(null, vaadinRequest), vaadinRequest);
            AtmosphereResource errorResource = resource;
            if (ui != null && ui.getInternals().getPushConnection() != null) {
                // We MUST use the opened push connection if there is one.
                // Otherwise we will write the response to the wrong request
                // when using streaming (the client -> server request
                // instead of the opened push channel)
                errorResource = ((AtmospherePushConnection) ui.getInternals().getPushConnection()).getResource();
            }
            sendNotificationAndDisconnect(errorResource, VaadinService.createCriticalNotificationJSON(msg.getInternalErrorCaption(), msg.getInternalErrorMessage(), null, msg.getInternalErrorURL()));
            callErrorHandler(session, e);
        } finally {
            try {
                session.unlock();
            } catch (Exception e) {
                getLogger().warn("Error while unlocking session", e);
            // can't call ErrorHandler, we (hopefully) don't have a lock
            }
        }
    } finally {
        try {
            if (isWebsocket) {
                service.requestEnd(vaadinRequest, null, session);
            }
        } catch (Exception e) {
            getLogger().warn("Error while ending request", e);
        // can't call ErrorHandler, we don't have a lock
        }
    }
}
Also used : AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) VaadinSession(com.vaadin.flow.server.VaadinSession) UI(com.vaadin.flow.component.UI) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) SessionExpiredException(com.vaadin.flow.server.SessionExpiredException) SystemMessages(com.vaadin.flow.server.SystemMessages) IOException(java.io.IOException) InvalidUIDLSecurityKeyException(com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException) JsonException(elemental.json.JsonException) SessionExpiredException(com.vaadin.flow.server.SessionExpiredException) IOException(java.io.IOException)

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