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.openflexo.foundation.sg.implmodel.TechnologyModuleDefinition.java

/**
 * Retrieve all {@link TechnologyModuleDefinition} available from classpath. <br>
 * Map contains the TechnologyModuleDefinition name as key and the TechnologyModuleDefinition itself as value.
 * /*from  w  w  w.j a v  a  2 s. c  om*/
 * @return the retrieved TechnologyModuleDefinition map.
 */
private static Map<String, TechnologyModuleDefinition> getTechnologyModuleDefinitionMap() {
    if (technologyModuleDefinitionMap == null) {
        technologyModuleDefinitionMap = new Hashtable<String, TechnologyModuleDefinition>();

        ServiceLoader<TechnologyModuleDefinition> loader = ServiceLoader.load(TechnologyModuleDefinition.class);
        Iterator<TechnologyModuleDefinition> iterator = loader.iterator();
        while (iterator.hasNext()) {
            TechnologyModuleDefinition technologyModuleDefinition = iterator.next();

            if (technologyModuleDefinitionMap.containsKey(technologyModuleDefinition.getName())) {
                logger.severe("Cannot include TechnologyModuleDefinition with name '"
                        + technologyModuleDefinition.getName()
                        + "' because it already exists !!!! A Technology module name MUST be unique !");
            } else {
                technologyModuleDefinitionMap.put(technologyModuleDefinition.getName(),
                        technologyModuleDefinition);
            }
        }
    }

    return technologyModuleDefinitionMap;
}

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

/**
 * Get a list of indexer plugins//from ww w.  j av  a  2  s  . c  o m
 *
 * @return map of indexer plugins, or empty map if not found
 */
public static Map<String, Indexer> getIndexerPlugins() {
    Map<String, Indexer> indexers = new HashMap<String, Indexer>();
    ServiceLoader<Indexer> plugins = ServiceLoader.load(Indexer.class);
    for (Indexer plugin : plugins) {
        indexers.put(plugin.getId(), plugin);
    }
    return indexers;
}

From source file:ru.apertum.qsystem.common.model.QCustomer.java

/**
 *  ?    ? //from ww  w  .  ja v  a 2 s  . c  o m
 *
 * @param state
 * @param newServiceId -     ?    ID  ?    ,  ?  ? ?  ??, ..     ?  
 */
public void setState(CustomerState state, Long newServiceId) {
    this.state = state;
    stateIn = state.ordinal();

    //   ?   ?      ?
    if (getUser() != null) {
        getUser().getShadow().setCustomerState(state);
    }

    switch (state) {
    case STATE_DEAD:
        QLog.l().logger().debug("?: ? ?  \"" + getPrefix()
                + getNumber() + "\"    ?");
        getUser().getPlanService(getService()).inkKilled();
        //  ? , ?    . ? ?  
        //  _  ?,  ?,  ?_ , ?
        setStartTime(new Date());
        setFinishTime(new Date());
        saveToSelfDB();
        break;
    case STATE_WAIT:
        QLog.l().logger().debug("?: ?    ?  \""
                + getPrefix() + getNumber() + "\"");
        break;
    case STATE_WAIT_AFTER_POSTPONED:
        QLog.l().logger().debug(
                "?: ?      ?    ?  \""
                        + getPrefix() + getNumber() + "\"");
        break;
    case STATE_WAIT_COMPLEX_SERVICE:
        QLog.l().logger().debug(
                "?: ?  ? ?   .. ? ??   ?  \""
                        + getPrefix() + getNumber() + "\"");
        break;
    case STATE_INVITED:
        QLog.l().logger().debug("?: ? ? ?  \""
                + getPrefix() + getNumber() + "\"");
        break;
    case STATE_INVITED_SECONDARY:
        QLog.l().logger().debug(
                "?: ?     ? ?  \""
                        + getPrefix() + getNumber() + "\"");
        break;
    case STATE_REDIRECT:
        QLog.l().logger().debug("?: ?  ?  \""
                + getPrefix() + getNumber() + "\"");
        getUser().getPlanService(getService()).inkWorked(new Date().getTime() - getStartTime().getTime());
        // ? ?  
        saveToSelfDB();
        break;
    case STATE_WORK:
        QLog.l().logger().debug("?  ? ? ?  \""
                + getPrefix() + getNumber() + "\"");
        getUser().getPlanService(getService()).upWait(new Date().getTime() - getStandTime().getTime());
        break;
    case STATE_WORK_SECONDARY:
        QLog.l().logger().debug(
                "?:      ? ? ?  \""
                        + getPrefix() + getNumber() + "\"");
        break;
    case STATE_BACK:
        QLog.l().logger().debug("?: ? ?  \"" + getPrefix()
                + getNumber() + "\"    ?");
        break;
    case STATE_FINISH:
        QLog.l().logger().debug("?:  ? ?  \"" + getPrefix()
                + getNumber() + "\"  ");
        getUser().getPlanService(getService()).inkWorked(new Date().getTime() - getStartTime().getTime());
        // ? ?  
        saveToSelfDB();
        break;
    case STATE_POSTPONED:
        QLog.l().logger().debug("? ?  \"" + getPrefix() + getNumber()
                + "\"    ?? ");
        getUser().getPlanService(getService()).inkWorked(new Date().getTime() - getStartTime().getTime());
        // ? ?  
        saveToSelfDB();
        break;
    }

    //  ??? 
    for (final IChangeCustomerStateEvent event : ServiceLoader.load(IChangeCustomerStateEvent.class)) {
        QLog.l().logger()
                .info(" SPI ??. ?: " + event.getDescription());
        try {
            event.change(this, state, newServiceId);
        } catch (Throwable tr) {
            QLog.l().logger().error(
                    " SPI ?? ?? . ?: "
                            + tr);
        }
    }
}

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

/**
 * Gets a roles plugin/*  w  w w .j  av  a 2 s.  c  o m*/
 *
 * @param id plugin identifier
 * @return a roles plugin, or null if not found
 */
public static Roles getRoles(String id) {
    Class<Roles> clazz = (Class<Roles>) cache.getIfPresent("roles" + 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<Roles> plugins = ServiceLoader.load(Roles.class);
    for (Roles plugin : plugins) {
        if (id.equals(plugin.getId())) {
            return plugin;
        }
    }
    File groovyFile = getPathFile("plugins/roles/" + id + ".groovy");
    if (groovyFile.exists()) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        try {
            clazz = gcl.parseClass(groovyFile);
            cache.put("roles" + 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:com.fitbur.testify.junit.system.SpringBootSystemTest.java

@Override
protected Statement methodBlock(FrameworkMethod method) {
    TestClass testClass = getTestClass();
    Class<?> javaClass = testClass.getJavaClass();

    Object testInstance;//w  ww  . ja v a2s . c o  m

    try {
        testInstance = createTest();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    TestContext testContext = getTestContext(javaClass);
    testContext.setTestInstance(testInstance);

    Optional<App> appOptional = testContext.getAnnotation(App.class);
    checkState(appOptional.isPresent(), "Test class '%s' is not annotated with @App annotation.",
            testClass.getName());

    App app = appOptional.get();
    Set<Class<?>> modules = testContext.getAnnotations(Module.class).parallelStream().map(p -> p.value())
            .collect(toSet());

    Set<Object> sources = new LinkedHashSet<>();
    sources.add(app.value());
    sources.addAll(modules);

    application = new SpringApplicationBuilder(sources.toArray()).bannerMode(Banner.Mode.OFF).build();

    APPLICATION_TEST_CONTEXTS.computeIfAbsent(application, p -> testContext);

    application.run();

    SpringBootDescriptor descriptor = APPLICATION_DESCRIPTORS.get(application);

    ServiceLocator serviceLocator = descriptor.getServiceLocator();
    serviceLocator.addConstant(descriptor.getClass().getSimpleName(), descriptor);

    try {
        URI baseURI = new URI("http", null, "0.0.0.0", descriptor.getServletContainer().getPort(),
                descriptor.getServletContext().getContextPath(), null, null);

        SpringBootClientDescriptor clientDescriptor = new SpringBootClientDescriptor(app, testContext, baseURI);
        ServiceLoader<ClientProvider> clientProviderLoader = ServiceLoader.load(ClientProvider.class);
        ArrayList<ClientProvider> clientProviders = Lists.newArrayList(clientProviderLoader);

        checkState(!clientProviders.isEmpty(), "ClientInstance provider not found in the classpath");
        checkState(clientProviders.size() == 1, "Multiple ClientInstance provider found in the classpath. "
                + "Please insure there is only one ClientInstance provider in the classpath.");

        ClientProvider clientProvider = clientProviders.get(0);
        Object context = clientProvider.configuration(clientDescriptor);

        testContext.getConfigMethod(context.getClass()).map(m -> m.getMethod()).ifPresent(m -> {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                try {
                    m.setAccessible(true);
                    m.invoke(testInstance, context);
                } catch (Exception e) {
                    checkState(false, "Call to config method '%s' in test class '%s' failed due to: ",
                            m.getName(), clientDescriptor.getTestClassName(), e.getMessage());
                }

                return null;
            });
        });

        serverInstance = new SpringBootServerInstance(descriptor.getServletContainer(), baseURI);
        serviceLocator.addConstant(serverInstance.getClass().getSimpleName(), serverInstance);

        clientInstance = clientProvider.init(clientDescriptor, context);
        serviceLocator.addConstant(clientInstance.getClass().getSimpleName(), clientInstance);

        TestCaseInstance testCaseInstance = new TestCaseInstance(method.getName(), testInstance);
        serviceLocator.addConstant(testCaseInstance.getTestName(), testCaseInstance);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    SystemTestReifier reifier = new SystemTestReifier(testContext, serviceLocator, testInstance);
    SystemTestCreator creator = new SystemTestCreator(testContext, reifier, serviceLocator);

    if (testContext.getCutDescriptor() != null) {
        creator.cut();
    }

    Set<FieldDescriptor> real = testContext.getFieldDescriptors().values().parallelStream()
            .filter(p -> !p.getInstance().isPresent())
            .filter(p -> p.hasAnnotations(descriptor.getServiceAnnotations().getInjectors())).collect(toSet());

    creator.real(real);

    SystemTestVerifier verifier = new SystemTestVerifier(testContext, LOGGER);
    verifier.wiring();

    Statement statement = methodInvoker(method, testInstance);
    statement = possiblyExpectingExceptions(method, testInstance, statement);
    statement = withBefores(method, testInstance, statement);
    statement = withAfters(method, testInstance, statement);
    statement = withRules(method, testInstance, statement);

    return statement;
}

From source file:org.deegree.services.csw.CSWController.java

private GetRecordByIdHandler getGetRecordByIdHandler() {
    ServiceLoader<GetRecordByIdHandler> serviceLoader = ServiceLoader.load(GetRecordByIdHandler.class);
    Iterator<GetRecordByIdHandler> iterator = serviceLoader.iterator();
    if (iterator.hasNext())
        return iterator.next();
    return new DefaultGetRecordByIdHandler();
}

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

/**
 * Get a list of roles plugins// ww  w.java 2 s.c  om
 *
 * @return map of roles plugins, or empty map if not found
 */
public static Map<String, Roles> getRolesPlugins() {
    Map<String, Roles> roles = new HashMap<String, Roles>();
    ServiceLoader<Roles> plugins = ServiceLoader.load(Roles.class);
    for (Roles plugin : plugins) {
        roles.put(plugin.getId(), plugin);
    }
    return roles;
}

From source file:com.anrisoftware.mongoose.environment.EnvironmentImpl.java

private CommandService loadCommandService(String name) {
    log.loadCommand(this, name);
    for (CommandService service : ServiceLoader.load(CommandService.class)) {
        if (service.getInfo().getId().equals(name)) {
            return service;
        }/*w  w w  .  j  a  v a  2s. com*/
    }
    return null;
}

From source file:net.sf.dsig.DSApplet.java

@Override
public void init() {
    super.init();

    // StrategyFactory service loader ----------------------------------- //
    strategyFactory = ServiceLoader.load(StrategyFactory.class).iterator().next();

    // Environment initialization --------------------------------------- //
    initProfiler.start("Environment init");
    Environment.getSingleton().setApplet(this);
    Environment.getSingleton().setProperties(UserHomeSettingsParser.parse());

    // Set the default java.logging logger for FINEST logging on
    // gr.ageorgiadis package when debug environmental parameter is set
    initProfiler.start("Logging init");
    if (Boolean.parseBoolean(Environment.getSingleton().getValue("debug"))) {
        System.out.println("\n*** Debug log enabled ***");

        Logger.getLogger("").getHandlers()[0].setLevel(Level.FINEST);
        Logger.getLogger("").setLevel(Level.INFO);

        Logger.getLogger("net.sf.dsig").setLevel(Level.FINEST);
    }/* w  w w .jav a2s. c om*/

    // Applet initialization through the Environment class -------------- //
    initProfiler.start("Applet init");
    Environment.getSingleton().init(this);

    // LiveConnect proxy initialization --------------------------------- //
    LiveConnectProxy.getSingleton().setApplet(this);

    // KeyStoreProxy initialization ------------------------------------- //
    try {
        KeyStoreProxyFactory factory = new KeyStoreProxyFactory();
        Environment.getSingleton().init(factory);

        keyStoreProxy = factory.createKeyStoreProxy();
    } catch (Exception e) {
        logger.error("Error while creating keyStoreProxy", e);

        createKeyStoreProxyException = e;
    }

    // Swing initialization --------------------------------------------- //
    initProfiler.start("Swing init");
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                initSwing();
            }
        });
    } catch (Exception e) {
        logger.error("Swing initialization failed", e);
    }

    initProfiler.start("Starting");
}

From source file:org.apache.jackrabbit.oak.run.osgi.OakOSGiRepositoryFactory.java

private PojoServiceRegistry createServiceRegistry(Map<String, Object> config) {
    try {/*from www .j a v a2 s .c  o m*/
        ServiceLoader<PojoServiceRegistryFactory> loader = ServiceLoader.load(PojoServiceRegistryFactory.class);
        return loader.iterator().next().newPojoServiceRegistry(config);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}