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

atom.content.Context Maven / Gradle / Ivy

/*
 * Copyright © 2015 Geeoz, and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * The Research Projects is dual-licensed under the GNU General Public
 * License, version 2.0 (GPLv2) and the Geeoz Commercial License.
 *
 * Solely for non-commercial purposes. A purpose is non-commercial only if
 * it is in no manner primarily intended for or directed toward commercial
 * advantage or private monetary compensation.
 *
 * This Geeoz Software is supplied to you by Geeoz in consideration of your
 * agreement to the following terms, and your use, installation, modification
 * or redistribution of this Geeoz Software constitutes acceptance of these
 * terms. If you do not agree with these terms, please do not use, install,
 * modify or redistribute this Geeoz Software.
 *
 * Neither the name, trademarks, service marks or logos of Geeoz may be used
 * to endorse or promote products derived from the Geeoz Software without
 * specific prior written permission from Geeoz.
 *
 * The Geeoz Software is provided by Geeoz on an "AS IS" basis. GEEOZ MAKES NO
 * WARRANTIES, EXPRESS  OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, REGARDING THE GEEOZ SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 * COMBINATION WITH YOUR PRODUCTS.
 *
 * IN NO EVENT SHALL GEEOZ BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
 * AND/OR DISTRIBUTION OF THE GEEOZ SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER
 * THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 * OTHERWISE, EVEN IF GEEOZ HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * A copy of the GNU General Public License is included in the distribution in
 * the file LICENSE and at
 *
 *     http://www.gnu.org/licenses/gpl-2.0.html
 *
 * If you are using the Research Projects for commercial purposes, we
 * encourage you to visit
 *
 *     http://products.geeoz.com/license
 *
 * for more details.
 *
 * This software or hardware and documentation may provide access to
 * or information on content, products, and services from third parties.
 * Geeoz and its affiliates are not responsible for and expressly disclaim
 * all warranties of any kind with respect to third-party content, products,
 * and services. Geeoz and its affiliates will not be responsible for any loss,
 * costs, or damages incurred due to your access to or use of third-party
 * content, products, or services. If a third-party content exists, the
 * additional copyright notices and license terms applicable to portions of the
 * software are set forth in the THIRD_PARTY_LICENSE_README file.
 *
 * Please contact Geeoz or visit www.geeoz.com if you need additional
 * information or have any questions.
 */

package atom.content;

import atom.app.ActivityManager;
import atom.app.ActivityThread;
import atom.app.EventBus;
import atom.app.EventHandler;
import atom.app.Notification;
import atom.app.NotificationManager;
import atom.content.pm.ActivityInfo;
import atom.content.pm.PackageInfo;
import atom.view.View;

import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.prefs.Preferences;

/**
 * Interface to global information about an application environment. It allows
 * access to application-specific resources and classes, as well as up-calls for
 * application-level operations such as launching activities, broadcasting and
 * receiving intents, etc.
 *
 * @author Alex Voloshyn
 * @author Serge Voloshyn
 * @version 1.19 4/18/15
 */
public class Context implements Serializable {
    /**
     * Use serialVersionUID from JDK 1.0.2 for interoperability.
     */
    private static final long serialVersionUID = 8247185941817028455L;
    /**
     * Error message template for cases when activity information is empty.
     */
    private static final String MSG_ILLEGAL_STATE =
            "Activity information can't be empty.";
    /**
     * System service registry.
     */
    private static final Map REGISTRY = new HashMap<>();
    /**
     * List of java package names that contain schema derived class and/or java
     * to schema (JAXB-annotated) mapped classes.
     */
    private static final String JAXB_CONTEXT_PATH = "atom.view:atom.widget";
    /**
     * JAXB unmarshaller instance.
     */
    private static final Unmarshaller JAXB;
    /**
     * An activity thread that corresponding for this activity.
     */
    private ActivityThread activityThread;
    /**
     * Detailed activity information.
     */
    private transient ActivityInfo activityInfo;
    /**
     * Class loader for external resources.
     */
    private transient ClassLoader classloader = null;
    /**
     * Current JCR Session.
     */
    private transient Session session = null;

    /**
     * Set of handlers that this activity registered.
     */
    private Set registeredEventHandlers
            = new HashSet<>(1);

    static {
        try {
            final JAXBContext context
                    = JAXBContext.newInstance(JAXB_CONTEXT_PATH);
            JAXB = context.createUnmarshaller();
        } catch (final JAXBException e) {
            throw new Error(e);
        }
    }

    /**
     * Instantiates a layout XML file into its corresponding {@link View}
     * objects.
     *
     * @param path path to the XML resource view view
     * @return the root View of the inflated hierarchy
     */
    public View inflate(final String path) {
        return inflate(path, getClassLoader());
    }

    /**
     * Instantiates a layout XML file into its corresponding {@link View}
     * objects.
     *
     * @param path   path to the XML resource view view
     * @param loader class loader for external resources
     * @return the root View of the inflated hierarchy
     */
    public static View inflate(final String path, final ClassLoader loader) {
        try {
            return (View) JAXB.unmarshal(loader.getResourceAsStream(path));
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Creates a new service for the given service type that was found first.
     *
     * @param service the interface or abstract class representing the service
     * @param      the service type
     * @return a new service that was found first or null - if not
     */
    public static  S getService(final Class service) {
        // Get corresponded class loader to avoid class cast exception
        final ClassLoader loader = service.getClassLoader();
        final ServiceLoader services = ServiceLoader.load(service, loader);
        if (services.iterator().hasNext()) {
            return services.iterator().next();
        }
        return null;
    }

    /**
     * Creates a new service list for the given service type.
     *
     * @param service the interface or abstract class representing the service
     * @param      the service type
     * @return a new service list
     */
    public static  List getServices(final Class service) {
        // Get corresponded class loader to avoid class cast exception
        final ClassLoader loader = service.getClassLoader();
        final ServiceLoader services = ServiceLoader.load(service, loader);
        if (services.iterator().hasNext()) {
            final List list = new ArrayList<>();
            for (S instance : services) {
                list.add(instance);
            }
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * Returns system service for the given service type.
     *
     * @param service the interface or abstract class representing the service
     * @param      the service interface
     * @return a system service
     */
    @SuppressWarnings("unchecked")
    public static  S getSystemService(final Class service) {
        final String serviceName = service.getName();
        S systemService;
        if (REGISTRY.containsKey(serviceName)) {
            systemService = (S) REGISTRY.get(serviceName);
        } else {
            synchronized (REGISTRY) {
                systemService = (S) REGISTRY.get(serviceName);
                // Check again, after having acquired the lock to make sure
                // the instance was not created meanwhile by another thread
                if (systemService == null) {
                    systemService = getService(service);
                    REGISTRY.put(serviceName, systemService);
                }
            }
        }
        return systemService;
    }

    /**
     * Retrieve detailed activity information.
     *
     * @return detailed activity information
     */
    public final ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    /**
     * Sets detailed activity information.
     *
     * @param info detailed activity information
     */
    public final void setActivityInfo(final ActivityInfo info) {
        activityInfo = info;
    }

    /**
     * Retrieve class loader for external resources.
     *
     * @return class loader for external resources
     */
    public final ClassLoader getClassLoader() {
        if (classloader == null) {
            return Thread.currentThread().getContextClassLoader();
        }
        return classloader;
    }

    /**
     * Sets Class loader for external resources.
     *
     * @param loader class loader for external resources
     */
    public final void setClassLoader(final ClassLoader loader) {
        classloader = loader;
    }

    /**
     * Retrieve an activity thread that corresponding for this activity.
     *
     * @return an activity thread that corresponding for this activity
     */
    public final ActivityThread getActivityThread() {
        return activityThread;
    }

    /**
     * Sets an activity thread that corresponding for this activity.
     *
     * @param thread an activity thread that corresponding for this activity
     */
    public final void setActivityThread(final ActivityThread thread) {
        activityThread = thread;
    }

    /**
     * Post an notification to be notified.
     *
     * @param notification the description of the event to notify
     */
    public final void notify(final Notification notification) {
        final NotificationManager manager =
                getSystemService(NotificationManager.class);
        manager.notify(notification);
    }

    /**
     * Launch a new activity. You will not receive any information about when
     * the activity exits.
     *
     * @param intent the description of the activity to start
     */
    public final void startActivity(final Intent intent) {
        final ActivityManager manager = getSystemService(ActivityManager.class);
        manager.startActivity(activityThread, intent);
    }

    /**
     * Register system event handler.
     *
     * @param      event type
     * @param event   event class
     * @param handler event handler instance
     * @return the handler registration, can be stored in order to remove the
     * handler later
     */
    public final  EventBus.HandlerRegistration
    registerEventHandler(final Class event, final EventHandler handler) {
        if (activityThread != null) {
            EventBus.HandlerRegistration handlerRegistration =
                    activityThread.registerEventHandler(event, handler);
            registeredEventHandlers.add(handlerRegistration);
            return handlerRegistration;
        }
        return null;
    }

    /**
     * Fire event for all registered handlers.
     *
     * @param    event type
     * @param event event
     */
    public final  void fireEvent(final E event) {
        final ActivityManager manager = getSystemService(ActivityManager.class);
        manager.fireEvent(activityThread, event);
    }

    /**
     * Provide a session for Java content repository.
     *
     * @return JCR session
     * @throws RepositoryException if if no suitable repository is found or
     *                             another error occurs.
     */
    public final Session getNewJcrSession() throws RepositoryException {
        final ActivityInfo info = getActivityInfo();
        final String workspace;
        if (info == null) {
            workspace = null;
        } else {
            final PackageInfo pack = info.getPackageInfo();
            workspace = pack.getName();
        }
        return getSystemService(JcrManager.class).login(workspace);
    }

    /**
     * Provide a session for Java content repository.
     *
     * @return JCR session
     * @throws RepositoryException if if no suitable repository is found or
     *                             another error occurs.
     */
    public final Session getJcrSession() throws RepositoryException {
        if (session == null) {
            session = getNewJcrSession();
        }
        return session;
    }

    /**
     * Destroy a session for Java content repository.
     */
    public final void destroyJcrSession() {
        if (session != null && session.isLive()) {
            session.logout();
            session = null;
        }
    }

    /**
     * Retrieve a root node of the preferences for the current application.
     *
     * @return a root node of the preferences
     */
    public final Preferences getPreferences() {
        final ActivityInfo info = getActivityInfo();
        if (info == null) {
            throw new IllegalStateException(MSG_ILLEGAL_STATE);
        }
        final PackageInfo pack = info.getPackageInfo();
        return PreferenceManager.SETTINGS.get(pack);
    }

    /**
     * Get set of handlers that this activity registered.
     *
     * @return Set of registered handlers.
     */
    protected Set getRegisteredEventHandlers() {
        return registeredEventHandlers;
    }

    @Override
    public boolean equals(final Object object) {
        boolean areEquals;
        if (this == object) {
            areEquals = true;
        } else {
            if (object instanceof Context) {
                final Context that = (Context) object;
                areEquals = Objects.equals(activityThread, that.activityThread)
                        && Objects.equals(activityInfo, that.activityInfo);
            } else {
                areEquals = false;
            }
        }
        return areEquals;
    }

    @Override
    public int hashCode() {
        return Objects.hash(activityThread, activityInfo);
    }

    @Override
    public String toString() {
        return String.format(
                "Context { activityThread='%s', activityInfo='%s' }",
                activityThread, activityInfo);
    }
}