List of usage examples for java.util ServiceLoader load
@CallerSensitive public static <S> ServiceLoader<S> load(Class<S> service)
From source file:org.lenskit.specs.SpecUtils.java
/** * Build an object from a specification. On its own, this method does very little. It depends on support from * objects in order to work./* w ww .j a v a 2 s. co m*/ * * It operates as follows: * * 1. Load the {@link SpecHandler}s using {@link java.util.ServiceLoader}. * 2. Query each spec handler, in turn, to try to find one that can build an object of type `type` from the spec. * 3. If no such handler is found, try to invoke a static `fromSpec(AbstractSpec)` method on `type`. * 4. If no such method is found, or it returns `null`, throw {@link NoSpecHandlerFound}. * * @param type The type of object to build. * @param spec The specification to use. * @param cl The class loader to search. * @param <T> The built object type. * @return The built object. Will be `null` if and only if `spec` is `null`. * @throws NoSpecHandlerFound if no spec handler or `fromSpec` method can be found. */ @Nullable public static <T> T buildObject(@Nonnull Class<T> type, @Nullable AbstractSpec spec, ClassLoader cl) { if (spec == null) { return null; } ServiceLoader<SpecHandler> loader; if (cl == null) { loader = ServiceLoader.load(SpecHandler.class); } else { loader = ServiceLoader.load(SpecHandler.class, cl); } for (SpecHandler h : loader) { T obj = h.build(type, spec); if (obj != null) { return obj; } } try { T obj = type.cast(MethodUtils.invokeStaticMethod(type, "fromSpec", spec)); if (obj == null) { throw new NoSpecHandlerFound("No spec handler to build " + type + " from " + spec); } else { return obj; } } catch (NoSuchMethodException e) { throw new NoSpecHandlerFound("No spec handler to build " + type + " from " + spec); } catch (IllegalAccessException e) { throw new RuntimeException("access error invoking fromSpec on " + type, e); } catch (InvocationTargetException e) { throw new RuntimeException("Error occurred in fromSpec on " + type, e); } }
From source file:org.lable.oss.dynamicconfig.core.ConfigurationInitializer.java
static List<HierarchicalConfigurationDeserializer> detectDeserializationServiceProviders() { List<HierarchicalConfigurationDeserializer> providers = new ArrayList<>(); ServiceLoader<HierarchicalConfigurationDeserializer> loader = ServiceLoader .load(HierarchicalConfigurationDeserializer.class); for (HierarchicalConfigurationDeserializer source : loader) { providers.add(source);// www . j av a2 s . c o m } return providers; }
From source file:org.apache.hadoop.security.token.DtFileOperations.java
/** Fetch a token from a service and save to file in the local filesystem. * @param tokenFile a local File object to hold the output. * @param fileFormat a string equal to FORMAT_PB or FORMAT_JAVA, for output * @param alias overwrite service field of fetched token with this text. * @param service use a DtFetcher implementation matching this service text. * @param url pass this URL to fetcher after stripping any http/s prefix. * @param renewer pass this renewer to the fetcher. * @param conf Configuration object passed along. * @throws IOException// w w w . ja va 2 s.co m */ public static void getTokenFile(File tokenFile, String fileFormat, Text alias, Text service, String url, String renewer, Configuration conf) throws Exception { Token<?> token = null; Credentials creds = tokenFile.exists() ? Credentials.readTokenStorageFile(tokenFile, conf) : new Credentials(); ServiceLoader<DtFetcher> loader = ServiceLoader.load(DtFetcher.class); for (DtFetcher fetcher : loader) { if (matchService(fetcher, service, url)) { if (!fetcher.isTokenRequired()) { String message = "DtFetcher for service '" + service + "' does not require a token. Check your configuration. " + "Note: security may be disabled or there may be two DtFetcher " + "providers for the same service designation."; LOG.error(message); throw new IllegalArgumentException(message); } token = fetcher.addDelegationTokens(conf, creds, renewer, stripPrefix(url)); } } if (alias != null) { if (token == null) { String message = "DtFetcher for service '" + service + "'" + " does not allow aliasing. Cannot apply alias '" + alias + "'." + " Drop alias flag to get token for this service."; LOG.error(message); throw new IOException(message); } Token<?> aliasedToken = token.copyToken(); aliasedToken.setService(alias); creds.addToken(alias, aliasedToken); LOG.info("Add token with service " + alias); } doFormattedWrite(tokenFile, fileFormat, creds, conf); }
From source file:org.acmsl.queryj.tools.QueryJChain.java
/** * Fills given chain with external template bundles. * @param chain the chain.//from w w w. j ava 2 s .c o m * @throws QueryJBuildException if the handlers cannot be retrieved. */ @SuppressWarnings("unchecked") protected void fillTemplateHandlers(@NotNull final Chain<QueryJCommand, QueryJBuildException, CH> chain) throws QueryJBuildException { // Don't know how to fix the generics warnings @NotNull final ServiceLoader<TemplateChainProvider> loader = ServiceLoader.load(TemplateChainProvider.class); if (loader.iterator().hasNext()) { // Don't know how to fix the generics warnings @NotNull final TemplateChainProvider provider = loader.iterator().next(); // Don't know how to fix the generics warnings for (@Nullable final TemplateHandler<?> handler : (List<TemplateHandler<?>>) provider.getHandlers()) { if (handler != null) { chain.add((CH) handler); } } } else { throw new CannotFindTemplatesException(TemplateChainProvider.class); } }
From source file:org.projectforge.business.user.UserRightServiceImpl.java
private void initUserRightIds() { ServiceLoader<RightRightIdProviderService> serviceLoader = ServiceLoader .load(RightRightIdProviderService.class); for (RightRightIdProviderService service : serviceLoader) { String cname = service.getClass().getName(); for (IUserRightId uid : service.getUserRightIds()) { if (userRightIds.containsKey(uid.getId()) == true) { Log.error("Duplicated UserId: " + uid.getId()); }// w ww .jav a 2 s . c o m userRightIds.put(uid.getId(), uid); } } }
From source file:com.amalto.core.storage.datasource.DataSourceFactory.java
private static DataSource getDataSourceConfiguration(Node document, String name, String path) throws XPathExpressionException { Node dataSource = (Node) evaluate(document, path, XPathConstants.NODE); if (dataSource == null) { return null; }// ww w . ja v a2 s. co m String type = (String) evaluate(dataSource, "type", XPathConstants.STRING); //$NON-NLS-1$ // Invoke extensions for datasource extensions ServiceLoader<DataSourceExtension> extensions = ServiceLoader.load(DataSourceExtension.class); if (LOGGER.isDebugEnabled()) { StringBuilder extensionsAsString = new StringBuilder(); int i = 0; for (DataSourceExtension extension : extensions) { extensionsAsString.append(extension.getClass().getName()).append(' '); i++; } if (i == 0) { LOGGER.debug("No datasource extension found"); } else { LOGGER.debug("Found datasource extensions (" + i + " found): " + extensionsAsString); } } for (DataSourceExtension extension : extensions) { if (extension.accept(type)) { return extension.create(dataSource, name); } else { LOGGER.debug("Extension '" + extension + "' is not eligible for datasource type '" + type + "'."); } } throw new NotImplementedException("No support for type '" + type + "'."); }
From source file:org.camunda.bpm.admin.impl.web.SetupResource.java
protected ProcessEngine lookupProcessEngine(String engineName) { ServiceLoader<ProcessEngineProvider> serviceLoader = ServiceLoader.load(ProcessEngineProvider.class); Iterator<ProcessEngineProvider> iterator = serviceLoader.iterator(); if (iterator.hasNext()) { ProcessEngineProvider provider = iterator.next(); return provider.getProcessEngine(engineName); } else {/*from w w w. j a v a 2s . c o m*/ throw new RestException(Status.BAD_REQUEST, "Could not find an implementation of the " + ProcessEngineProvider.class + "- SPI"); } }
From source file:com.googlecode.fascinator.api.PluginManager.java
/** * Gets an authentication plugin/*from w w w .ja va 2 s . c om*/ * * @param id plugin identifier * @return an authentication plugin, or null if not found */ public static Authentication getAuthentication(String id) { Class<Authentication> clazz = (Class<Authentication>) cache.getIfPresent("authentication" + 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<Authentication> plugins = ServiceLoader.load(Authentication.class); for (Authentication plugin : plugins) { if (id.equals(plugin.getId())) { return plugin; } } File groovyFile = getPathFile("plugins/authentication/" + id + ".groovy"); if (groovyFile.exists()) { GroovyClassLoader gcl = new GroovyClassLoader(); try { clazz = gcl.parseClass(groovyFile); cache.put("authentication" + 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.apache.hadoop.gateway.identityasserter.function.UsernameFunctionProcessorTest.java
@Test public void testServiceLoader() throws Exception { ServiceLoader loader = ServiceLoader.load(UrlRewriteFunctionProcessor.class); Iterator iterator = loader.iterator(); while (iterator.hasNext()) { Object object = iterator.next(); if (object instanceof UsernameFunctionProcessor) { return; }//from ww w .jav a 2 s. com } fail("Failed to find UsernameFunctionProcessor via service loader."); }
From source file:org.commonjava.freeki.cli.Main.java
public void run() throws IOException, InvalidRemoteException, TransportException, GitAPIException { if (!canStart) { return;/*from w w w. j ava 2 s .co m*/ } start(); final Vertx v = new DefaultVertx(); setVertx(v); final GitManager git = new GitManager(config); final FreekiStore store = new FreekiStore(config, git); final Map<String, String> rawTemplateConf = new HashMap<>(); rawTemplateConf.put("group@" + ContentType.TEXT_HTML.value(), "groovy/html/group.groovy"); rawTemplateConf.put("page@" + ContentType.TEXT_HTML.value(), "groovy/html/page.groovy"); rawTemplateConf.put("group@" + ContentType.TEXT_PLAIN.value(), "groovy/plain/group.groovy"); rawTemplateConf.put("page@" + ContentType.TEXT_PLAIN.value(), "groovy/plain/page.groovy"); final GTemplateConfig templateConfig = new GTemplateConfig(rawTemplateConf, config); final Set<ContentRenderer> renderers = new HashSet<>(); renderers.add(new GTHtmlRenderer(templates, /*proc,*/templateConfig)); renderers.add(new GTTextRenderer(templates, templateConfig)); final JsonSerializer serializer = new JsonSerializer(/* new PrettyPrintingAdapter() */); renderers.add(new JsonRenderer(serializer)); final RenderingEngine engine = new RenderingEngine(renderers); final Authorizer authorizer = new Authorizer(config); final StaticContentHandler staticContent = new StaticContentHandler(config); final Set<RouteHandler> handlers = new HashSet<RouteHandler>() { private static final long serialVersionUID = 1L; { add(new GroupContentHandler(store, engine, authorizer)); add(new PageContentHandler(store, engine, authorizer)); add(staticContent); add(new UpdateHandler(git)); add(new TemplateContentHandler(new TemplateController(store, config), serializer)); add(new ExportContentHandler(config, store)); } }; final ServiceLoader<RouteCollection> collections = ServiceLoader.load(RouteCollection.class); final ApplicationRouter router = new ApplicationRouter(handlers, collections); router.noMatch(staticContent); final String listen = config.getListen(); vertx.createHttpServer().requestHandler(router).listen(config.getPort(), listen); printDiagnostics(git, config); System.out.printf("Listening for requests on %s:%s\n\n", config.getListen(), config.getPort()); synchronized (this) { try { wait(); } catch (final InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }