下面列出了怎么用com.google.inject.ConfigurationException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testValidation()
throws IOException
{
Path securityConfigFile = Files.createTempFile(null, null);
assertThatThrownBy(() -> newInstance(ImmutableMap.of(SECURITY_REFRESH_PERIOD, "1ms")))
.isInstanceOf(ConfigurationException.class)
.hasMessageContaining("security.config-file: may not be null ");
assertThatThrownBy(() -> newInstance(ImmutableMap.of(
SECURITY_CONFIG_FILE, securityConfigFile.toString(),
SECURITY_REFRESH_PERIOD, "1us")))
.isInstanceOf(ConfigurationException.class)
.hasMessageContaining("Invalid configuration property security.refresh-period");
newInstance(ImmutableMap.of(SECURITY_CONFIG_FILE, securityConfigFile.toString()));
}
@Test
public void testLoadMap() throws Exception {
Map<String, TestInterface> services = target.loadMap(TestInterface.class);
assertTrue(services.get("TestImpl1") instanceof TestInterface.TestImpl1);
assertTrue(services.get("TestImpl3") instanceof TestInterface.TestImpl3);
assertEquals(services.size(), 2, services.toString());
for (TestInterface s : services.values()) {
assertNotNull(s.getInjector());
assertNotNull(s.getInjector().getInstance(ImmutableConfiguration.class));
try {
s.getInjector().getInstance(ServiceFactory.class);
fail();
} catch (ConfigurationException e) {
// Success
}
}
}
@Test
void createServiceFailsIfNoServiceBindingsInModule() {
ServiceArtifactId artifactId = ServiceArtifactId
.newJavaId("com.acme/incomplete-service", "1.0.0");
LoadedServiceDefinition serviceDefinition = LoadedServiceDefinition
.newInstance(artifactId, IncompleteServiceModule::new);
ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(TEST_NAME,
TEST_ID, artifactId);
Node node = mock(Node.class);
// Try to create the service
Exception e = assertThrows(ConfigurationException.class,
() -> factory.createService(serviceDefinition, instanceSpec, node));
// Check the message indicates missing bindings
assertThat(e).hasMessageContaining(Service.class.getSimpleName());
}
private static <T> T instantiateClass(Class<? extends T> cl) {
try {
return MCRInjectorConfig.injector().getInstance(cl);
} catch (ConfigurationException e) {
// no default or injectable constructor, check for singleton factory method
try {
return (T) Stream.of(cl.getMethods())
.filter(m -> m.getReturnType().isAssignableFrom(cl))
.filter(m -> Modifier.isStatic(m.getModifiers()))
.filter(m -> Modifier.isPublic(m.getModifiers()))
.filter(m -> m.getName().toLowerCase(Locale.ROOT).contains("instance"))
.findAny()
.orElseThrow(() -> new MCRConfigurationException("Could not instantiate class " + cl.getName(), e))
.invoke(cl, (Object[]) null);
} catch (ReflectiveOperationException r) {
throw new MCRConfigurationException("Could not instantiate class " + cl.getName(), r);
}
}
}
private Node lookupOrCreateGlobalComponent(Node node, Injector fallbackInjector, Class<?> clazz, Key<?> key) {
Optional<Node> component = lookupGlobalComponent(key);
if (component.isEmpty()) {
Object instance;
try {
log.log(Level.FINE, "Trying the fallback injector to create" + messageForNoGlobalComponent(clazz, node));
instance = fallbackInjector.getInstance(key);
} catch (ConfigurationException e) {
throw removeStackTrace(new IllegalStateException(
(messageForMultipleClassLoaders(clazz).isEmpty()) ? "No global" + messageForNoGlobalComponent(clazz, node)
: messageForMultipleClassLoaders(clazz)));
}
component = Optional.of(matchingGuiceNode(key, instance).orElseGet(() -> {
GuiceNode guiceNode = new GuiceNode(instance, key.getAnnotation());
add(guiceNode);
return guiceNode;
}));
}
return component.get();
}
/**
* Finds the {@link IResourceServiceProvider} for a language by given its id.
*
* @param languageId
* the language id (grammar name)
* @return the {@link IResourceServiceProvider} for the given language id
*/
public IResourceServiceProvider getResourceServiceProviderById(final String languageId) {
ImmutableMap<Map<String, Object>, ? extends Function<String, IResourceServiceProvider>> resourceProvidersMap = getProviderMaps();
for (Map.Entry<Map<String, Object>, ? extends Function<String, IResourceServiceProvider>> mapEntry : resourceProvidersMap.entrySet()) {
Map<String, Object> map = mapEntry.getKey();
for (Map.Entry<String, Object> entry : map.entrySet()) {
try {
IResourceServiceProvider resourceServiceProvider = mapEntry.getValue().apply(entry.getKey());
if (resourceServiceProvider == null) {
continue;
}
IGrammarAccess grammarAccess = resourceServiceProvider.get(IGrammarAccess.class);
if (grammarAccess != null && grammarAccess.getGrammar().getName().equals(languageId)) {
return resourceServiceProvider;
}
// CHECKSTYLE:OFF
} catch (ConfigurationException ex) {
// CHECKSTYLE:ON
// ignore
}
}
}
return null;
}
/**
* Gets the all languages available in the workbench.
*
* @return set of all languages
*/
public Set<String> getAllLanguages() {
Set<String> languages = new HashSet<String>();
for (String extension : Registry.INSTANCE.getExtensionToFactoryMap().keySet()) {
final URI dummyUri = URI.createURI("foo:/foo." + extension);
IResourceServiceProvider resourceServiceProvider = Registry.INSTANCE.getResourceServiceProvider(dummyUri);
// By checking that description manager is AbstractCachingResourceDescriptionManager we exclude technical languages of the framework
if (resourceServiceProvider != null && resourceServiceProvider.getResourceDescriptionManager() instanceof AbstractCachingResourceDescriptionManager) {
try {
IGrammarAccess grammarAccess = resourceServiceProvider.get(IGrammarAccess.class);
if (grammarAccess != null && grammarAccess.getGrammar() != null) {
languages.add(grammarAccess.getGrammar().getName());
}
} catch (ConfigurationException e) {
// Will happen if no binding for IGrammarAccess was present.
}
}
}
return languages;
}
/**
* Find and invoke the relevant {@link SpecificationConverter} for the given specification to
* convert it into an object of type {@link T}.
*
* @param specification the specification to convert.
* @param context the translation context.
* @param <S> the type of the specification to convert.
* @return the converted target object representing the given specification.
*/
protected <S extends Specification<?>> T convert(S specification, C context) {
if (specification instanceof SubstitutableSpecification) {
return convert(((SubstitutableSpecification<?>) specification).getSubstitute(), context);
} else {
SpecificationConverter<S, C, T> converter;
Class<? extends Specification> specificationClass = specification.getClass();
try {
converter = injector.getInstance(buildKey(specificationClass));
} catch (ConfigurationException e) {
throw BusinessException.wrap(e, BusinessErrorCode.NO_CONVERTER_FOUND)
.put("contextClass", contextClass)
.put("targetClass", targetClass)
.put("specificationClass", specificationClass);
}
return converter.convert(specification, context, this);
}
}
int execute(String cliCommand, CliContext cliContext, Map<String, String> kernelParameters) throws Exception {
if (launched.compareAndSet(false, true)) {
KernelConfiguration kernelConfiguration = NuunCore.newKernelConfiguration();
for (Map.Entry<String, String> kernelParameter : kernelParameters.entrySet()) {
kernelConfiguration.param(kernelParameter.getKey(), kernelParameter.getValue());
}
kernel = Seed.createKernel(cliContext, kernelConfiguration, true);
CommandLineHandler cliHandler;
try {
cliHandler = kernel.objectGraph()
.as(Injector.class)
.getInstance(Key.get(CommandLineHandler.class, Names.named(cliCommand)));
LOGGER.info("Executing CLI command {}, handled by {}",
cliCommand,
cliHandler.getClass().getCanonicalName());
} catch (ConfigurationException e) {
throw SeedException.wrap(e, CliErrorCode.COMMAND_LINE_HANDLER_NOT_FOUND)
.put("commandLineHandler", cliCommand);
}
return cliHandler.call();
} else {
throw SeedException.createNew(CliErrorCode.COMMAND_LINE_HANDLER_ALREADY_RUN);
}
}
@PostConstruct
public void checkConfig()
{
long maxQueryRangeDuration = (long) getMaxQueryRangeDuration().getValue(TimeUnit.SECONDS);
long queryChunkSizeDuration = (long) getQueryChunkSizeDuration().getValue(TimeUnit.SECONDS);
if (maxQueryRangeDuration < queryChunkSizeDuration) {
throw new ConfigurationException(ImmutableList.of(new Message("prometheus.max.query.range.duration must be greater than prometheus.query.chunk.size.duration")));
}
}
@Test
public void testFailOnDurationLessThanQueryChunkConfig()
throws Exception
{
PrometheusConnectorConfig config = new PrometheusConnectorConfig();
config.setPrometheusURI(new URI("http://doesnotmatter.com"));
config.setQueryChunkSizeDuration(Duration.valueOf("21d"));
config.setMaxQueryRangeDuration(Duration.valueOf("1d"));
config.setCacheDuration(Duration.valueOf("30s"));
assertThatThrownBy(() -> config.checkConfig())
.isInstanceOf(ConfigurationException.class)
.hasMessageContaining("prometheus.max.query.range.duration must be greater than prometheus.query.chunk.size.duration");
}
private static <O> O findOne(Injector injector, Class<O> type) {
try {
return injector.getInstance(type);
} catch (ConfigurationException e) {
LOG.trace("Missed direct resolution of type={}", type.getSimpleName());
}
List<O> instances = search(injector, type);
if (!instances.isEmpty()) {
return instances.get(0);
}
return null;
}
@Override
public ComponentRenderer load(final Class<? extends BaseComponent> type) throws Exception {
ConfigurationException originalException = null;
for(Class c = type; BaseComponent.class.isAssignableFrom(c); c = c.getSuperclass()) {
try {
return (ComponentRenderer) injector.getInstance(Key.get(ComponentRenderers.rendererType(c)));
} catch(ConfigurationException e) {
if(originalException == null) originalException = e;
}
}
throw new IllegalStateException("Can't find a renderer for component type " + type, originalException);
}
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext)
throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
if (getBindingAnnotations(parameter).size() > 1) {
return false;
}
Key<?> key = getKey(
extensionContext.getTestClass(),
parameter);
Optional<Injector> optInjector = getInjectorForParameterResolution(extensionContext);
return optInjector.filter(injector -> {
// Do not bind String without explicit bindings.
if (key.equals(Key.get(String.class)) && injector.getExistingBinding(key) == null) {
return false;
}
try {
injector.getInstance(key);
return true;
} catch (ConfigurationException | ProvisionException e) {
// If we throw a ParameterResolutionException here instead of returning false, we'll block
// other ParameterResolvers from being able to work.
return false;
}
}).isPresent();
}
@Override
public <T extends Object> T get(final Class<T> t) {
try {
return injector.<T>getInstance(t);
} catch (final ConfigurationException e) {
return null;
}
}
@Test(expected = ConfigurationException.class)
public void testEmptyInjectorNoJIT() {
Injector injector = Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.requireExplicitBindings();
}
});
Assert.assertNull(injector.getExistingBinding(Key.get(String.class)));
injector.getInstance(String.class);
}
@Test(expected = ConfigurationException.class)
public void testEmptyChildInjectorNoJIT() {
Injector injector = Guice.createInjector().createChildInjector(new Module() {
@Override
public void configure(Binder binder) {
binder.requireExplicitBindings();
}
});
Assert.assertNull(injector.getExistingBinding(Key.get(String.class)));
injector.getInstance(String.class);
}
@Override
public String get() {
try {
return injector.getInstance(key);
} catch (ConfigurationException e) { // NOSONAR no need to logs
throw new GossipInitializeException("[" + keyName + "] should be configured on gossip.properties");
}
}
private void assertPrivate(Injector injector, Class<?> type) {
try {
injector.getInstance(type);
fail();
} catch (ConfigurationException e) {
// Expected
}
}
private void assertPrivate(Injector injector, Class<?> type) {
try {
injector.getInstance(type);
fail();
} catch (ConfigurationException e) {
// Expected
}
}
private void assertPrivate(Injector injector, Class<?> type) {
try {
injector.getInstance(type);
fail();
} catch (ConfigurationException e) {
// Expected
}
}
private void assertPrivate(Injector injector, Class<?> type) {
try {
injector.getInstance(type);
fail();
} catch (ConfigurationException e) {
// Expected
}
}
private void assertPrivate(Injector injector, Class<?> type) {
try {
injector.getInstance(type);
fail();
} catch (ConfigurationException e) {
// Expected
}
}
private Optional<Path> injectedApplicationPath() {
try {
return Optional.ofNullable(injector.getInstance(Key.get(Path.class, APPLICATION_PATH_NAME)));
} catch (ConfigurationException | ProvisionException ignored) {
}
return Optional.empty();
}
private static void assertNoBinding(GuiceRepository guice, String name) {
try {
guice.getInjector().getInstance(Key.get(String.class, Names.named(name)));
fail();
} catch (ConfigurationException e) {
}
}
@Test
public void requireThatStartFailsWithoutApplication() throws Exception {
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
Collections.<Module>emptyList());
try {
loader.init(null, false);
loader.start();
fail();
} catch (ConfigurationException e) {
}
}
@Override
public <T> T get(Class<T> t) {
try {
return injector.getInstance(t);
} catch (ConfigurationException e) {
return null;
}
}
@Override
public <T> T get(Class<T> t) {
try {
return injector.getInstance(t);
} catch (ConfigurationException e) {
return null;
}
}
/**
* For each {@link IResourceDescription.Delta} searches and calls the responsible {@link ILanguageSpecificBuilderParticipant}s.
*
* @param buildContext
* the {@link IBuildContext}, must not be {@code null}
* @param monitor
* the {@link IProgressMonitor}, must not be {@code null}
*/
protected void buildLanguageSpecificParticipants(final IBuildContext buildContext, final IProgressMonitor monitor) {
initParticipants();
SubMonitor progress = SubMonitor.convert(monitor, buildContext.getDeltas().size() * MONITOR_PARTICIPANTS_PER_LANGUAGE);
Map<String, BuildContext> languageIdToBuildContext = Maps.newHashMap();
for (IResourceDescription.Delta delta : buildContext.getDeltas()) {
IResourceServiceProvider resourceServiceProvider = IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(delta.getUri());
if (resourceServiceProvider == null) {
progress.worked(MONITOR_PARTICIPANTS_PER_LANGUAGE);
continue;
}
IGrammarAccess grammarAccess = null;
try {
grammarAccess = resourceServiceProvider.get(IGrammarAccess.class);
} catch (ConfigurationException e) {
progress.worked(MONITOR_PARTICIPANTS_PER_LANGUAGE);
continue;
}
if (grammarAccess == null) {
progress.worked(MONITOR_PARTICIPANTS_PER_LANGUAGE);
continue;
}
String languageId = grammarAccess.getGrammar().getName();
BuildContext entryBuildContext = languageIdToBuildContext.get(languageId);
if (entryBuildContext == null) {
entryBuildContext = new BuildContext(buildContext.getBuiltProject(), buildContext.getResourceSet(), buildContext.getBuildType());
languageIdToBuildContext.put(languageId, entryBuildContext);
}
entryBuildContext.addDelta(delta);
}
builLanguageSpecificContext(buildContext, progress, languageIdToBuildContext);
}
@Override
public CapabilityFactory get(final CapabilityType type) {
CapabilityFactory factory = factories.get(checkNotNull(type).toString());
if (factory == null) {
factory = dynamicFactories.get(checkNotNull(type).toString());
}
if (factory == null) {
final CapabilityDescriptor descriptor = capabilityDescriptorRegistry.get(type);
if (descriptor instanceof CapabilityFactory) {
factory = (CapabilityFactory) descriptor;
}
if (factory == null) {
try {
final Iterable<? extends BeanEntry<?, Capability>> entries = beanLocator.locate(
Key.get(Capability.class, named(type.toString()))
);
if (entries != null && entries.iterator().hasNext()) {
factory = new CapabilityFactory()
{
@Override
public Capability create() {
return entries.iterator().next().getValue();
}
};
}
}
catch (ConfigurationException ignore) {
// ignore
}
}
}
return factory;
}