com.google.inject.ConfigurationException Java Examples

The following examples show how to use com.google.inject.ConfigurationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MCRConfiguration2.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #2
Source File: ComponentGraph.java    From vespa with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #3
Source File: ResourceServiceProviderLocator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: CheckCfgUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: GuiceServicesFactoryTest.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: ServiceFactoryImplTest.java    From cryptotrader with GNU Affero General Public License v3.0 6 votes vote down vote up
@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
        }

    }

}
 
Example #7
Source File: CliLauncher.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source File: TestFileBasedAccessControlConfig.java    From presto with Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #9
Source File: BaseSpecificationTranslator.java    From business with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #10
Source File: DefaultCapabilityFactoryRegistry.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #11
Source File: KaryonAbstractInjectorGrapher.java    From karyon with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the bindings for the root keys and their transitive dependencies.
 */
private Iterable<Binding<?>> getBindings(Injector injector, Set<Key<?>> root) {
    Set<Key<?>> keys = Sets.newHashSet(root);
    Set<Key<?>> visitedKeys = Sets.newHashSet();
    List<Binding<?>> bindings = Lists.newArrayList();
    TransitiveDependencyVisitor keyVisitor = new TransitiveDependencyVisitor();

    while (!keys.isEmpty()) {
        Iterator<Key<?>> iterator = keys.iterator();
        Key<?> key = iterator.next();
        iterator.remove();

        if (!visitedKeys.contains(key)) {
            try {
                Binding<?> binding = injector.getBinding(key);
                bindings.add(binding);
                visitedKeys.add(key);
                keys.addAll(binding.acceptTargetVisitor(keyVisitor));
            }
            catch (ConfigurationException e) {
                System.out.println("Missing binding for : " + key);
                visitedKeys.add(key);
            }
        }
    }
    return bindings;
}
 
Example #12
Source File: GuiceRepositoryTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static void assertNoBinding(GuiceRepository guice, String name) {
    try {
        guice.getInjector().getInstance(Key.get(String.class, Names.named(name)));
        fail();
    } catch (ConfigurationException e) {

    }
}
 
Example #13
Source File: ApplicationLoaderTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@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) {

    }
}
 
Example #14
Source File: GenericResourceServiceProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T> T get(Class<T> t) {
	try {
		return injector.getInstance(t);
	} catch (ConfigurationException e) {
		return null;
	}
}
 
Example #15
Source File: DefaultResourceServiceProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T> T get(Class<T> t) {
	try {
		return injector.getInstance(t);
	} catch (ConfigurationException e) {
		return null;
	}
}
 
Example #16
Source File: RegistryBuilderParticipant.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #17
Source File: AcaiTest.java    From acai with Apache License 2.0 5 votes vote down vote up
@Test
public void failingTestInjectionDoesNotAffectSubsequentTests() throws Throwable {
  Acai acai = new Acai(TestModule.class);
  try {
    acai.apply(statement, frameworkMethod, new TestWithUnsatisfiedBinding()).evaluate();
    assertWithMessage("Expected ConfigurationException to be thrown.").fail();
  } catch (ConfigurationException e) {
    // Expected: TestWithUnsatisfiedBinding requires binding not satisfied by TestModule.
  }

  acai.apply(statement, frameworkMethod, new ExampleTest()).evaluate();

  verify(statement, times(1)).evaluate();
}
 
Example #18
Source File: TckListener.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private TckResourcesCleaner getResourcesCleaner(Injector injector, Key<TckResourcesCleaner> key) {
  try {
    return injector.getInstance(key);
  } catch (ConfigurationException ignored) {
  }
  return null;
}
 
Example #19
Source File: ScheduleInjectionListener.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private <T> T getValue(Class<T> configurationType, String configurationKey) {
  try {
    return injectorProvider
        .get()
        .getInstance(Key.get(configurationType, Names.named(configurationKey)));
  } catch (ConfigurationException | ProvisionException e) {
    return null;
  }
}
 
Example #20
Source File: DataStoreModuleTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void assertPrivate(Injector injector, Class<?> type) {
    try {
        injector.getInstance(type);
        fail();
    } catch (ConfigurationException e) {
        // Expected
    }
}
 
Example #21
Source File: JerseyContextResource.java    From dropwizard-guicier with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/is-resolvable-by-guice")
public boolean isResolvableByGuice(@QueryParam("className") String className) throws ClassNotFoundException {
  Class<?> clazz = Class.forName(className);
  try {
    return injector.getInstance(clazz) != null;
  } catch (ConfigurationException e) {
    return false;
  }
}
 
Example #22
Source File: AssemblerRegistryImpl.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T, D> Assembler<T, D> findAssemblerOf(Type aggregateRoot, Class<D> dto, @Nullable Annotation qualifier,
        @Nullable Class<? extends Annotation> qualifierClass) {
    Assembler<T, D> o;
    try {
        if (qualifier != null) {
            o = (Assembler<T, D>) getInstance(Assembler.class, qualifier, aggregateRoot, dto);
        } else if (qualifierClass != null) {
            o = (Assembler<T, D>) getInstance(Assembler.class, qualifierClass, aggregateRoot, dto);
        } else {
            o = (Assembler<T, D>) getInstance(Assembler.class, aggregateRoot, dto);
        }
    } catch (ConfigurationException e) {
        BusinessException seedException = BusinessException.createNew(
                BusinessErrorCode.UNABLE_TO_FIND_ASSEMBLER_WITH_QUALIFIER)
                .put("aggregateRoot", aggregateRoot)
                .put("dto", dto);
        if (qualifier != null) {
            seedException.put("qualifier", qualifier);
            throw seedException;
        } else if (qualifierClass != null) {
            seedException.put("qualifier", qualifierClass.getSimpleName());
            throw seedException;
        } else {
            throw BusinessException.createNew(BusinessErrorCode.UNABLE_TO_FIND_ASSEMBLER)
                    .put("aggregateRoot", aggregateRoot)
                    .put("dto", dto);
        }
    }
    return o;
}
 
Example #23
Source File: DeletedMessageVaultRetentionModule.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
RetentionConfiguration providesRetentionConfiguration(PropertiesProvider propertiesProvider) throws ConfigurationException, org.apache.commons.configuration2.ex.ConfigurationException {
    try {
        Configuration configuration = propertiesProvider.getConfiguration("deletedMessageVault");
        return RetentionConfiguration.from(configuration);
    } catch (FileNotFoundException e) {
        LOGGER.warn("Error encountered while retrieving Deleted message vault configuration. Using default RetentionTime (1 year) instead.");
        return RetentionConfiguration.DEFAULT;
    }
}
 
Example #24
Source File: TermFacetSelectorViewModelFactory.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
private TermFacetViewModelFactory findViewModelFactory(final TermFacetedSearchFormSettings<?> settings) {
    if (settings.getMapperSettings() != null) {
        try {
            final Named named = Names.named(settings.getMapperSettings().getName());
            return injector.getInstance(Key.get(TermFacetViewModelFactory.class, named));
        } catch (ConfigurationException e) {
            LOGGER.warn("Could not find term facet mapper with name \"{}\"", settings.getFieldName());
        }
    }
    return termFacetViewModelFactory;
}
 
Example #25
Source File: PlainInjectorTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source File: TestPrometheusConnectorConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #27
Source File: GuiceSmartAppDefinition.java    From smartapp-sdk-java with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #28
Source File: ComponentRendererRegistry.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: GuiceExtension.java    From junit5-extensions with MIT License 5 votes vote down vote up
@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();
}
 
Example #30
Source File: JavaResourceServiceProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T extends Object> T get(final Class<T> t) {
	try {
		return injector.<T>getInstance(t);
	} catch (final ConfigurationException e) {
		return null;
	}
}