com.adobe.cq.social.messaging.osgi.BundleServices Maven / Gradle / Ivy
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* __________________
*
* Copyright 2014 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
package com.adobe.cq.social.messaging.osgi;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
/**
* Implementation of {@link org.osgi.framework.BundleActivator} for Messaging.
*/
public class BundleServices implements BundleActivator {
private static BundleContext bundleContext;
private static Map serviceTrackers = new HashMap();
@Override
public void start(final BundleContext context) throws Exception {
synchronized (BundleServices.class) {
bundleContext = context;
}
}
@Override
public synchronized void stop(final BundleContext context) throws Exception {
synchronized (BundleServices.class) {
for (final Iterator i = serviceTrackers.values().iterator(); i.hasNext();) {
i.next().close();
}
}
}
/**
* Get the service for the specified class.
* @param in The class.
* @param The type of the service.
* @return The service.
*/
public static T getService(final Class in) {
if (bundleContext == null) {
return null;
}
final String name = in.getName();
ServiceTracker t = null;
synchronized (BundleServices.class) {
t = serviceTrackers.get(name);
if (t == null) {
t = new ServiceTracker(bundleContext, name, null);
serviceTrackers.put(name, t);
t.open();
}
}
final T service = (T) t.getService();
if (service == null) {
throw new IllegalStateException("Service unavailable: " + name);
}
return service;
}
}