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

javolution.osgi.internal.ServiceTrackerImpl Maven / Gradle / Ivy

The newest version!
/*
 * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
 * Copyright (C) 2012 - Javolution (http://javolution.org/)
 * All rights reserved.
 * 
 * Permission to use, copy, modify, and distribute this software is
 * freely granted, provided that this notice is preserved.
 */
package javolution.osgi.internal;

import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

/**
 * Bridge to service tracker (does not trigger class loading exception 
 * if running outside OSGi).
 */
public final class ServiceTrackerImpl {

    private volatile ServiceTracker tracker;
    private final Class type;
    private final Class defaultImplClass;
    private C defaultImpl;

    /** Creates a context tracker for the specified context type. */
    public ServiceTrackerImpl(Class type, Class defaultImplClass) {
        this.defaultImplClass = defaultImplClass;
        this.type = type;
    }

    /** Activates OSGi tracking. */
    public void activate(BundleContext bc) {
        ServiceTracker trk = new ServiceTracker(bc, type, null);
        trk.open();
        tracker = trk;
    }

    /** Deactivates OSGi tracking. */
    public void deactivate(BundleContext bc) {
        tracker.close();
        tracker = null;
    }

    /** Returns the published services or the default implementation if none. */
    public Object[] getServices() {
        ServiceTracker trk = tracker;
        if (trk != null) {
            Object[] services = trk.getServices();
            if (services != null) return services;        
        }
        synchronized (this) {
            if (defaultImpl == null) {
                try {
                    defaultImpl = defaultImplClass.newInstance();
                } catch (Throwable error) {
                    throw new RuntimeException(error);
                } 
            }
        }
        return new Object[] { defaultImpl };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy