Search in sources :

Example 1 with AtmosphereResource

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

the class LifecycleHandler method on.

public LifecycleHandler on(final DefaultBroadcaster broadcaster) {
    final BroadcasterLifeCyclePolicy lifeCyclePolicy = broadcaster.getBroadcasterLifeCyclePolicy();
    final BroadcasterConfig bc = broadcaster.getBroadcasterConfig();
    final Collection<AtmosphereResource> resources = broadcaster.getAtmosphereResources();
    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);
    }
    if (bc != null && bc.getScheduledExecutorService() == 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) {
        recentActivity.set(false);
        int time = lifeCyclePolicy.getTimeout();
        if (time == -1) {
            throw new IllegalStateException("BroadcasterLifeCyclePolicy time is not set");
        }
        Future<?> currentLifecycleTask = bc.getScheduledExecutorService().scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                try {
                    // Check for activity since the last execution.
                    if (recentActivity.getAndSet(false)) {
                        return;
                    } else if (resources.isEmpty()) {
                        if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE) {
                            notifyEmptyListener(broadcaster);
                            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) {
                            notifyEmptyListener(broadcaster);
                            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());
                    }
                } 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();
                }
                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 : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BroadcasterLifeCyclePolicy(org.atmosphere.runtime.BroadcasterLifeCyclePolicy) AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) BroadcasterConfig(org.atmosphere.runtime.BroadcasterConfig)

Example 2 with AtmosphereResource

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

the class LifecycleHandler method offIfEmpty.

public LifecycleHandler offIfEmpty(DefaultBroadcaster broadcaster) {
    BroadcasterConfig bc = broadcaster.getBroadcasterConfig();
    Collection<AtmosphereResource> resources = broadcaster.getAtmosphereResources();
    final BroadcasterLifeCyclePolicy lifeCyclePolicy = broadcaster.getBroadcasterLifeCyclePolicy();
    if (resources.isEmpty()) {
        notifyEmptyListener(broadcaster);
        if (broadcaster.getScope() != Broadcaster.SCOPE.REQUEST && lifeCyclePolicy.getLifeCyclePolicy() == EMPTY) {
            broadcaster.releaseExternalResources();
        } else if (broadcaster.getScope() == Broadcaster.SCOPE.REQUEST || lifeCyclePolicy.getLifeCyclePolicy() == EMPTY_DESTROY) {
            bc.getAtmosphereConfig().getBroadcasterFactory().remove(broadcaster, broadcaster.getID());
            broadcaster.destroy();
        }
    }
    return this;
}
Also used : BroadcasterLifeCyclePolicy(org.atmosphere.runtime.BroadcasterLifeCyclePolicy) AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) BroadcasterConfig(org.atmosphere.runtime.BroadcasterConfig)

Example 3 with AtmosphereResource

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

the class BlockingIOCometSupport method suspend.

/**
     * Suspend the connection by blocking the current {@link Thread}
     *
     * @param action The {@link Action}
     * @param req    the {@link AtmosphereRequest}
     * @param res    the {@link AtmosphereResponse}
     * @throws java.io.IOException
     * @throws javax.servlet.ServletException
     */
protected void suspend(Action action, AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
    final CountDownLatch latch = new CountDownLatch(1);
    req.setAttribute(LATCH, latch);
    boolean ok = true;
    AtmosphereResource resource = req.resource();
    if (resource != null) {
        try {
            resource.addEventListener(new AtmosphereResourceEventListenerAdapter.OnResume() {

                @Override
                public void onResume(AtmosphereResourceEvent event) {
                    latch.countDown();
                }
            });
            if (action.timeout() != -1) {
                ok = latch.await(action.timeout(), TimeUnit.MILLISECONDS);
            } else {
                latch.await();
            }
        } catch (InterruptedException ex) {
            logger.trace("", ex);
        } finally {
            if (!ok) {
                timedout(req, res);
            } else {
                AtmosphereResourceImpl.class.cast(resource).cancel();
            }
        }
    }
}
Also used : AtmosphereResourceEventListenerAdapter(org.atmosphere.runtime.AtmosphereResourceEventListenerAdapter) AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 4 with AtmosphereResource

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

the class AtmosphereServiceProcessor method handle.

@Override
public void handle(AtmosphereFramework framework, Class<Object> annotatedClass) {
    try {
        Class<?> aClass = annotatedClass;
        AtmosphereService a = aClass.getAnnotation(AtmosphereService.class);
        framework.setBroadcasterCacheClassName(a.broadcasterCache().getName());
        atmosphereConfig(a.atmosphereConfig(), framework);
        framework.setDefaultBroadcasterClassName(a.broadcaster().getName());
        filters(a.broadcastFilters(), framework);
        LinkedList<AtmosphereInterceptor> l = new LinkedList<AtmosphereInterceptor>();
        AtmosphereInterceptor aa = listeners(a.listeners(), framework);
        if (aa != null) {
            l.add(aa);
        }
        if (!a.servlet().isEmpty()) {
            final ReflectorServletProcessor r = framework.newClassInstance(ReflectorServletProcessor.class, ReflectorServletProcessor.class);
            r.setServletClassName(a.servlet());
            String mapping = a.path();
            AnnotationUtil.interceptorsForHandler(framework, Arrays.asList(a.interceptors()), l);
            if (!a.dispatch()) {
                AtmosphereHandler proxy = new AtmosphereServletProcessor() {

                    private String method = "GET";

                    @Override
                    public void onRequest(AtmosphereResource resource) throws IOException {
                        if (!resource.getRequest().getMethod().equalsIgnoreCase(method)) {
                            r.onRequest(resource);
                        }
                    }

                    @Override
                    public void onStateChange(AtmosphereResourceEvent event) throws IOException {
                        r.onStateChange(event);
                    }

                    @Override
                    public void destroy() {
                        r.destroy();
                    }

                    @Override
                    public void init(AtmosphereConfig config) throws ServletException {
                        String s = config.getInitParameter(ATMOSPHERERESOURCE_INTERCEPTOR_METHOD);
                        if (s != null) {
                            method = s;
                        }
                        r.init(config);
                    }
                };
                framework.addAtmosphereHandler(mapping, proxy, l);
            } else {
                framework.addAtmosphereHandler(mapping, r, l);
            }
        } else {
            interceptors(a.interceptors(), framework);
        }
    } catch (Throwable e) {
        logger.warn("", e);
    }
}
Also used : AtmosphereService(org.atmosphere.config.service.AtmosphereService) AtmosphereInterceptor(org.atmosphere.runtime.AtmosphereInterceptor) AtmosphereConfig(org.atmosphere.runtime.AtmosphereConfig) AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) LinkedList(java.util.LinkedList) AtmosphereHandler(org.atmosphere.runtime.AtmosphereHandler) AtmosphereServletProcessor(org.atmosphere.runtime.AtmosphereServletProcessor) AtmosphereResourceEvent(org.atmosphere.runtime.AtmosphereResourceEvent) ReflectorServletProcessor(org.atmosphere.handler.ReflectorServletProcessor)

Example 5 with AtmosphereResource

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

the class SessionBroadcasterCache method retrieveFromCache.

@Override
public List<Object> retrieveFromCache(String broadcasterId, String uuid) {
    if (uuid == null) {
        throw new IllegalArgumentException("AtmosphereResource can't be null");
    }
    List<Object> result = new ArrayList<Object>();
    try {
        AtmosphereResource r = config.resourcesFactory().find(uuid);
        if (r == null) {
            logger.trace("Invalid UUID {}", uuid);
            return result;
        }
        HttpSession session = r.session();
        if (session == null) {
            logger.error(ERROR_MESSAGE);
            return result;
        }
        String cacheHeaderTimeStr = (String) session.getAttribute(broadcasterId);
        if (cacheHeaderTimeStr == null)
            return result;
        Long cacheHeaderTime = Long.valueOf(cacheHeaderTimeStr);
        if (cacheHeaderTime == null)
            return result;
        return get(cacheHeaderTime);
    } catch (IllegalStateException ex) {
        logger.trace("", ex);
        logger.warn("The Session has been invalidated. Unable to retrieve cached messages");
        return Collections.emptyList();
    }
}
Also used : AtmosphereResource(org.atmosphere.runtime.AtmosphereResource) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList)

Aggregations

AtmosphereResource (org.atmosphere.runtime.AtmosphereResource)19 AtmosphereResourceImpl (org.atmosphere.runtime.AtmosphereResourceImpl)8 AtmosphereRequest (org.atmosphere.runtime.AtmosphereRequest)7 IOException (java.io.IOException)3 HashSet (java.util.HashSet)3 AsynchronousProcessor (org.atmosphere.runtime.AsynchronousProcessor)3 AtmosphereResourceEvent (org.atmosphere.runtime.AtmosphereResourceEvent)3 AtmosphereResourceEventImpl (org.atmosphere.runtime.AtmosphereResourceEventImpl)3 BroadcasterFuture (org.atmosphere.runtime.BroadcasterFuture)3 Deliver (org.atmosphere.runtime.Deliver)3 ArrayList (java.util.ArrayList)2 Future (java.util.concurrent.Future)2 ServletException (javax.servlet.ServletException)2 Action (org.atmosphere.runtime.Action)2 AtmosphereRequestImpl (org.atmosphere.runtime.AtmosphereRequestImpl)2 AtmosphereResponse (org.atmosphere.runtime.AtmosphereResponse)2 BroadcasterConfig (org.atmosphere.runtime.BroadcasterConfig)2 BroadcasterLifeCyclePolicy (org.atmosphere.runtime.BroadcasterLifeCyclePolicy)2 WebSocketEvent (org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent)2 LinkedList (java.util.LinkedList)1