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.googlecode.fascinator.api.PluginManager.java

/**
 * Get the access manager. Used in The indexer if the portal isn't running
 *
 * @param id plugin identifier/*from   ww w.j av a 2s. c o  m*/
 * @return an access manager plugin, or null if not found
 */
public static AccessControlManager getAccessManager(String id) {
    Class<AccessControlManager> clazz = (Class<AccessControlManager>) cache.getIfPresent("accessManager" + 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<AccessControlManager> plugins = ServiceLoader.load(AccessControlManager.class);
    for (AccessControlManager plugin : plugins) {
        if (id.equals(plugin.getId())) {
            return plugin;
        }
    }

    File groovyFile = getPathFile("plugins/accessManager/" + id + ".groovy");
    if (groovyFile.exists()) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        try {
            clazz = gcl.parseClass(groovyFile);
            cache.put("accessManager" + 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.ops4j.pax.exam.forked.ForkedFrameworkFactoryTest.java

@Test(expected = TestContainerException.class)
public void forkWithInvalidBootClasspath()
        throws BundleException, IOException, InterruptedException, NotBoundException, URISyntaxException {
    ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class);
    FrameworkFactory frameworkFactory = loader.iterator().next();

    ForkedFrameworkFactory forkedFactory = new ForkedFrameworkFactory(frameworkFactory);

    List<String> bootClasspath = Arrays
            .asList(CoreOptions.maven("org.kohsuke.metainf-services", "metainf-services", "1.2").getURL());

    Map<String, Object> frameworkProperties = new HashMap<String, Object>();
    frameworkProperties.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());
    frameworkProperties.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.kohsuke.metainf_services");
    forkedFactory.fork(Collections.<String>emptyList(), Collections.<String, String>emptyMap(),
            frameworkProperties, null, bootClasspath);
}

From source file:org.opennms.reporting.jasperreports.svclayer.JasperReportService.java

public JasperReportService() {
    parameterFilters = new ArrayList<>();
    Iterator<ParameterFilter> it = ServiceLoader.load(ParameterFilter.class).iterator();
    while (it.hasNext()) {
        parameterFilters.add(it.next());
    }//from  w  w w.  j  ava 2s  . c o  m
}

From source file:org.forgerock.openidm.shell.impl.BasicCommandScope.java

private Map<String, List<Method>> getCommands() {
    Map<String, List<Method>> commands = new TreeMap<String, List<Method>>();

    ServiceLoader<CustomCommandScope> ldr = ServiceLoader.load(CustomCommandScope.class);
    for (CustomCommandScope cmdScope : ldr) {
        if (null != cmdScope.getScope() && null != cmdScope.getFunctionMap()) {

            for (String func : cmdScope.getFunctionMap().keySet()) {
                commands.put(cmdScope.getScope() + ":" + func, new ArrayList<Method>());
            }/*from   w ww.  ja v  a 2  s  . c  o m*/

            if (!commands.isEmpty()) {
                Method[] methods = cmdScope.getClass().getMethods();
                for (Method method : methods) {
                    List<Method> commandMethods = commands.get(cmdScope.getScope() + ":" + method.getName());
                    if (commandMethods != null) {
                        commandMethods.add(method);
                    }
                }
            }

            // Remove any missing commands.
            Iterator<Map.Entry<String, List<Method>>> it = commands.entrySet().iterator();
            while (it.hasNext()) {
                if (it.next().getValue().size() == 0) {
                    it.remove();
                }
            }
        }
    }

    return commands;
}

From source file:kenh.xscript.Environment.java

/**
 * Load element packages through <code>Extension</code>.
 *//* ww w . j av  a 2 s  . co m*/
private void loadElementPackages_Extension() {
    ServiceLoader<Extension> es = ServiceLoader.load(Extension.class);
    for (Extension e : es) {
        if (e != null) {
            Map<String, String> p = e.getElementPackages();
            if (p != null && p.size() > 0) {
                Set<String> keys = p.keySet();
                for (String key : keys) {
                    String elementPackage = p.get(key);
                    setElementPackage(key, elementPackage);
                }
            }
        }
    }
}

From source file:org.codehaus.enunciate.config.EnunciateConfiguration.java

/**
 * Discover the deployment modules./* w  w w. j  a  v  a2 s. co m*/
 * @return An iterator over the deployment modules.
 * @param loader The classloader, or null if none.
 */
protected Iterator<DeploymentModule> discoverModules(ClassLoader loader) {
    return loader == null ? ServiceLoader.load(DeploymentModule.class).iterator()
            : ServiceLoader.load(DeploymentModule.class, loader).iterator();
}

From source file:org.wso2.ballerinalang.compiler.BinaryFileWriter.java

public void writeExecutableBinary(BLangPackage packageNode, String fileName) {
    String execFileName = cleanupExecFileName(fileName, BLANG_COMPILED_PROG_EXT);

    // Generate code for the given executable
    ProgramFile programFile = this.codeGenerator.generateBALX(packageNode);
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    try {//from   www.j  a v  a 2s  .c  o m
        ProgramFileWriter.writeProgram(programFile, byteArrayOS);
    } catch (IOException e) {
        throw new BLangCompilerException("error writing program file '" + execFileName + "'", e);
    }

    final Path execFilePath = this.sourceDirectory
            .saveCompiledProgram(new ByteArrayInputStream(byteArrayOS.toByteArray()), execFileName);
    ServiceLoader<CompilerPlugin> processorServiceLoader = ServiceLoader.load(CompilerPlugin.class);
    processorServiceLoader.forEach(plugin -> {
        plugin.codeGenerated(packageNode.packageID, execFilePath);
    });
}

From source file:sf.net.experimaestro.scheduler.Scheduler.java

/**
 * Initialise the task manager//from   ww w  . ja va2  s. c  o  m
 *
 * @param baseDirectory The directory where the XPM database will be stored
 */
public Scheduler(File baseDirectory) throws IOException {
    if (INSTANCE != null) {
        throw new XPMRuntimeException("Only one scheduler instance should be created");
    }

    INSTANCE = this;

    // Initialise the database
    LOGGER.info("Initialising database in directory %s", baseDirectory);
    HashMap<String, Object> properties = new HashMap<>();
    properties.put("hibernate.connection.url",
            format("jdbc:hsqldb:file:%s/xpm;shutdown=true;hsqldb.tx=mvcc", baseDirectory));
    properties.put("hibernate.connection.username", "");
    properties.put("hibernate.connection.password", "");

    /* From HSQLDB http://hsqldb.org/doc/guide/sessions-chapt.html#snc_tx_mvcc
            
    In MVCC mode
    - locks are at the row level
    - no shared (i.e. read) locks
    - in TRANSACTION_READ_COMMITTED mode: if a session wants to read/write a row that was written by another one => wait
    - in TRANSACTION_REPEATABLE_READ: if a session wants to write the same row than another one => exception
    */
    properties.put("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_READ_COMMITTED));

    ArrayList<Class<?>> loadedClasses = new ArrayList<>();
    ServiceLoader<PersistentClassesAdder> services = ServiceLoader.load(PersistentClassesAdder.class);
    for (PersistentClassesAdder service : services) {
        service.add(loadedClasses);
    }

    properties.put(org.hibernate.jpa.AvailableSettings.LOADED_CLASSES, loadedClasses);

    entityManagerFactory = Persistence.createEntityManagerFactory("net.bpiwowar.experimaestro", properties);

    // Add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(Scheduler.this::close));

    // Create reused criteria queries
    CriteriaBuilder builder = entityManagerFactory.getCriteriaBuilder();
    readyJobsQuery = builder.createQuery(Long.TYPE);
    Root<Job> root = readyJobsQuery.from(Job.class);
    readyJobsQuery.orderBy(builder.desc(root.get("priority")));
    readyJobsQuery.where(root.get("state").in(ResourceState.READY));
    readyJobsQuery.select(root.get(Resource_.resourceID));

    // Initialise the running resources so that they can retrieve their state
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    TypedQuery<Resource> query = entityManager.createQuery("from resources r where r.state = :state",
            Resource.class);
    query.setParameter("state", ResourceState.RUNNING);
    for (Resource resource : query.getResultList()) {
        LOGGER.info("Job %s is running: starting a watcher", resource);
        Job job = (Job) resource;
        if (job.process != null) {
            job.process.init(job);
        } else {
            Transaction.run(em -> {
                // Set the job state to ERROR (and update the state in case it was finished)
                // The job should take care of setting a new process if the job is still running
                Job _job = em.find(Job.class, job.getId());
                _job.setState(ResourceState.ERROR);
                _job.updateStatus();
                LOGGER.error("No process attached to a running job. New status is: %s", _job.getState());
            });
        }
        resource.updateStatus();
    }

    // Start the thread that notify dependencies
    LOGGER.info("Starting the notifier thread");
    notifier = new Notifier();
    notifier.start();
    runningThreadsCounter.add();

    // Start the thread that notify dependencies
    LOGGER.info("Starting the messager thread");
    messengerThread = new MessengerThread();
    messengerThread.start();
    runningThreadsCounter.add();

    // Start the thread that start the jobs
    LOGGER.info("Starting the job runner thread");
    readyJobSemaphore.setValue(true);
    runner = new JobRunner("JobRunner");
    runner.start();
    runningThreadsCounter.add();

    executorService = Executors.newFixedThreadPool(1);

    LOGGER.info("Done - ready status work now");
}

From source file:org.apache.hadoop.gateway.GatewaySslFuncTest.java

private static GatewayServices instantiateGatewayServices() {
    ServiceLoader<GatewayServices> loader = ServiceLoader.load(GatewayServices.class);
    Iterator<GatewayServices> services = loader.iterator();
    if (services.hasNext()) {
        return services.next();
    }//from   w  w  w  .ja  va  2 s .c  om
    return null;
}

From source file:org.lable.oss.dynamicconfig.core.ConfigurationInitializer.java

static List<ConfigurationSource> detectConfigurationSourceServiceProviders() {
    List<ConfigurationSource> providers = new ArrayList<>();
    ServiceLoader<ConfigurationSource> loader = ServiceLoader.load(ConfigurationSource.class);
    for (ConfigurationSource source : loader) {
        providers.add(source);//ww  w  .j  ava  2 s  .com
    }
    return providers;
}