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.buaa.cfs.security.token.Token.java

private static Class<? extends TokenIdentifier> getClassForIdentifier(Text kind) {
    Class<? extends TokenIdentifier> cls = null;
    synchronized (Token.class) {
        if (tokenKindMap == null) {
            tokenKindMap = Maps.newHashMap();
            for (TokenIdentifier id : ServiceLoader.load(TokenIdentifier.class)) {
                tokenKindMap.put(id.getKind(), id.getClass());
            }/*from ww  w .java 2 s .c om*/
        }
        cls = tokenKindMap.get(kind);
    }
    if (cls == null) {
        LOG.warn("Cannot find class for token kind " + kind);
        return null;
    }
    return cls;
}

From source file:org.apache.marmotta.maven.plugins.buildinfo.BuildInfoMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    Map<String, String> map = new HashMap<String, String>();

    for (InfoProvider provider : ServiceLoader.load(InfoProvider.class)) {
        if (provider.isActive(project)) {
            map.putAll(provider.getInfo(project));
        }/*from   w w w  .j  a  va 2  s .  c o m*/
    }

    if (systemProperties != null) {
        for (String property : systemProperties) {
            map.put(property, System.getProperty(property, DEFAULT_VALUE));
        }
    }

    // operating system
    map.put("build.os", System.getProperty("os.name") + " " + System.getProperty("os.version") + "/"
            + System.getProperty("os.arch"));

    // host name
    try {
        map.put("build.host", java.net.InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
    }

    // user name
    if (marmottaCommiters.get(System.getProperty("user.name")) != null) {
        map.put("build.user", marmottaCommiters.get(System.getProperty("user.name")));
    } else {
        map.put("build.user", System.getProperty("user.name"));
    }

    Build build = project.getBuild();
    StringBuilder filename = new StringBuilder();
    filename.append(build.getOutputDirectory()).append(File.separator).append(BUILD_INFO_FILE_NAME);

    getLog().info("Writing to file " + filename.toString());

    Writer out = null;
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename.toString()), "UTF-8"));
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                out.write(entry.getKey());
                out.write(" = ");
                out.write(entry.getValue());
                out.write("\n");
            }
        }
        out.flush();
    } catch (IOException ioe) {
        getLog().warn(ioe.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.n52.car.io.Preferences.java

private Access instantiateAccess() {
    ServiceLoader<Access> loader = ServiceLoader.load(Access.class);
    for (Access access : loader) {
        access.initialize(instantiateConnection());
        return access;
    }/*from w ww  .  ja  va 2  s.c  o m*/
    return null;
}

From source file:org.apache.falcon.ExtensionHandler.java

private List<Entity> getEntities(ClassLoader extensionClassloader, String extensionName, String jobName,
        InputStream configStream) throws IOException, FalconException {
    Thread.currentThread().setContextClassLoader(extensionClassloader);

    ServiceLoader<ExtensionBuilder> extensionBuilders = ServiceLoader.load(ExtensionBuilder.class);

    List<Class<? extends ExtensionBuilder>> result = new ArrayList<>();

    for (ExtensionBuilder extensionBuilder : extensionBuilders) {
        result.add(extensionBuilder.getClass());
    }/* w  ww.j  a v  a 2s  .  c om*/

    if (result.isEmpty()) {
        throw new FalconException("Extension Implementation not found in the package of : " + extensionName);
    } else if (result.size() > 1) {
        throw new FalconException(
                "Found more than one extension Implementation in the package of : " + extensionName);
    }

    ExtensionBuilder extensionBuilder = null;
    try {
        @SuppressWarnings("unchecked")
        Class<ExtensionBuilder> clazz = (Class<ExtensionBuilder>) extensionClassloader
                .loadClass(result.get(0).getCanonicalName());
        extensionBuilder = clazz.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new FalconCLIException("Failed to instantiate extension implementation " + extensionName, e);
    }

    extensionBuilder.validateExtensionConfig(extensionName, configStream);

    return extensionBuilder.getEntities(jobName, configStream);
}

From source file:org.apache.tinkerpop.gremlin.structure.io.gryo.kryoshim.KryoShimServiceLoader.java

/**
 * Return a reference to the shim service.  This method may return a cached shim service
 * unless {@code forceReload} is true.  Calls to this method need not be externally
 * synchonized.//from ww  w. j  a  v a 2  s.c  om
 *
 * @param forceReload if false, this method may use its internal service cache; if true,
 *                    this method must ignore cache, and it must invoke {@link ServiceLoader#reload()}
 *                    before selecting a new service to return
 * @return the shim service
 */
private static KryoShimService load(final boolean forceReload) {
    // if the service is loaded and doesn't need reloading, simply return in
    if (null != cachedShimService && !forceReload)
        return cachedShimService;

    // if a service is already loaded, close it
    if (null != cachedShimService)
        cachedShimService.close();

    // if the configuration is null, try and load the configuration from System.properties
    if (null == configuration)
        configuration = SystemUtil.getSystemPropertiesConfiguration("tinkerpop", true);

    // get all of the shim services
    final ArrayList<KryoShimService> services = new ArrayList<>();
    final ServiceLoader<KryoShimService> serviceLoader = ServiceLoader.load(KryoShimService.class);
    synchronized (KryoShimServiceLoader.class) {
        if (forceReload)
            serviceLoader.reload();
        for (final KryoShimService kss : serviceLoader) {
            services.add(kss);
        }
    }
    // if a shim service class is specified in the configuration, use it -- else, priority-based
    if (configuration.containsKey(KRYO_SHIM_SERVICE)) {
        for (final KryoShimService kss : services) {
            if (kss.getClass().getCanonicalName().equals(configuration.getString(KRYO_SHIM_SERVICE))) {
                log.info("Set KryoShimService to {} because of configuration {}={}",
                        kss.getClass().getSimpleName(), KRYO_SHIM_SERVICE,
                        configuration.getString(KRYO_SHIM_SERVICE));
                cachedShimService = kss;
                break;
            }
        }
    } else {
        Collections.sort(services, KryoShimServiceComparator.INSTANCE);
        for (final KryoShimService kss : services) {
            log.debug("Found KryoShimService: {} (priority {})", kss.getClass().getCanonicalName(),
                    kss.getPriority());
        }
        if (0 != services.size()) {
            cachedShimService = services.get(services.size() - 1);
            log.info("Set KryoShimService to {} because its priority value ({}) is the best available",
                    cachedShimService.getClass().getSimpleName(), cachedShimService.getPriority());
        }
    }

    // no shim service was available
    if (null == cachedShimService)
        throw new IllegalStateException("Unable to load KryoShimService");

    // once the shim service is defined, configure it
    log.info(
            "Configuring KryoShimService {} with the following configuration:\n#######START########\n{}\n########END#########",
            cachedShimService.getClass().getCanonicalName(), ConfigurationUtils.toString(configuration));
    cachedShimService.applyConfiguration(configuration);
    return cachedShimService;
}

From source file:com.rodiontsev.maven.plugins.buildinfo.BuildInfoMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    Map<String, String> map = new LinkedHashMap<String, String>();

    for (InfoProvider provider : ServiceLoader.load(InfoProvider.class)) {
        map.putAll(provider.getInfo(project, this));
    }// www . jav a 2s .  co m

    File buildDir = new File(project.getBuild().getDirectory());
    File file = new File(buildDir, filename);

    Writer out = null;
    try {
        // we may not have target/ yet
        buildDir.mkdir();
        boolean created = file.createNewFile();
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        for (Map.Entry<String, String> entry : map.entrySet()) {
            out.write(entry.getKey());
            out.write(" = ");
            out.write(entry.getValue());
            out.write("\n");
        }
        out.flush();
        getLog().info(created ? "Created " : "Overwrote " + file.getAbsolutePath());
    } catch (IOException e) {
        getLog().warn(e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.n52.car.io.Preferences.java

private Connection instantiateConnection() {
    ServiceLoader<Connection> loader = ServiceLoader.load(Connection.class);
    for (Connection connection : loader) {
        connection.initialize(getServer());
        return connection;
    }//from  www  . j  a  va  2s  . c  o  m
    return null;
}

From source file:com.thoughtworks.go.plugin.infra.FelixGoPluginOSGiFramework.java

@Override
public void start() {
    List<FrameworkFactory> frameworkFactories = IteratorUtils
            .toList(ServiceLoader.load(FrameworkFactory.class).iterator());

    if (frameworkFactories.size() != 1) {
        throw new RuntimeException(
                "One OSGi framework expected. Got " + frameworkFactories.size() + ": " + frameworkFactories);
    }/* ww  w.  ja v  a 2s.  c o m*/

    try {
        framework = getFelixFramework(frameworkFactories);
        framework.start();
        registerInternalServices(framework.getBundleContext());
    } catch (BundleException e) {
        throw new RuntimeException("Failed to initialize OSGi framework", e);
    }
}

From source file:org.kitodo.serviceloader.KitodoServiceLoader.java

/**
 * Loads a module from the classpath which implements the constructed clazz.
 * Frontend files of all modules will be loaded into the core module.
 *
 * @return A module with type T./*from  w w w. ja  v a  2  s  . c o  m*/
 */
@SuppressWarnings("unchecked")
public T loadModule() {

    loadModulesIntoClasspath();
    loadBeans();
    loadFrontendFilesIntoCore();

    ServiceLoader<T> loader = ServiceLoader.load(clazz);

    return loader.iterator().next();
}

From source file:org.ops4j.pax.exam.forked.ForkedFrameworkFactoryTest.java

@Test
public void forkWithBootClasspath()
        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(new File("target/bundles/metainf-services.jar").getCanonicalPath());

    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");
    RemoteFramework framework = forkedFactory.fork(Collections.<String>emptyList(),
            Collections.<String, String>emptyMap(), frameworkProperties, null, bootClasspath);
    framework.start();//from  w  w w.  ja  va 2 s. c o  m

    File testBundle = generateBundle();
    long bundleId = framework.installBundle("file:" + testBundle.getAbsolutePath());
    framework.startBundle(bundleId);

    // START>>> not yet implemented
    // framework.waitForState(bundleId, Bundle.ACTIVE, 1500);
    Thread.sleep(3000);
    // <<<END not yet implemented

    framework.stop();

    forkedFactory.join();
}