下面列出了怎么用java.util.ServiceConfigurationError的API类实例代码及写法,或者点击链接到github查看源代码。
private static <T> T findServiceProvider(final Class<T> type)
throws DatatypeConfigurationException
{
try {
return AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
final Iterator<T> iterator = serviceLoader.iterator();
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
}
});
} catch(ServiceConfigurationError e) {
final DatatypeConfigurationException error =
new DatatypeConfigurationException(
"Provider for " + type + " cannot be found", e);
throw error;
}
}
/**
* Invoke to find all services for given service type using specified class loader
*
* @param classLoader specified class loader
* @param serviceType given service type
* @return List of found services
*/
public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {
List<T> foundServices = new ArrayList<>();
Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();
while (checkHasNextSafely(iterator)) {
try {
T item = iterator.next();
foundServices.add(item);
LOGGER.debug(String.format("Found %s [%s]", serviceType.getSimpleName(), item.toString()));
} catch (ServiceConfigurationError e) {
LOGGER.trace("Can't find services using Java SPI", e);
LOGGER.error(e.getMessage());
}
}
return foundServices;
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static <T> T findServiceProvider(final Class<T> type)
throws DatatypeConfigurationException
{
try {
return AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
final Iterator<T> iterator = serviceLoader.iterator();
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
}
});
} catch(ServiceConfigurationError e) {
final DatatypeConfigurationException error =
new DatatypeConfigurationException(
"Provider for " + type + " cannot be found", e);
throw error;
}
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
/**
* Use the ServiceLoader mechanism to load the default RowSetFactory
* @return default RowSetFactory Implementation
*/
static private RowSetFactory loadViaServiceLoader() throws SQLException {
RowSetFactory theFactory = null;
try {
trace("***in loadViaServiceLoader():");
for (RowSetFactory factory : ServiceLoader.load(javax.sql.rowset.RowSetFactory.class)) {
trace(" Loading done by the java.util.ServiceLoader :" + factory.getClass().getName());
theFactory = factory;
break;
}
} catch (ServiceConfigurationError e) {
throw new SQLException(
"RowSetFactory: Error locating RowSetFactory using Service "
+ "Loader API: " + e, e);
}
return theFactory;
}
@SuppressWarnings("rawtypes")
public ExtractedEntities extractEntitiesFromSentences(Map[] sentences, boolean manuallyReplaceDemonyms, String langauge){
ExtractedEntities e = new ExtractedEntities();
try {
Iterator<EntityExtractor> extractors = loader.iterator();
while (extractors != null && extractors.hasNext()) {
EntityExtractor currentExtractor = extractors.next();
ExtractedEntities e2 = currentExtractor.extractEntitiesFromSentences(sentences, manuallyReplaceDemonyms, langauge);
e.merge(e2);
}
} catch (ServiceConfigurationError serviceError) {
e = null;
serviceError.printStackTrace();
}
return e;
}
private static boolean loadProviderFromProperty() {
String cn = System.getProperty("com.sun.net.httpserver.HttpServerProvider");
if (cn == null)
return false;
try {
Class<?> c = Class.forName(cn, true,
ClassLoader.getSystemClassLoader());
provider = (HttpServerProvider)c.newInstance();
return true;
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
SecurityException x) {
throw new ServiceConfigurationError(null, x);
}
}
private static Map<String, MetricReporterFactory> loadAvailableReporterFactories(@Nullable PluginManager pluginManager) {
final Map<String, MetricReporterFactory> reporterFactories = new HashMap<>(2);
final Iterator<MetricReporterFactory> factoryIterator = getAllReporterFactories(pluginManager);
// do not use streams or for-each loops here because they do not allow catching individual ServiceConfigurationErrors
// such an error might be caused if the META-INF/services contains an entry to a non-existing factory class
while (factoryIterator.hasNext()) {
try {
MetricReporterFactory factory = factoryIterator.next();
String factoryClassName = factory.getClass().getName();
MetricReporterFactory existingFactory = reporterFactories.get(factoryClassName);
if (existingFactory == null) {
reporterFactories.put(factoryClassName, factory);
LOG.debug("Found reporter factory {} at {} ",
factoryClassName,
new File(factory.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getCanonicalPath());
} else {
LOG.warn("Multiple implementations of the same reporter were found in 'lib' and/or 'plugins' directories for {}. It is recommended to remove redundant reporter JARs to resolve used versions' ambiguity.", factoryClassName);
}
} catch (Exception | ServiceConfigurationError e) {
LOG.warn("Error while loading reporter factory.", e);
}
}
return Collections.unmodifiableMap(reporterFactories);
}
private static boolean loadProviderAsService() {
ServiceLoader<SelectorProvider> sl =
ServiceLoader.load(SelectorProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<SelectorProvider> i = sl.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static boolean loadProviderFromProperty() {
String cm = System.getProperty("sun.net.ftpClientProvider");
if (cm == null) {
return false;
}
try {
Class<?> c = Class.forName(cm, true, null);
provider = (FtpClientProvider) c.newInstance();
return true;
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
SecurityException x) {
throw new ServiceConfigurationError(x.toString());
}
}
private static boolean loadProviderFromProperty() {
String cn = System.getProperty("com.sun.net.httpserver.HttpServerProvider");
if (cn == null)
return false;
try {
Class<?> c = Class.forName(cn, true,
ClassLoader.getSystemClassLoader());
provider = (HttpServerProvider)c.newInstance();
return true;
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
SecurityException x) {
throw new ServiceConfigurationError(null, x);
}
}
private static boolean loadProviderFromProperty() {
String cn = System.getProperty("com.sun.net.httpserver.HttpServerProvider");
if (cn == null)
return false;
try {
Class<?> c = Class.forName(cn, true,
ClassLoader.getSystemClassLoader());
provider = (HttpServerProvider)c.newInstance();
return true;
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
SecurityException x) {
throw new ServiceConfigurationError(null, x);
}
}
private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
if (procNames != null)
return true;
URL[] urls = new URL[1];
for(File pathElement : workingpath) {
try {
urls[0] = pathElement.toURI().toURL();
if (ServiceProxy.hasService(Processor.class, urls))
return true;
} catch (MalformedURLException ex) {
throw new AssertionError(ex);
}
catch (ServiceProxy.ServiceConfigurationError e) {
log.error(Errors.ProcBadConfigFile(e.getLocalizedMessage()));
return true;
}
}
return false;
}
/**
* Use the ServiceLoader mechanism to load the default RowSetFactory
* @return default RowSetFactory Implementation
*/
static private RowSetFactory loadViaServiceLoader() throws SQLException {
RowSetFactory theFactory = null;
try {
trace("***in loadViaServiceLoader():");
for (RowSetFactory factory : ServiceLoader.load(javax.sql.rowset.RowSetFactory.class)) {
trace(" Loading done by the java.util.ServiceLoader :" + factory.getClass().getName());
theFactory = factory;
break;
}
} catch (ServiceConfigurationError e) {
throw new SQLException(
"RowSetFactory: Error locating RowSetFactory using Service "
+ "Loader API: " + e, e);
}
return theFactory;
}
@Test(dataProvider = "badfactories",
expectedExceptions = ServiceConfigurationError.class)
public void testBadFactory(String testName, String ignore) throws Exception {
Path mods = compileTest(TEST1_MODULE);
// compile the bad factory
Path source = BADFACTORIES_DIR.resolve(testName);
Path output = Files.createTempDirectory(USER_DIR, "tmp");
boolean compiled = CompilerUtils.compile(source, output);
assertTrue(compiled);
// copy the compiled class into the module
Path classFile = Paths.get("p", "ProviderFactory.class");
Files.copy(output.resolve(classFile),
mods.resolve(TEST1_MODULE).resolve(classFile),
StandardCopyOption.REPLACE_EXISTING);
// load providers and instantiate each one
loadProviders(mods, TEST1_MODULE).forEach(Provider::get);
}
private static boolean loadProviderAsService() {
ServiceLoader<SelectorProvider> sl =
ServiceLoader.load(SelectorProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<SelectorProvider> i = sl.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
/**
* Check {@link java.util.Iterator#hasNext()} safely.
*
* @param iterator specified Iterator to check hasNext
* @return true if {@link java.util.Iterator#hasNext()} checked successfully, false otherwise.
*/
public static boolean checkHasNextSafely(Iterator iterator) {
try {
/* Throw a ServiceConfigurationError if a provider-configuration file violates the specified format,
or if it names a provider class that cannot be found and instantiated, or if the result of
instantiating the class is not assignable to the service type, or if any other kind of exception
or error is thrown as the next provider is located and instantiated.
@see http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html#iterator()
*/
return iterator.hasNext();
} catch (Exception | ServiceConfigurationError e) {
LOGGER.trace("Can't load some service using Java SPI", e);
LOGGER.error(e.getMessage());
return false;
}
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
/**
* Use the ServiceLoader mechanism to load the default RowSetFactory
* @return default RowSetFactory Implementation
*/
static private RowSetFactory loadViaServiceLoader() throws SQLException {
RowSetFactory theFactory = null;
try {
trace("***in loadViaServiceLoader():");
for (RowSetFactory factory : ServiceLoader.load(javax.sql.rowset.RowSetFactory.class)) {
trace(" Loading done by the java.util.ServiceLoader :" + factory.getClass().getName());
theFactory = factory;
break;
}
} catch (ServiceConfigurationError e) {
throw new SQLException(
"RowSetFactory: Error locating RowSetFactory using Service "
+ "Loader API: " + e, e);
}
return theFactory;
}
private static boolean loadProviderAsService() {
Iterator<HttpServerProvider> i =
ServiceLoader.load(HttpServerProvider.class,
ClassLoader.getSystemClassLoader())
.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static boolean loadProviderAsService() {
Iterator<HttpServerProvider> i =
ServiceLoader.load(HttpServerProvider.class,
ClassLoader.getSystemClassLoader())
.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
/**
* Use the ServiceLoader mechanism to load the default RowSetFactory
* @return default RowSetFactory Implementation
*/
static private RowSetFactory loadViaServiceLoader() throws SQLException {
RowSetFactory theFactory = null;
try {
trace("***in loadViaServiceLoader():");
for (RowSetFactory factory : ServiceLoader.load(javax.sql.rowset.RowSetFactory.class)) {
trace(" Loading done by the java.util.ServiceLoader :" + factory.getClass().getName());
theFactory = factory;
break;
}
} catch (ServiceConfigurationError e) {
throw new SQLException(
"RowSetFactory: Error locating RowSetFactory using Service "
+ "Loader API: " + e, e);
}
return theFactory;
}
private static boolean loadProviderAsService() {
ServiceLoader<SelectorProvider> sl =
ServiceLoader.load(SelectorProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<SelectorProvider> i = sl.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static boolean loadProviderAsService() {
ServiceLoader<SelectorProvider> sl =
ServiceLoader.load(SelectorProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<SelectorProvider> i = sl.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static boolean loadProviderAsService() {
ServiceLoader<SelectorProvider> sl =
ServiceLoader.load(SelectorProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<SelectorProvider> i = sl.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}