package org.glassfish.hk2.osgiresourcelocator;
import org.osgi.framework.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public final class ServiceLoaderImpl extends org.glassfish.hk2.osgiresourcelocator.ServiceLoader {
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
private BundleListener bundleTracker;
private BundleContext bundleContext;
private ProvidersList providersList = new ProvidersList();
public ServiceLoaderImpl() {
ClassLoader cl = getClass().getClassLoader();
if (cl instanceof BundleReference) {
bundleContext = getBundleContextSecured(BundleReference.class.cast(cl).getBundle());
}
if (bundleContext == null) {
throw new RuntimeException("There is no bundle context available yet. " +
"Instatiate this class in STARTING or ACTIVE state only");
}
}
private BundleContext getBundleContextSecured(final Bundle bundle) {
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<BundleContext>() {
public BundleContext run() {
return bundle.getBundleContext();
}
});
} else {
return bundle.getBundleContext();
}
}
public void trackBundles() {
assert (bundleTracker == null);
bundleTracker = new BundleTracker();
bundleContext.addBundleListener(bundleTracker);
for (Bundle bundle : bundleContext.getBundles()) {
addProviders(bundle);
}
}
<T> Iterable<? extends T> lookupProviderInstances1(Class<T> serviceClass, ProviderFactory<T> factory) {
if (factory == null) {
factory = new DefaultFactory<T>();
}
List<T> providers = new ArrayList<T>();
for (Class c : lookupProviderClasses1(serviceClass)) {
try {
final T providerInstance = factory.make(c, serviceClass);
if (providerInstance != null) {
providers.add(providerInstance);
} else {
debug(factory + " returned null provider instance!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return providers;
}
<T> Iterable<Class> lookupProviderClasses1(Class<T> serviceClass) {
List<Class> providerClasses = new ArrayList<Class>();
rwLock.readLock().lock();
try {
final String serviceName = serviceClass.getName();
for (ProvidersPerBundle providersPerBundle : providersList.getAllProviders()) {
final Bundle bundle = bundleContext.getBundle(providersPerBundle.getBundleId());
if (bundle == null) {
continue;
}
final List<String> providerNames = providersPerBundle.getServiceToProvidersMap().get(serviceName);
if (providerNames == null) {
continue;
}
for (String providerName : providerNames) {
try {
final Class providerClass = loadClassSecured(bundle, providerName);
if (isCompatible(providerClass, serviceClass)) {
providerClasses.add(providerClass);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return providerClasses;
} finally {
rwLock.readLock().unlock();
}
}
private Class loadClassSecured(final Bundle bundle, final String name)
throws ClassNotFoundException {
if (System.getSecurityManager()!=null) {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class>(){
public Class run() throws ClassNotFoundException {
return bundle.loadClass(name);
}
});
} catch (PrivilegedActionException e) {
throw ClassNotFoundException.class.cast(e.getException());
}
} else {
return bundle.loadClass(name);
}
}
private boolean isCompatible(Class providerClass, Class serviceClass) {
try {
final Class<?> serviceClassSeenByProviderClass = Class.forName(serviceClass.getName(), false, providerClass.getClassLoader());
final boolean isCompatible = serviceClassSeenByProviderClass == serviceClass;
if (!isCompatible) {
debug(providerClass + " loaded by " + providerClass.getClassLoader()
+ " sees " + serviceClass + " from " + serviceClassSeenByProviderClass.getClassLoader()
+ ", where as caller uses " + serviceClass + " loaded by " + serviceClass.getClassLoader());
}
return isCompatible;
} catch (ClassNotFoundException e) {
debug("Unable to reach " + serviceClass + " from " + providerClass + ", which is loaded by " + providerClass.getClassLoader(), e);
return true;
}
}
private List<String> load(InputStream is) throws IOException {
List<String> providerNames = new ArrayList<String>();
try {
Scanner scanner = new Scanner(is);
final String commentPattern = "#";
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (!line.startsWith(commentPattern)) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
providerNames.add(st.nextToken());
break;
}
}
}
} finally {
is.close();
}
return providerNames;
}
private class BundleTracker implements BundleListener {
public void bundleChanged(BundleEvent event) {
Bundle bundle = event.getBundle();
switch (event.getType()) {
case BundleEvent.INSTALLED:
addProviders(bundle);
break;
case BundleEvent.UNINSTALLED:
removeProviders(bundle);
break;
case BundleEvent.UPDATED:
removeProviders(bundle);
addProviders(bundle);
break;
}
}
}
private void addProviders(Bundle bundle) {
rwLock.writeLock().lock();
try {
final String SERVICE_LOCATION = "META-INF/services";
if (bundle.getEntry(SERVICE_LOCATION) == null) return;
Enumeration<String> entries;
entries = bundle.getEntryPaths(SERVICE_LOCATION);
if (entries != null) {
ProvidersPerBundle providers = new ProvidersPerBundle(bundle.getBundleId());
while (entries.hasMoreElements()) {
String entry = entries.nextElement();
String serviceName = entry.substring(SERVICE_LOCATION.length() + 1);
InputStream is;
final URL url = bundle.getEntry(entry);
try {
is = url.openStream();
List<String> providerNames = load(is);
debug("Bundle = " + bundle + ", serviceName = " + serviceName + ", providerNames = " + providerNames);
providers.put(serviceName, providerNames);
} catch (IOException e) {
}
}
providersList.addProviders(providers);
}
} finally {
rwLock.writeLock().unlock();
}
}
private synchronized void removeProviders(Bundle bundle) {
rwLock.writeLock().lock();
try {
providersList.removeProviders(bundle.getBundleId());
} finally {
rwLock.writeLock().unlock();
}
}
private static class ProvidersPerBundle {
private long bundleId;
Map<String, List<String>> serviceToProvidersMap = new HashMap<String, List<String>>();
private ProvidersPerBundle(long bundleId) {
this.bundleId = bundleId;
}
public long getBundleId() {
return bundleId;
}
public void put(String serviceName, List<String> providerNames) {
serviceToProvidersMap.put(serviceName, providerNames);
}
public Map<String, List<String>> getServiceToProvidersMap() {
return serviceToProvidersMap;
}
}
private static class ProvidersList {
private List<ProvidersPerBundle> allProviders = new LinkedList<ProvidersPerBundle>();
void addProviders(ProvidersPerBundle providers) {
long bundleId = providers.getBundleId();
int idx = 0;
Iterator<ProvidersPerBundle> iterator = getAllProviders().iterator();
while (iterator.hasNext()) {
ProvidersPerBundle providersPerBundle = iterator.next();
if (providersPerBundle.getBundleId() > bundleId) {
getAllProviders().add(idx, providers);
return;
}
}
getAllProviders().add(providers);
}
void removeProviders(long bundleId) {
Iterator<ProvidersPerBundle> iterator = getAllProviders().iterator();
while (iterator.hasNext()) {
ProvidersPerBundle providersPerBundle = iterator.next();
if (providersPerBundle.getBundleId() == bundleId) {
iterator.remove();
return;
}
}
}
public List<ProvidersPerBundle> getAllProviders() {
return allProviders;
}
}
private static class DefaultFactory<T> implements ProviderFactory<T> {
public T make(Class providerClass, Class<T> serviceClass) throws Exception {
if (serviceClass.isAssignableFrom(providerClass)) {
return (T) providerClass.newInstance();
}
return null;
}
}
private void debug(String s) {
if (Boolean.valueOf(bundleContext.getProperty("org.glassfish.hk2.osgiresourcelocator.debug"))) {
System.out.println("org.glassfish.hk2.osgiresourcelocator:DEBUG: " + s);
}
}
private void debug(String s, Throwable t) {
if (Boolean.valueOf(bundleContext.getProperty("org.glassfish.hk2.osgiresourcelocator.debug"))) {
System.out.println("org.glassfish.hk2.osgiresourcelocator:DEBUG: " + s);
t.printStackTrace(System.out);
}
}
}