Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package org.infinispan.commons.util;
 
 import java.util.Set;
 
 import  org.osgi.framework.BundleContext;
import  org.osgi.framework.BundleReference;
import  org.osgi.util.tracker.ServiceTracker;

ServiceFinder is a java.util.ServiceLoader replacement which understands multiple classpaths

Author(s):
Tristan Tarrant
Brett Meyer
Since:
6.0
public class ServiceFinder {
   private static final Log LOG = LogFactory.getLog(ServiceFinder.class);
   
   public static <T> Set<T> load(Class<T> contractClassLoader... loaders) {
      Set<T> services = new LinkedHashSet<T>();
      
      if (loaders.length == 0) {
         try {
            ServiceLoader<T> loadedServices = ServiceLoader.load(contract);
            addServicesloadedServicesservices );
         } catch (Exception e) {
            // Ignore
         }
      }
      else {
         for (ClassLoader loader : loaders) {
            if (loader == null)
               continue;
            try {
               ServiceLoader<T> loadedServices = ServiceLoader.load(contractloader);
               addServicesloadedServicesservices );
            } catch (Exception e) {
               // Ignore
            }
         }
      }
      
      addOsgiServicescontractservices );
      
      if (services.isEmpty()) {
         .debugf("No service impls found: %s"contract.getSimpleName());
      }
      return services;
   }
   
   private static <T> void addServices(ServiceLoader<T> loadedServicesSet<T> services) {
      if (loadedServices.iterator().hasNext()) {
         for (T loadedService : loadedServices) {
            .debugf("Loading service impl: %s"loadedService.getClass().getSimpleName());
            services.add(loadedService);
         }
      }
   }
   private static <T> void addOsgiServices(Class<T> contractSet<T> services) {
      if (!Util.isOSGiContext()) {
          return;
      }
      ClassLoader loader = ServiceFinder.class.getClassLoader();
      if ((loader != null) && (loader instanceof org.osgi.framework.BundleReference)) {
         final BundleContext bundleContext = ((BundleReference) loader).getBundle().getBundleContext();
         final ServiceTracker<T, T> serviceTracker = new ServiceTracker<T, T>(bundleContextcontract.getName(),
               null);
         serviceTracker.open();
         try {
            final Object[] osgiServices = serviceTracker.getServices();
            if (osgiServices != null) {
               for (Object osgiService : osgiServices) {
                  services.add((T) osgiService);
               }
            }
         } catch (Exception e) {
            // ignore
         }
      }
   }
New to GrepCode? Check out our FAQ X