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

org.atmosphere.cpr.DefaultBroadcasterFactory Maven / Gradle / Ivy

/*
 * Copyright 2013 Jeanfrancois Arcand
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 *
 * Contributor(s):
 *
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 *
 */
package org.atmosphere.cpr;


import org.atmosphere.di.InjectorProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY_DESTROY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_DESTROY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_RESUME;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.NEVER;

/**
 * This class is responsible for creating {@link Broadcaster} instance. You can also add and remove {@link Broadcaster}
 * and lookup using {@link BroadcasterFactory#getDefault()} ()}
 * from any Classes loaded using the same class loader.
 *
 * @author Jeanfrancois Arcand
 * @author Jason Burgess
 */
public class DefaultBroadcasterFactory extends BroadcasterFactory {

    private static final Logger logger = LoggerFactory.getLogger(DefaultBroadcasterFactory.class);
    protected AtmosphereConfig config;
    private final ConcurrentHashMap store = new ConcurrentHashMap();
    private final Class clazz;
    private BroadcasterLifeCyclePolicy policy =
            new BroadcasterLifeCyclePolicy.Builder().policy(NEVER).build();

    protected DefaultBroadcasterFactory(Class clazz, String broadcasterLifeCyclePolicy, AtmosphereConfig c) {
        this.clazz = clazz;
        this.factory = this;
        config = c;
        configure(broadcasterLifeCyclePolicy);
    }

    private void configure(String broadcasterLifeCyclePolicy) {

        int maxIdleTime = 5 * 60 * 1000;
        String idleTime = config.getInitParameter(ApplicationConfig.BROADCASTER_LIFECYCLE_POLICY_IDLETIME);
        if (idleTime != null) {
            maxIdleTime = Integer.parseInt(idleTime);
        }

        if (EMPTY.name().equalsIgnoreCase(broadcasterLifeCyclePolicy)) {
            policy = new BroadcasterLifeCyclePolicy.Builder().policy(EMPTY).build();
        } else if (EMPTY_DESTROY.name().equalsIgnoreCase(broadcasterLifeCyclePolicy)) {
            policy = new BroadcasterLifeCyclePolicy.Builder().policy(EMPTY_DESTROY).build();
        } else if (IDLE.name().equalsIgnoreCase(broadcasterLifeCyclePolicy)) {
            policy = new BroadcasterLifeCyclePolicy.Builder().policy(IDLE).idleTimeInMS(maxIdleTime).build();
        } else if (IDLE_DESTROY.name().equalsIgnoreCase(broadcasterLifeCyclePolicy)) {
            policy = new BroadcasterLifeCyclePolicy.Builder().policy(IDLE_DESTROY).idleTimeInMS(maxIdleTime).build();
        } else if (IDLE_RESUME.name().equalsIgnoreCase(broadcasterLifeCyclePolicy)) {
            policy = new BroadcasterLifeCyclePolicy.Builder().policy(IDLE_RESUME).idleTimeInMS(maxIdleTime).build();
        } else if (NEVER.name().equalsIgnoreCase(broadcasterLifeCyclePolicy)) {
            policy = new BroadcasterLifeCyclePolicy.Builder().policy(NEVER).build();
        } else {
            logger.warn("Unsupported BroadcasterLifeCyclePolicy policy {}", broadcasterLifeCyclePolicy);
        }
    }

    /**
     * {@inheritDoc}
     */
    public synchronized final Broadcaster get() {
        return get(clazz.getSimpleName() + "-" + UUID.randomUUID());
    }

    /**
     * {@inheritDoc}
     */
    public final Broadcaster get(Object id) {
        return get(clazz, id);
    }

    /**
     * {@inheritDoc}
     */
    public final Broadcaster get(Class c, Object id) {

        if (id == null) {
            throw new NullPointerException("id is null");
        }
        if (c == null) {
            throw new NullPointerException("Class is null");
        }

        return lookup(c, id, true, true);
    }

    private Broadcaster createBroadcaster(Class c, Object id) throws BroadcasterCreationException {
        try {
            Broadcaster b = c.getConstructor(String.class, AtmosphereConfig.class).newInstance(id.toString(), config);
            InjectorProvider.getInjector().inject(b);

            if (b.getBroadcasterConfig() == null) {
                b.setBroadcasterConfig(new BroadcasterConfig(config.framework().broadcasterFilters, config, id.toString()));
            }

            b.setBroadcasterLifeCyclePolicy(policy);
            if (DefaultBroadcaster.class.isAssignableFrom(clazz)) {
                DefaultBroadcaster.class.cast(b).start();
            }

            for (BroadcasterListener l : broadcasterListeners) {
                b.addBroadcasterListener(l);
            }
            logger.trace("Broadcaster {} was created {}", id, b);

            notifyOnPostCreate(b);
            return b;
        } catch (Throwable t) {
            throw new BroadcasterCreationException(t);
        }
    }

    /**
     * {@inheritDoc}
     */
    public boolean add(Broadcaster b, Object id) {
        return (store.put(id, b) == null);
    }

    /**
     * {@inheritDoc}
     */
    public boolean remove(Broadcaster b, Object id) {
        boolean removed = store.remove(id, b);
        if (removed) {
            logger.debug("Removing Broadcaster {} factory size now {} ", id, store.size());
        }
        return removed;
    }

    /**
     * {@inheritDoc}
     */
    public final Broadcaster lookup(Class c, Object id) {
        return lookup(c, id, false);
    }

    /**
     * {@inheritDoc}
     */
    public final Broadcaster lookup(Object id) {
        return lookup(clazz, id, false);
    }

    /**
     * {@inheritDoc}
     */
    public final Broadcaster lookup(Object id, boolean createIfNull) {
        return lookup(clazz, id, createIfNull);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Broadcaster lookup(Class c, Object id, boolean createIfNull) {
        return lookup(c, id, createIfNull, false);
    }

    public Broadcaster lookup(Class c, Object id, boolean createIfNull, boolean unique) {
        synchronized(id) {
            logger.trace("About to create {}", id);
            if (unique && store.get(id) != null) {
                throw new IllegalStateException("Broadcaster already existing " + id + ". Use BroadcasterFactory.lookup instead");
            }

            Broadcaster b = store.get(id);
            logger.trace("Looking in the store using {} returned {}", id, b);
            if (b != null && !c.isAssignableFrom(b.getClass())) {
                String msg = "Invalid lookup class " + c.getName() + ". Cached class is: " + b.getClass().getName();
                logger.debug(msg);
                throw new IllegalStateException(msg);
            }

            if ((b == null && createIfNull) || (b != null && b.isDestroyed())) {
                if (b != null) {
                    logger.trace("Removing destroyed Broadcaster {}", b.getID());
                    store.remove(b.getID(), b);
                }

                Broadcaster nb = store.get(id);
                if (nb == null) {
                    nb = createBroadcaster(c, id);
                    store.put(id, nb);
                }

                if (nb == null) {
                    logger.trace("Added Broadcaster {} . Factory size: {}", id, store.size());
                }

                b = nb;
            }
            return b;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeAllAtmosphereResource(AtmosphereResource r) {
        // Remove inside all Broadcaster as well.
        try {
            if (store.size() > 0) {
                for (Broadcaster b : lookupAll()) {
                    try {
                        // Prevent deadlock
                        if (b.getAtmosphereResources().contains(r)) {
                            b.removeAtmosphereResource(r);
                        }
                    } catch (IllegalStateException ex) {
                        logger.trace(ex.getMessage(), ex);
                    }
                }
            }
        } catch (Exception ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }

    @Override
    public boolean remove(Object id) {
        return store.remove(id) != null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection lookupAll() {
        return Collections.unmodifiableCollection(store.values());
    }

    /**
     * {@inheritDoc}
     */
    public synchronized void destroy() {

        String s = config.getInitParameter(ApplicationConfig.SHARED);
        if (s != null && s.equalsIgnoreCase("true")) {
            logger.warn("Factory shared, will not be destroyed. That can possibly cause memory leaks if" +
                    "Broadcaster where created. Make sure you destroy them manually.");
            return;
        }

        Enumeration e = store.elements();
        Broadcaster b;
        // We just need one when shared.
        BroadcasterConfig bc = null;
        while (e.hasMoreElements()) {
            try {
                b = e.nextElement();
                b.resumeAll();
                b.destroy();
                bc = b.getBroadcasterConfig();
            } catch (Throwable t) {
                // Shield us from any bad behaviour
                logger.trace("Destroy", t);
            }
        }

        try {
            if (bc != null) bc.forceDestroy();
        } catch (Throwable t) {
            logger.trace("Destroy", t);

        }

        store.clear();
        factory = null;
    }

    public void notifyOnPostCreate(Broadcaster b) {
        for (BroadcasterListener l : broadcasterListeners) {
            try {
                l.onPostCreate(b);
            } catch (Exception ex) {
                logger.warn("onPostCreate", ex);
            }
        }
    }

    /**
     * Build a default {@link BroadcasterFactory} returned when invoking {@link #getDefault()} ()}.
     *
     * @param clazz A class implementing {@link Broadcaster}
     * @param c     An instance of {@link AtmosphereConfig}
     * @return the default {@link BroadcasterFactory}.
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static BroadcasterFactory buildAndReplaceDefaultfactory(Class clazz, AtmosphereConfig c)
            throws InstantiationException, IllegalAccessException {

        factory = new DefaultBroadcasterFactory(clazz, "NEVER", c);
         c.framework().setBroadcasterFactory(factory);
        return factory;
    }

    public static final class BroadcasterCreationException extends RuntimeException {
        public BroadcasterCreationException(Throwable t) {
            super(t);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy