All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.atmosphere.jersey.util.JerseyBroadcasterUtil Maven / Gradle / Ivy

package org.atmosphere.jersey.util;

import com.sun.jersey.spi.container.ContainerResponse;
import org.atmosphere.cpr.AtmosphereEventLifecycle;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.AtmosphereResourceEventImpl;
import org.atmosphere.cpr.AtmosphereResourceImpl;
import org.atmosphere.jersey.AtmosphereFilter;
import org.atmosphere.util.LoggerUtils;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;

/**
 * Simple util class shared among Jersey's Broadcaster.
 * 
 * @author Jeanfrancois Arcand
 */
public final class JerseyBroadcasterUtil {

    public final static void broadcast(final AtmosphereResource r, final AtmosphereResourceEvent e) {
        HttpServletRequest res = (HttpServletRequest)r.getRequest();

        try {
            ContainerResponse cr = (ContainerResponse)res.getAttribute(AtmosphereFilter.CONTAINER_RESPONSE);

            if (e.getMessage() instanceof Response){
                cr.setResponse((Response)e.getMessage());
                cr.write();
            } else {
                cr.reset();
                cr.setEntity(e.getMessage());

                cr.write();
                cr.getOutputStream().flush();
            }
            if (r instanceof AtmosphereEventLifecycle){
                ((AtmosphereEventLifecycle)r).notifyListeners();
            }
        } catch (Throwable t){
            onException(t,r);
        } finally {
            Boolean resumeOnBroadcast = (Boolean)res.getAttribute(AtmosphereFilter.RESUME_ON_BROADCAST);
            if (resumeOnBroadcast != null && resumeOnBroadcast){

                String uuid = (String)res.getAttribute(AtmosphereFilter.RESUME_UUID);
                if (uuid != null){
                    if (res.getAttribute(AtmosphereFilter.RESUME_CANDIDATES) != null){
                        ((ConcurrentHashMap)res.getAttribute(AtmosphereFilter.RESUME_CANDIDATES)).remove(uuid);
                    }
                }
                r.resume();
            }
        }
    }

    final static void onException(Throwable t, AtmosphereResource r){
        if(LoggerUtils.getLogger().isLoggable(Level.FINE)){
            LoggerUtils.getLogger().log(Level.FINE, "", t);
        }
        if (t instanceof IOException && r instanceof AtmosphereEventLifecycle){
            ((AtmosphereEventLifecycle) r).notifyListeners(new AtmosphereResourceEventImpl((AtmosphereResourceImpl)r,true,false));
            ((AtmosphereEventLifecycle) r).removeEventListeners();
        }
        r.getBroadcaster().removeAtmosphereResource(r);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy