Example usage for java.util ServiceLoader load

List of usage examples for java.util ServiceLoader load

Introduction

In this page you can find the example usage for java.util ServiceLoader load.

Prototype

@CallerSensitive
public static <S> ServiceLoader<S> load(Class<S> service) 

Source Link

Document

Creates a new service loader for the given service type, using the current thread's java.lang.Thread#getContextClassLoader context class loader .

Usage

From source file:org.apache.synapse.config.xml.endpoints.resolvers.ResolverFactory.java

private void registerExterns() {
    ServiceLoader<Resolver> loaders = ServiceLoader.load(Resolver.class);
    for (Resolver resolver : loaders) {
        String className = resolver.getClass().getName();
        String[] packageList = className.split(".");
        className = packageList[packageList.length - 1];
        if (resolverMap.get(className.toLowerCase()) == null) {
            resolverMap.put(className.toLowerCase(), resolver.getClass());
            if (log.isDebugEnabled()) {
                log.debug("Added Resolver " + className + " to resolver factory ");
            }//from w w  w  .java2 s .c  o  m
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Failed to Resolver " + className + " to resolver factory. Already exist");
            }
        }
    }
}

From source file:org.trellisldp.http.impl.BaseLdpHandler.java

private static <T> Optional<T> loadFirst(final Class<T> service) {
    return of(ServiceLoader.load(service).iterator()).filter(Iterator::hasNext).map(Iterator::next);
}

From source file:com.ngdata.sep.impl.SepReplicationSource.java

@Override
public void init(Configuration conf, FileSystem fs, ReplicationSourceManager manager, ReplicationQueues queues,
        ReplicationPeers peers, Stoppable stopper, String peerClusterZnode, UUID uuid) throws IOException {
    super.init(conf, fs, manager, queues, peers, stopper, peerClusterZnode, uuid);
    log.debug("init on cluster " + getPeerClusterId() + " on node " + getPeerClusterZnode());
    setWALEditFilter(loadEditFilter(getPeerClusterId(), ServiceLoader.load(WALEditFilterProvider.class)));
}

From source file:org.commonjava.maven.cartographer.ftest.LocalTestDriver.java

@Override
public Cartographer start(TemporaryFolder temp) throws Exception {
    sourceManager = new SourceManagerImpl();

    temp.create();/*  ww w  . j a  v a2 s.  c  o  m*/

    File homeDir = temp.newFolder("carto-home");
    File configDir = new File(homeDir, "etc");
    configDir.mkdirs();

    configurator.accept(configDir);

    final ServiceLoader<BootOptions> loader = ServiceLoader.load(BootOptions.class);
    final BootOptions opts = loader.iterator().next();

    options = (Options) opts;
    options.setPort(-1);
    options.setHomeDir(homeDir.getAbsolutePath());

    // Should not need this; the configurator should be smart enough to try ${carto.home}/etc/main.conf on its own.
    //        options.setConfig( new File( configDir, MAIN_CONF ).getAbsolutePath() );

    booter = new Booter();
    bootStatus = booter.start(options);

    if (bootStatus == null) {
        fail("No boot status");
    }

    Throwable t = bootStatus.getError();
    if (t != null) {
        throw new RuntimeException("Failed to start Cartographer test server.", t);
    }

    assertThat(bootStatus.isSuccess(), equalTo(true));

    WeldContainer container = booter.getContainer();
    sourceManager = container.instance().select(SourceManagerImpl.class).get();

    passwordManager = new MemoryPasswordManager();
    siteConfig = new SiteConfigBuilder("local-test", formatUrl().toString()).withRequestTimeoutSeconds(30)
            .build();
    httpFactory = new HttpFactory(passwordManager);

    carto = new ClientCartographer(siteConfig, httpFactory);
    return carto;
}

From source file:org.pentaho.pms.mql.dialect.SQLDialectFactory.java

/**
 * Load and register dialects defined as service providers implementing {@link SQLDialectInterface} (via Java's
 * ServiceLoader mechanism)./*  ww  w  .ja  va  2 s. c  om*/
 */
private void loadDialectPlugins() {
    ServiceLoader<SQLDialectInterface> dialects = ServiceLoader.load(SQLDialectInterface.class);
    Iterator<SQLDialectInterface> dialectIter = dialects.iterator();
    while (dialectIter.hasNext()) {
        SQLDialectInterface dialect = null;
        try {
            dialect = dialectIter.next(); // Try to instantiate the next dialect
        } catch (ServiceConfigurationError err) {
            // Log an error if dialect instantiation/registration fails for any other reason. We don't know the dialect
            // we attempted to load here so log it as a generic error with stack trace.
            logger.warn(Messages.getErrorString("SQLDialectFactory.WARN_0001_DIALECT_COULD_NOT_BE_LOADED", //$NON-NLS-1$
                    err.getMessage()));
            if (logger.isDebugEnabled()) {
                logger.debug(Messages.getErrorString("SQLDialectFactory.WARN_0001_DIALECT_COULD_NOT_BE_LOADED", //$NON-NLS-1$
                        err.getMessage()), err);
            }
        }
        if (dialect != null) {
            addDialect(dialect);
        }
    }
}

From source file:io.adeptj.runtime.osgi.FrameworkManager.java

public void startFramework() {
    try {//w w w.  ja  v  a 2  s .  c  o m
        long startTime = System.nanoTime();
        LOGGER.info("Starting the OSGi Framework!!");
        FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
        this.framework = frameworkFactory.newFramework(this.frameworkConfigs());
        long startTimeFramework = System.nanoTime();
        this.framework.start();
        LOGGER.info("OSGi Framework creation took [{}] ms!!", Times.elapsedMillis(startTimeFramework));
        BundleContext systemBundleContext = this.framework.getBundleContext();
        this.frameworkListener = new FrameworkLifecycleListener();
        systemBundleContext.addFrameworkListener(this.frameworkListener);
        BundleContextHolder.getInstance().setBundleContext(systemBundleContext);
        this.provisionBundles(systemBundleContext);
        List<String> errors = Configs.INSTANCE.undertow().getStringList("common.osgi-error-pages");
        this.errorHandler = Servlets.osgiServlet(systemBundleContext, new DefaultErrorHandler(), errors);
        LOGGER.info("OSGi Framework started in [{}] ms!!", Times.elapsedMillis(startTime));
    } catch (Exception ex) { // NOSONAR
        LOGGER.error("Failed to start OSGi Framework!!", ex);
        // Stop the Framework if the Bundles throws exception.
        this.stopFramework();
    }
}

From source file:org.jpos.qnode.QNode.java

private void startOSGIFramework() throws BundleException {
    Iterator<FrameworkFactory> iter = ServiceLoader.load(FrameworkFactory.class).iterator();
    if (iter.hasNext()) {
        FrameworkFactory frameworkFactory = iter.next();
        Map<String, String> config = new HashMap<String, String>();
        osgiFramework = frameworkFactory.newFramework(config);
        osgiFramework.start();//w  w w.j  av  a2 s .c o  m
        scanBundleDir();
    } else {
        warn("OSGI framework not found");
    }
}

From source file:net.landora.video.addons.AddonManager.java

private List<Addon> createOrderedAddons() {

    ServiceLoader<Addon> loader = ServiceLoader.load(Addon.class);

    final Map<String, Addon> allProviders = new HashMap<String, Addon>();
    for (Addon provider : loader) {
        allProviders.put(provider.getAddonId(), provider);
    }//from  ww  w  .j a v a2  s .c o m

    final Map<String, MutableInt> orders = new HashMap<String, MutableInt>();
    for (String id : allProviders.keySet()) {
        orders.put(id, new MutableInt());
    }

    boolean ordersChanged;
    do {
        ordersChanged = false;
        for (Map.Entry<String, Addon> entry : allProviders.entrySet()) {
            String id = entry.getKey();
            MutableInt myOrder = orders.get(id);

            for (String requiredId : entry.getValue().getRequiredAddons()) {
                MutableInt other = orders.get(requiredId);
                if (other.intValue() >= myOrder.intValue()) {
                    myOrder.setValue(other.intValue() + 1);
                    ordersChanged = true;
                }
            }

            if (myOrder.intValue() > 1000) {
                throw new IllegalStateException("Possible circular dependancy detected: " + id);
            }
        }
    } while (ordersChanged);

    List<String> ids = new ArrayList<String>(allProviders.keySet());
    Comparator<String> cmp = new Comparator<String>() {

        public int compare(String o1, String o2) {
            return orders.get(o1).compareTo(orders.get(o2));
        }
    };
    Collections.sort(ids, cmp);

    List<Addon> result = new ArrayList<Addon>(ids.size());
    for (String id : ids) {
        result.add(allProviders.get(id));
    }

    return result;
}

From source file:com.adeptj.runtime.osgi.FrameworkManager.java

public void startFramework() {
    try {/* w  w w.  j  av  a  2s .co m*/
        long startTime = System.nanoTime();
        LOGGER.info("Starting the OSGi Framework!!");
        FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
        this.framework = frameworkFactory.newFramework(this.frameworkConfigs());
        long startTimeFramework = System.nanoTime();
        this.framework.start();
        LOGGER.info("OSGi Framework creation took [{}] ms!!", Times.elapsedMillis(startTimeFramework));
        BundleContext systemBundleContext = this.framework.getBundleContext();
        this.frameworkListener = new FrameworkLifecycleListener();
        systemBundleContext.addFrameworkListener(this.frameworkListener);
        BundleContextHolder.getInstance().setBundleContext(systemBundleContext);
        this.provisionBundles();
        List<String> errors = Configs.of().undertow().getStringList("common.osgi-error-pages");
        this.errorHandler = Servlets.osgiServlet(systemBundleContext, new OSGiErrorServlet(), errors);
        LOGGER.info("OSGi Framework [Apache Felix v{}] started in [{}] ms!!",
                systemBundleContext.getBundle().getVersion(), Times.elapsedMillis(startTime));
    } catch (Exception ex) { // NOSONAR
        LOGGER.error("Failed to start OSGi Framework!!", ex);
        // Stop the Framework if the Bundles throws exception.
        this.stopFramework();
    }
}

From source file:de.shadowhunt.subversion.internal.ProbeServerOperation.java

@Override
public Repository execute(final HttpClient client, final HttpContext context) {
    final HttpUriRequest request = createRequest();

    final ProtocolVersion version;
    final Resource prefix;
    InputStream in = null;/* w  ww.j a v a 2 s. c o m*/
    try {
        final HttpResponse response = client.execute(request, context);
        in = getContent(response);
        check(response);

        version = determineVersion(response.getAllHeaders());
        prefix = Prefix.read(in, version);
    } catch (final IOException e) {
        throw new TransmissionException(e);
    } finally {
        IOUtils.closeQuietly(in);
    }

    for (final RepositoryLocator repositoryLocator : ServiceLoader.load(RepositoryLocator.class)) {
        if (repositoryLocator.isSupported(version)) {
            return repositoryLocator.create(repository, prefix, client, context);
        }
    }

    throw new SubversionException("Could not find suitable repository for " + repository);
}