use of java.util.ServiceLoader in project knox by apache.
the class HostmapFunctionProcessorTest method testServiceLoader.
@Test
public void testServiceLoader() throws Exception {
ServiceLoader loader = ServiceLoader.load(UrlRewriteFunctionProcessor.class);
Iterator iterator = loader.iterator();
assertThat("Service iterator empty.", iterator.hasNext());
while (iterator.hasNext()) {
Object object = iterator.next();
if (object instanceof HostmapFunctionProcessor) {
return;
}
}
fail("Failed to find " + HostmapFunctionProcessor.class.getName() + " via service loader.");
}
use of java.util.ServiceLoader in project Bytecoder by mirkosertic.
the class LoginContext method invoke.
private void invoke(String methodName) throws LoginException {
for (int i = moduleIndex; i < moduleStack.length; i++, moduleIndex++) {
try {
if (moduleStack[i].module == null) {
// locate and instantiate the LoginModule
//
String name = moduleStack[i].entry.getLoginModuleName();
ServiceLoader<LoginModule> sc = AccessController.doPrivileged((PrivilegedAction<ServiceLoader<LoginModule>>) () -> ServiceLoader.load(LoginModule.class, contextClassLoader));
for (LoginModule m : sc) {
if (m.getClass().getName().equals(name)) {
moduleStack[i].module = m;
if (debug != null) {
debug.println(name + " loaded as a service");
}
break;
}
}
if (moduleStack[i].module == null) {
try {
@SuppressWarnings("deprecation") Object tmp = Class.forName(name, false, contextClassLoader).newInstance();
moduleStack[i].module = (LoginModule) tmp;
if (debug != null) {
debug.println(name + " loaded via reflection");
}
} catch (ClassNotFoundException e) {
throw new LoginException("No LoginModule found for " + name);
}
}
// invoke the LoginModule initialize method
moduleStack[i].module.initialize(subject, callbackHandler, state, moduleStack[i].entry.getOptions());
}
// find the requested method in the LoginModule
boolean status;
switch(methodName) {
case LOGIN_METHOD:
status = moduleStack[i].module.login();
break;
case COMMIT_METHOD:
status = moduleStack[i].module.commit();
break;
case LOGOUT_METHOD:
status = moduleStack[i].module.logout();
break;
case ABORT_METHOD:
status = moduleStack[i].module.abort();
break;
default:
throw new AssertionError("Unknown method " + methodName);
}
if (status == true) {
// if SUFFICIENT, return if no prior REQUIRED errors
if (!methodName.equals(ABORT_METHOD) && !methodName.equals(LOGOUT_METHOD) && moduleStack[i].entry.getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT && firstRequiredError == null) {
// clear state
clearState();
if (debug != null)
debug.println(methodName + " SUFFICIENT success");
return;
}
if (debug != null)
debug.println(methodName + " success");
success = true;
} else {
if (debug != null)
debug.println(methodName + " ignored");
}
} catch (Exception ite) {
// failure cases
LoginException le;
if (ite instanceof PendingException && methodName.equals(LOGIN_METHOD)) {
throw (PendingException) ite;
} else if (ite instanceof LoginException) {
le = (LoginException) ite;
} else if (ite instanceof SecurityException) {
// do not want privacy leak
// (e.g., sensitive file path in exception msg)
le = new LoginException("Security Exception");
le.initCause(new SecurityException());
if (debug != null) {
debug.println("original security exception with detail msg " + "replaced by new exception with empty detail msg");
debug.println("original security exception: " + ite.toString());
}
} else {
// capture an unexpected LoginModule exception
java.io.StringWriter sw = new java.io.StringWriter();
ite.printStackTrace(new java.io.PrintWriter(sw));
sw.flush();
le = new LoginException(sw.toString());
}
if (moduleStack[i].entry.getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUISITE) {
if (debug != null)
debug.println(methodName + " REQUISITE failure");
// if REQUISITE, then immediately throw an exception
if (methodName.equals(ABORT_METHOD) || methodName.equals(LOGOUT_METHOD)) {
if (firstRequiredError == null)
firstRequiredError = le;
} else {
throwException(firstRequiredError, le);
}
} else if (moduleStack[i].entry.getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUIRED) {
if (debug != null)
debug.println(methodName + " REQUIRED failure");
// mark down that a REQUIRED module failed
if (firstRequiredError == null)
firstRequiredError = le;
} else {
if (debug != null)
debug.println(methodName + " OPTIONAL failure");
// mark down that an OPTIONAL module failed
if (firstError == null)
firstError = le;
}
}
}
// we went thru all the LoginModules.
if (firstRequiredError != null) {
// a REQUIRED module failed -- return the error
throwException(firstRequiredError, null);
} else if (success == false && firstError != null) {
// no module succeeded -- return the first error
throwException(firstError, null);
} else if (success == false) {
// no module succeeded -- all modules were IGNORED
throwException(new LoginException(ResourcesMgr.getString("Login.Failure.all.modules.ignored")), null);
} else {
// success
clearState();
return;
}
}
use of java.util.ServiceLoader in project Bytecoder by mirkosertic.
the class Bundles method loadBundleOf.
private static ResourceBundle loadBundleOf(String baseName, Locale targetLocale, Strategy strategy) {
Objects.requireNonNull(baseName);
Objects.requireNonNull(targetLocale);
Objects.requireNonNull(strategy);
CacheKey cacheKey = new CacheKey(baseName, targetLocale);
ResourceBundle bundle = null;
// Quick lookup of the cache.
BundleReference bundleRef = cacheList.get(cacheKey);
if (bundleRef != null) {
bundle = bundleRef.get();
}
// then return this bundle.
if (isValidBundle(bundle)) {
return bundle;
}
// Get the providers for loading the "leaf" bundle (i.e., bundle for
// targetLocale). If no providers are required for the bundle,
// none of its parents will require providers.
Class<? extends ResourceBundleProvider> type = strategy.getResourceBundleProviderType(baseName, targetLocale);
if (type != null) {
@SuppressWarnings("unchecked") ServiceLoader<ResourceBundleProvider> providers = (ServiceLoader<ResourceBundleProvider>) ServiceLoader.loadInstalled(type);
cacheKey.setProviders(providers);
}
List<Locale> candidateLocales = strategy.getCandidateLocales(baseName, targetLocale);
bundle = findBundleOf(cacheKey, strategy, baseName, candidateLocales, 0);
if (bundle == null) {
throwMissingResourceException(baseName, targetLocale, cacheKey.getCause());
}
return bundle;
}
use of java.util.ServiceLoader in project shiro by apache.
the class EnvironmentLoaderServiceTest method singleServiceTest.
@Test()
public void singleServiceTest() throws Exception {
List<WebEnvironmentStub> environmentList = Arrays.asList(new WebEnvironmentStub());
ServletContext servletContext = EasyMock.mock(ServletContext.class);
expect(servletContext.getInitParameter("shiroEnvironmentClass")).andReturn(null);
expect(servletContext.getInitParameter("shiroConfigLocations")).andReturn(null);
PowerMock.mockStaticPartialStrict(ServiceLoader.class, "load");
final ServiceLoader serviceLoader = PowerMock.createMock(ServiceLoader.class);
EasyMock.expect(ServiceLoader.load(WebEnvironment.class)).andReturn(serviceLoader);
EasyMock.expect(serviceLoader.iterator()).andReturn(environmentList.iterator());
EasyMock.replay(servletContext);
PowerMock.replayAll();
WebEnvironment resultEnvironment = new EnvironmentLoader().createEnvironment(servletContext);
PowerMock.verifyAll();
EasyMock.verify(servletContext);
assertThat(resultEnvironment, instanceOf(WebEnvironmentStub.class));
WebEnvironmentStub environmentStub = (WebEnvironmentStub) resultEnvironment;
assertThat(environmentStub.getServletContext(), sameInstance(servletContext));
}
use of java.util.ServiceLoader in project stdlib by petergeneric.
the class HibernateModule method getHibernateConfiguration.
@Provides
@Singleton
public Configuration getHibernateConfiguration(GuiceConfig guiceConfig, @Named(GuiceProperties.HIBERNATE_PROPERTIES) String propertyFileName, HibernateObservingInterceptor interceptor) {
final Properties properties = extractHibernateProperties(guiceConfig, propertyFileName);
validateHibernateProperties(guiceConfig, properties);
// Set up the hibernate Configuration
Configuration config = new Configuration();
// Set up the interceptor
config.setInterceptor(interceptor.getInterceptor());
config.addProperties(properties);
configure(config);
registerTypes(config);
{
ServiceLoader<HibernateConfigurationValidator> services = ServiceLoader.load(HibernateConfigurationValidator.class);
final Iterator<HibernateConfigurationValidator> it = services.iterator();
if (log.isTraceEnabled())
log.trace("Evaluate HibernateConfigurationValidators. has at least one=" + it.hasNext());
while (it.hasNext()) {
final HibernateConfigurationValidator validator = it.next();
if (log.isTraceEnabled())
log.trace("Validating hibernate configuration with " + validator);
// Have the validator check the hibernate/database configuration
validator.validate(config, properties, guiceConfig);
}
}
return config;
}
Aggregations