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:com.clustercontrol.plugin.HinemosPluginService.java

/**
 * private(Singleton)./*from   ww w.  ja v  a  2 s  . co m*/
 */
private HinemosPluginService() {
    String pluginDir = System.getProperty("hinemos.manager.home.dir") + File.separator + "plugins";
    try {
        // /opt/hinemos/plugins??jar??
        ClassUtils.addDirToClasspath(new File(pluginDir));
        log.info("initialized plugin directory : " + pluginDir);
    } catch (Exception e) {
        log.warn("classpath configure failure. (pluginDir = " + pluginDir + ")", e);
    }

    ServiceLoader<HinemosPlugin> serviceLoader = ServiceLoader.load(HinemosPlugin.class);
    Iterator<HinemosPlugin> itr = serviceLoader.iterator();
    while (itr.hasNext()) {
        HinemosPlugin plugin = itr.next();

        pluginMap.put(plugin.getClass().getName(), plugin);
        pluginStatusMap.put(plugin.getClass().getName(), PluginStatus.NULL);
    }

}

From source file:com.caricah.iotracah.bootstrap.runner.ResourceService.java

public SystemInitializer getSystemInitializer() throws UnRetriableException {

    Iterator<SystemInitializer> systemInitializerIterator = ServiceLoader.load(SystemInitializer.class)
            .iterator();//from   w w w  . jav a 2s  . c  om

    if (systemInitializerIterator.hasNext())
        return systemInitializerIterator.next();
    else
        throw new UnRetriableException(
                "A plugin supplying the system initializer: SystemInitializer is missing");
}

From source file:com.redhat.ewittman.MultiReferencePropertyJoinTest.java

@Test
public void test() throws Exception {
    Repository repository = null;/* w w w. j av  a  2  s .co m*/
    AnonymousCredentials credentials = new AnonymousCredentials();
    Session session = null;
    Node rootNode = null;

    // Get the ModeShape repo
    Map<String, String> parameters = new HashMap<String, String>();
    URL configUrl = getClass().getResource("inmemory-config.json");
    RepositoryConfiguration config = RepositoryConfiguration.read(configUrl);
    Problems problems = config.validate();
    if (problems.hasErrors()) {
        throw new RepositoryException(problems.toString());
    }
    parameters.put("org.modeshape.jcr.URL", configUrl.toExternalForm());
    for (RepositoryFactory factory : ServiceLoader.load(RepositoryFactory.class)) {
        repository = factory.getRepository(parameters);
        if (repository != null)
            break;
    }
    if (repository == null) {
        throw new RepositoryException("ServiceLoader could not instantiate JCR Repository");
    }

    // Configure it with our CND
    InputStream is = null;
    session = repository.login(credentials, "default");

    // Register some namespaces.
    NamespaceRegistry namespaceRegistry = session.getWorkspace().getNamespaceRegistry();
    namespaceRegistry.registerNamespace(JCRConstants.SRAMP, JCRConstants.SRAMP_NS);
    namespaceRegistry.registerNamespace(JCRConstants.SRAMP_PROPERTIES, JCRConstants.SRAMP_PROPERTIES_NS);
    namespaceRegistry.registerNamespace(JCRConstants.SRAMP_RELATIONSHIPS, JCRConstants.SRAMP_RELATIONSHIPS_NS);

    NodeTypeManager manager = (NodeTypeManager) session.getWorkspace().getNodeTypeManager();

    // Register the ModeShape S-RAMP node types ...
    is = getClass().getResourceAsStream("multiref-property-join.cnd");
    manager.registerNodeTypes(is, true);
    IOUtils.closeQuietly(is);
    session.logout();

    ////////////////////////////////////////////////
    // Add some artifact nodes.
    ////////////////////////////////////////////////
    session = repository.login(credentials, "default");
    rootNode = session.getRootNode();
    String jcrNodeType = JCRConstants.SRAMP_ + "artifact";
    // Node - Artifact A
    /////////////////////////
    Node artifactA = rootNode.addNode("artifact-a", jcrNodeType);
    artifactA.setProperty("sramp:uuid", "1");
    artifactA.setProperty("sramp:name", "A");
    artifactA.setProperty("sramp:model", "core");
    artifactA.setProperty("sramp:type", "Document");
    // Node - Artifact B
    /////////////////////////
    Node artifactB = rootNode.addNode("artifact-b", jcrNodeType);
    artifactB.setProperty("sramp:uuid", "2");
    artifactB.setProperty("sramp:name", "B");
    artifactB.setProperty("sramp:model", "core");
    artifactB.setProperty("sramp:type", "Document");
    // Node - Artifact C
    /////////////////////////
    Node artifactC = rootNode.addNode("artifact-c", jcrNodeType);
    artifactC.setProperty("sramp:uuid", "3");
    artifactC.setProperty("sramp:name", "C");
    artifactC.setProperty("sramp:model", "core");
    artifactC.setProperty("sramp:type", "Document");
    session.save();

    //////////////////////////////////////////////////////////////////////
    // Add the relationship nodes.  Here's what
    // I'm going for here:
    //    A has relationships to both B and C of type 'relatesTo'
    //    A has a relationship to C of type 'isDocumentedBy'
    //    B has a single relationship to C of type 'covets'
    //    C has no relationships
    //////////////////////////////////////////////////////////////////////
    Node relA_relatesTo = artifactA.addNode("relatesTo", "sramp:relationship");
    relA_relatesTo.setProperty("sramp:type", "relatesTo");
    Value[] targets = new Value[2];
    targets[0] = session.getValueFactory().createValue(artifactB, false);
    targets[1] = session.getValueFactory().createValue(artifactC, false);
    relA_relatesTo.setProperty("sramp:target", targets);

    Node relA_isDocumentedBy = artifactA.addNode("isDocumentedBy", "sramp:relationship");
    relA_isDocumentedBy.setProperty("sramp:type", "isDocumentedBy");
    relA_isDocumentedBy.setProperty("sramp:target", session.getValueFactory().createValue(artifactC, false));

    Node relB_covets = artifactB.addNode("relationship-b-1", "sramp:relationship");
    relB_covets.setProperty("sramp:type", "covets");
    relB_covets.setProperty("sramp:target", session.getValueFactory().createValue(artifactC, false));

    session.save();
    session.logout();

    //////////////////////////////////////////////////////////////////////
    // Now it's time to do some querying.
    //////////////////////////////////////////////////////////////////////
    session = repository.login(credentials, "default");
    // Show that we have the 'relatesTo' relationship set up for Artifact A (with two targets)
    String query = "SELECT relationship.[sramp:target] AS target_jcr_uuid\r\n"
            + "    FROM [sramp:artifact] AS artifact \r\n"
            + "    JOIN [sramp:relationship] AS relationship ON ISCHILDNODE(relationship, artifact) \r\n"
            + "   WHERE artifact.[sramp:name] = 'A'\r\n"
            + "     AND relationship.[sramp:type] = 'relatesTo'\r\n" + "";
    QueryManager jcrQueryManager = session.getWorkspace().getQueryManager();
    javax.jcr.query.Query jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    QueryResult jcrQueryResult = jcrQuery.execute();
    System.out.println("Result 1:");
    System.out.println(jcrQueryResult.toString());
    NodeIterator jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected one (1) node to come back (with two values).", 1, jcrNodes.getSize());
    Node n = jcrNodes.nextNode();
    Set<String> jcr_uuids = new HashSet<String>();
    for (Value value : n.getProperty("sramp:target").getValues()) {
        System.out.println("  Found JCR UUID: " + value.getString());
        jcr_uuids.add(value.getString());
    }

    // Now show that the UUIDs found above match the jcr:uuid for Artifact B and Artifact C
    query = "SELECT artifact.[jcr:uuid]\r\n" + "  FROM [sramp:artifact] AS artifact \r\n"
            + " WHERE artifact.[sramp:name] = 'B' OR artifact.[sramp:name] = 'C'\r\n" + "";
    jcrQueryManager = session.getWorkspace().getQueryManager();
    jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    jcrQueryResult = jcrQuery.execute();
    System.out.println("\n\nResult 2:");
    System.out.println(jcrQueryResult.toString());
    jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected two (2) nodes to come back.", 2, jcrNodes.getSize());
    Node n1 = jcrNodes.nextNode();
    Node n2 = jcrNodes.nextNode();
    Assert.assertTrue("Expected to find the JCR UUID in jcr_uuids",
            jcr_uuids.contains(n1.getProperty("jcr:uuid").getString()));
    Assert.assertTrue("Expected to find the JCR UUID in jcr_uuids",
            jcr_uuids.contains(n2.getProperty("jcr:uuid").getString()));
    System.out.println("Confirmed: the [jcr:uuid] for both Artifact B and Artifact C were found!");

    // OK - so far so good.  Now put it all together in a single query!  Here
    // we are trying to select Artifact B and Artifact C by selecting all Artifacts
    // that Artifatc A has a 'relatesTo' relationship on
    query = "SELECT artifact2.*\r\n" + "   FROM [sramp:artifact] AS artifact1\r\n"
            + "   JOIN [sramp:relationship] AS relationship1 ON ISCHILDNODE(relationship1, artifact1)\r\n"
            + "   JOIN [sramp:artifact] AS artifact2 ON relationship1.[sramp:target] = artifact2.[jcr:uuid]\r\n"
            + "   WHERE artifact1.[sramp:name] = 'A'\r\n"
            + "    AND relationship1.[sramp:type] = 'relatesTo')\r\n" + "";
    jcrQueryManager = session.getWorkspace().getQueryManager();
    jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    jcrQueryResult = jcrQuery.execute();
    System.out.println("\n\nResult 3:");
    System.out.println(jcrQueryResult.toString());
    jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected two (2) nodes (Artifact B and Artifact C) to come back!", 2,
            jcrNodes.getSize());

    // We made it past that.  Cool.  Let's try the same query but with a DISTINCT on it.  We'll
    // need this in case multiple artifacts have the same relationship to the same other artifact.  We
    // don't want that other artifact showing up in the result set multiple times.
    query = "SELECT DISTINCT artifact2.*\r\n" + "   FROM [sramp:artifact] AS artifact1\r\n"
            + "   JOIN [sramp:relationship] AS relationship1 ON ISCHILDNODE(relationship1, artifact1)\r\n"
            + "   JOIN [sramp:artifact] AS artifact2 ON relationship1.[sramp:target] = artifact2.[jcr:uuid]\r\n"
            + "   WHERE artifact1.[sramp:name] = 'A'\r\n"
            + "    AND relationship1.[sramp:type] = 'relatesTo')\r\n" + "";
    jcrQueryManager = session.getWorkspace().getQueryManager();
    jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    jcrQueryResult = jcrQuery.execute();
    System.out.println("\n\nResult 3:");
    System.out.println(jcrQueryResult.toString());
    jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected two (2) nodes (Artifact B and Artifact C) to come back!", 2,
            jcrNodes.getSize());

    session.logout();

}

From source file:com.springrts.springls.TASServer.java

private static Framework createFramework() {

    Framework framework = null;/*from w w  w  . jav  a 2s  .c  o m*/

    Iterator<FrameworkFactory> frameworkFactoryIterator = ServiceLoader.load(FrameworkFactory.class).iterator();
    if (frameworkFactoryIterator.hasNext()) {
        FrameworkFactory frameworkFactory = frameworkFactoryIterator.next();
        framework = frameworkFactory.newFramework(createFrameworkConfig());
    } else {
        LOG.error("No OSGi framework implementation was found.");
    }

    return framework;
}

From source file:org.apache.hadoop.hbase.metrics.MetricRegistriesLoader.java

private static List<MetricRegistries> getDefinedImplemantations() {
    ServiceLoader<MetricRegistries> loader = ServiceLoader.load(MetricRegistries.class);
    List<MetricRegistries> availableFactories = new ArrayList<>();
    for (MetricRegistries impl : loader) {
        availableFactories.add(impl);//from w w w .  j  a v  a 2s . c om
    }
    return availableFactories;
}

From source file:cross.io.AFragmentCommandServiceLoader.java

/**
 * Returns the available implementations of {@link AFragmentCommand} as provided
 * by the Java {@link java.util.ServiceLoader} infrastructure.
 *
 * Elements are sorted according to lexical order on their classnames.
 *
 * @return the list of available fragment commands
 *///  w w  w  .  j  a  va  2  s .  com
public List<AFragmentCommand> getAvailableCommands() {
    ServiceLoader<AFragmentCommand> sl = ServiceLoader.load(AFragmentCommand.class);
    HashSet<AFragmentCommand> s = new HashSet<>();
    for (AFragmentCommand ifc : sl) {
        s.add(ifc);
    }
    return createSortedListFromSet(s, new ClassNameLexicalComparator());
}

From source file:org.apache.mnemonic.Utils.java

/**
 * retrieve a volatile memory allocator service
 * /*from www.  j  ava2s  . c  om*/
 * @param id
 *          specify a name of allocator to retrieve
 *
 * @param allownvmsvc
 *          specify whether allow to treat non-volatile memory allocator as
 *          volatile one during searching
 *
 * @return the volatile memory allocator service instance
 */
public static VolatileMemoryAllocatorService getVolatileMemoryAllocatorService(String id, boolean allownvmsvc) {
    VolatileMemoryAllocatorService ret = null;
    if (null == m_vmasvcloader) {
        m_vmasvcloader = ServiceLoader.load(VolatileMemoryAllocatorService.class);
    }
    Iterator<VolatileMemoryAllocatorService> svcit = m_vmasvcloader.iterator();
    VolatileMemoryAllocatorService svc = null;
    while (null == ret && svcit.hasNext()) {
        svc = svcit.next();
        if (svc.getServiceId().equals(id)) {
            ret = svc;
        }
    }
    if (null == ret && allownvmsvc) {
        ret = getNonVolatileMemoryAllocatorService(id);
    }
    assert null != ret : "VolatileMemoryAllocatorService \'" + id + "\' not found!";
    return ret;
}

From source file:com.googlecode.fascinator.api.PluginManager.java

/**
 * Gets an access control plugin//w w  w.  j a  v a2s .  c o  m
 *
 * @param id plugin identifier
 * @return an access control plugin, or null if not found
 */
public static AccessControl getAccessControl(String id) {
    Class<AccessControl> clazz = (Class<AccessControl>) cache.getIfPresent("accessControl" + id);
    if (clazz != null) {
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            // Throwing RuntimeException to keep it unchecked
            // TODO: Remove later
            throw new RuntimeException(e);
        }
    }
    ServiceLoader<AccessControl> plugins = ServiceLoader.load(AccessControl.class);
    for (AccessControl plugin : plugins) {
        if (id.equals(plugin.getId())) {
            return plugin;
        }
    }

    File groovyFile = getPathFile("plugins/accessControl/" + id + ".groovy");
    if (groovyFile.exists()) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        try {
            clazz = gcl.parseClass(groovyFile);
            cache.put("accessControl" + id, clazz);
            return clazz.newInstance();

        } catch (Exception e) {
            // Throwing RuntimeException to keep it unchecked
            // TODO: Remove later
            throw new RuntimeException(e);
        }

    }

    return null;
}

From source file:org.cesecore.certificates.ca.CvcCA.java

public static ServiceLoader<? extends CvcPlugin> getImplementationClasses() {
    ServiceLoader<? extends CvcPlugin> serviceLoader = ServiceLoader.load(CvcPlugin.class);
    return serviceLoader;
}

From source file:org.kie.server.controller.websocket.management.KieServerMgmtCommandServiceImpl.java

private KieServerMgmtCommandServiceImpl() {
    ServiceLoader<PersistingServerTemplateStorageService> storageServices = ServiceLoader
            .load(PersistingServerTemplateStorageService.class);
    if (storageServices != null && storageServices.iterator().hasNext()) {
        PersistingServerTemplateStorageService storageService = storageServices.iterator().next();
        setTemplateStorage(storageService.getTemplateStorage());
    } else {//from w ww  .  j  a  va  2s.  c o  m
        LOGGER.debug(
                "No server template storage defined. Default storage: InMemoryKieServerTemplateStorage will be used");
    }

    ServiceLoader<NotificationServiceFactory> notificationServiceLoader = ServiceLoader
            .load(NotificationServiceFactory.class);
    if (notificationServiceLoader != null && notificationServiceLoader.iterator().hasNext()) {
        final NotificationService notificationService = notificationServiceLoader.iterator().next()
                .getNotificationService();
        setNotificationService(notificationService);
    } else {
        LOGGER.warn(
                "Notification service not defined. Default notification: LoggingNotificationService will be used");
    }
}