com.google.inject.ProvisionException Java Examples

The following examples show how to use com.google.inject.ProvisionException. 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: JoynrMessageScopeTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetScopedInstance() {
    Injector injector = setupInjectorWithScope();
    JoynrMessageScope scope = injector.getInstance(JoynrMessageScope.class);
    scope.activate();
    try {
        ScopedInstance instance = injector.getInstance(ScopedInstance.class);
        logger.debug("On first getInstance got: {}", instance);
        assertNotNull(instance);
        assertNull(instance.getValue());
        instance.setValue("myValue");
        ScopedInstance secondInstance = injector.getInstance(ScopedInstance.class);
        logger.debug("On second getInstance got: {}", secondInstance);
        assertNotNull(secondInstance);
        assertEquals("myValue", secondInstance.getValue());
    } finally {
        scope.deactivate();
    }
    try {
        injector.getInstance(ScopedInstance.class);
        fail("Should not be able to get scoped bean from inactive scope.");
    } catch (ProvisionException e) {
        // expected
        assertTrue(e.getCause() instanceof IllegalStateException);
    }
}
 
Example #2
Source File: LifecycleModule.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
private <I> Method findPostConstruct(final Class<? super I> rawType) {
    Method postConstructFound = null;
    for (final Method method : rawType.getDeclaredMethods()) {
        if (method.isAnnotationPresent(PostConstruct.class)) {
            if (method.getParameterTypes().length != 0) {
                throw new ProvisionException("A method annotated with @PostConstruct must not have any parameters");
            }
            if (method.getExceptionTypes().length > 0) {
                throw new ProvisionException("A method annotated with @PostConstruct must not throw any checked exceptions");
            }
            if (Modifier.isStatic(method.getModifiers())) {
                throw new ProvisionException("A method annotated with @PostConstruct must not be static");
            }
            if (postConstructFound != null) {
                throw new ProvisionException("More than one @PostConstruct method found for class " + rawType);
            }
            postConstructFound = method;
        }
    }
    return postConstructFound;
}
 
Example #3
Source File: LifecycleModule.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
private <I> void invokePostConstruct(final TypeEncounter<I> encounter, final Method postConstruct) {
    encounter.register(new InjectionListener<I>() {
        @Override
        public void afterInjection(final I injectee) {
            try {
                postConstruct.setAccessible(true);
                postConstruct.invoke(injectee);
            } catch (final IllegalAccessException | InvocationTargetException e) {
                if (e.getCause() instanceof UnrecoverableException) {
                    if (((UnrecoverableException) e.getCause()).isShowException()) {
                        log.error("An unrecoverable Exception occurred. Exiting HiveMQ", e);
                    }
                    System.exit(1);
                }
                throw new ProvisionException("An error occurred while calling @PostConstruct", e);
            }
        }
    });
}
 
Example #4
Source File: ReconContainerDBProvider.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
public DBStore get() {
  DBStore dbStore;
  File reconDbDir =
      reconUtils.getReconDbDir(configuration, OZONE_RECON_DB_DIR);
  File lastKnownContainerKeyDb =
      reconUtils.getLastKnownDB(reconDbDir, RECON_CONTAINER_KEY_DB);
  if (lastKnownContainerKeyDb != null) {
    LOG.info("Last known container-key DB : {}",
        lastKnownContainerKeyDb.getAbsolutePath());
    dbStore = initializeDBStore(configuration, reconUtils,
        lastKnownContainerKeyDb.getName());
  } else {
    dbStore = getNewDBStore(configuration, reconUtils);
  }
  if (dbStore == null) {
    throw new ProvisionException("Unable to provide instance of DBStore " +
        "store.");
  }
  return dbStore;
}
 
Example #5
Source File: DefaultModuleTest.java    From bromium with MIT License 6 votes vote down vote up
@Test
public void ifCommmandIsInvalidExceptionIsThrown() throws IOException {
    String command = "invalid";
    Map<String, Object> opts = new HashMap<>();
    opts.put(BROWSER, CHROME);
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, localhostUrl);
    opts.put(CASE, caseFile.getAbsolutePath());
    opts.put(SCREEN, screenString);
    opts.put(TIMEOUT, timeoutString);
    opts.put(PRECISION, precisionString);
    Module module = new DefaultModule(command, opts);
    Injector injector = Guice.createInjector(module);

    try {
        RequestFilter instance = injector.getInstance(
                Key.get(new TypeLiteral<IOProvider<RequestFilter>>() {})).get();
    } catch (ProvisionException e) {
        assertTrue(e.getCause() instanceof NoSuchCommandException);
    }
}
 
Example #6
Source File: DefaultModuleTest.java    From bromium with MIT License 6 votes vote down vote up
@Test
public void ifCommmandIsInvalidResponseExceptionIsThrown() throws IOException, URISyntaxException {
    String command = "invalid";
    Map<String, Object> opts = new HashMap<>();
    opts.put(BROWSER, CHROME);
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, localhostUrl);
    opts.put(CASE, caseFile.getAbsolutePath());
    opts.put(SCREEN, screenString);
    opts.put(TIMEOUT, timeoutString);
    opts.put(PRECISION, precisionString);
    Module module = new DefaultModule(command, opts);
    Injector injector = Guice.createInjector(module);

    try {
        IOProvider<ResponseFilter> instance = injector.getInstance(new Key<IOProvider<ResponseFilter>>() {});
        instance.get();
    } catch (ProvisionException e) {
        assertTrue(e.getCause() instanceof NoSuchCommandException);
    }
}
 
Example #7
Source File: ElasticSearchTransportClientProvider.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public Client get() {

    Settings settings = Settings.builder()
            .put("client.transport.ignore_cluster_name", true)
            .put("client.transport.sniff", true)
            .build();

    TransportClient tc = new PreBuiltTransportClient(settings);

    List<URI> clusterAddresses = configuration.getURIs();

    if (clusterAddresses.isEmpty()) {
        logger.warn(ElasticSearchConfiguration.ELASTIC_SEARCH_URL_PROPERTY_NAME +
                " is not set.  Indexing will remain DISABLED.");
    }
    for (URI hostAddress : clusterAddresses) {
        int port = Optional.ofNullable(hostAddress.getPort()).orElse(9200);
        try {
            tc.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostAddress.getHost()), port));
        } catch (UnknownHostException uhe){
            throw new ProvisionException("Invalid host" + hostAddress.getHost(), uhe);
        }
    }
    return tc;
}
 
Example #8
Source File: ElasticSearchTransportClientProvider.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public Client get() {

    Settings settings = Settings.builder()
            .put("client.transport.ignore_cluster_name", true)
            .put("client.transport.sniff", true)
            .build();

    TransportClient tc = new PreBuiltTransportClient(settings);

    List<URI> clusterAddresses = configuration.getURIs();

    if (clusterAddresses.isEmpty()) {
        logger.warn(ElasticSearchConfiguration.ELASTIC_SEARCH_URL_PROPERTY_NAME +
                " is not set.  Indexing will remain DISABLED.");
    }
    for (URI hostAddress : clusterAddresses) {
        int port = Optional.ofNullable(hostAddress.getPort()).orElse(9200);
        try {
            tc.addTransportAddress(new TransportAddress(InetAddress.getByName(hostAddress.getHost()), port));
        } catch (Exception e) {
            throw new ProvisionException("Invalid host" + hostAddress.getHost(), e);
        }
    }
    return tc;
}
 
Example #9
Source File: ClientInfoProviderImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Nullable
public ClientInfo getCurrentThreadClientInfo() {
  try {
    HttpServletRequest request = httpRequestProvider.get();
    return ClientInfo
        .builder()
        .userId(UserIdHelper.get())
        .remoteIP(request.getRemoteAddr())
        .userAgent(request.getHeader(HttpHeaders.USER_AGENT))
        .path(request.getServletPath())
        .build();
  }
  catch (ProvisionException | OutOfScopeException e) {
    // ignore; this happens when called out of scope of http request
    return null;
  }
}
 
Example #10
Source File: Guicer.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
private <T, S> void startServiceIfApplicable(T instance, ServiceLifecycleActions<S> withActions) {
    if (services.contains(instance)) {
        return;
    }
    if (withActions == null) {
        services.add(instance);
        return;
    }
    S service = withActions.castIfActionable(instance);
    if (service != null) {
        try {
            withActions.onStart(service);
            services.add(service);
        } catch (Exception e) {
            try {
                stopServices(withActions, e);
            } catch (Exception e1) {
                e = e1;
            }
            throw new ProvisionException("While starting service " + instance.getClass(), e);
        }
    }
}
 
Example #11
Source File: GuicerTest.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void errorOnStartup() throws Exception {
    Guicer guicer = messageGuicer(
            bind(DummyInterfaces.Alpha.class, DummyErroringServices.ErroringAlpha.class, true),
            bind(DummyInterfaces.Beta.class, DummyErroringServices.ErroringBeta.class, false),
            bind(DummyInterfaces.Gamma.class, DummyErroringServices.ErroringGamma.class, false)
    );
    try{
        startRequiredServices(guicer);
        fail("should have caught ErroringException");
    } catch (ProvisionException e) {
        assertEventualCause(e, DummyErroringServices.ErroringException.class);
        assertEquals(
                "messages",
                joined(
                        "starting ErroringAlpha",
                        "starting ErroringBeta",
                        "starting ErroringGamma",
                        "started ErroringGamma",
                        "stopping ErroringGamma",
                        "stopped ErroringGamma"
                ),
                Strings.join(DummyInterfaces.messages())
        );
    }
}
 
Example #12
Source File: JsonConfigurator.java    From druid-api with Apache License 2.0 6 votes vote down vote up
private <T> void verifyClazzIsConfigurable(Class<T> clazz)
{
  final List<BeanPropertyDefinition> beanDefs = jsonMapper.getSerializationConfig()
                                                            .introspect(jsonMapper.constructType(clazz))
                                                            .findProperties();
  for (BeanPropertyDefinition beanDef : beanDefs) {
    final AnnotatedField field = beanDef.getField();
    if (field == null || !field.hasAnnotation(JsonProperty.class)) {
      throw new ProvisionException(
          String.format(
              "JsonConfigurator requires Jackson-annotated Config objects to have field annotations. %s doesn't",
              clazz
          )
      );
    }
  }
}
 
Example #13
Source File: EverrestModule.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Application get() {
    ApplicationContext context = ApplicationContext.getCurrent();
    if (context == null) {
        throw new ProvisionException("EverRest ApplicationContext is not initialized.");
    }
    return context.getApplication();
}
 
Example #14
Source File: SigningSignatureHandler.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
public FileInputStream apply(String filename) {
  try {
    return new FileInputStream(filename);
  } catch (FileNotFoundException e) {
    throw new ProvisionException("could not read certificates", e);
  }
}
 
Example #15
Source File: SingularityMainModule.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Provides
@Named(CURRENT_HTTP_REQUEST)
public Optional<HttpServletRequest> providesUrl(
  Provider<HttpServletRequest> requestProvider
) {
  try {
    return Optional.of(requestProvider.get());
  } catch (ProvisionException pe) { // this will happen if we're not in the REQUEST scope
    return Optional.empty();
  }
}
 
Example #16
Source File: SingularityHeaderPassthroughAuthenticator.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private Optional<String> getUserId(ContainerRequestContext context) {
  try {
    return Optional.ofNullable(
      Strings.emptyToNull(context.getHeaderString(requestUserHeaderName))
    );
  } catch (ProvisionException pe) {
    return Optional.empty();
  }
}
 
Example #17
Source File: TestScopeTest.java    From acai with Apache License 2.0 5 votes vote down vote up
@Test
public void servicesInstantiatedOutsideTestScope() throws Throwable {
  FakeTestClass test = new FakeTestClass();

  thrown.expect(ProvisionException.class);
  thrown.expectMessage("@TestScoped binding outside test");
  new Acai(InvalidTestModule.class).apply(statement, frameworkMethod, test).evaluate();
}
 
Example #18
Source File: SeedConstraintValidatorFactory.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
    if (key.getName().startsWith("org.hibernate.validator")) {
        // Hibernate constraint validators are instantiated directly (no injection possible nor needed)
        return Classes.instantiateDefault(key);
    } else {
        try {
            return injector.getInstance(key);
        } catch (ProvisionException e) {
            LOGGER.warn("Constraint validator {} was not detected by SeedStack and is not injectable",
                    key.getName());
            return Classes.instantiateDefault(key);
        }
    }
}
 
Example #19
Source File: PersistenceModule.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
private Properties getHikariProperties(final String dataSourceClassName) {

    final Properties properties = new Properties();

    // different drivers requires different sets of properties
    switch (dataSourceClassName) {
      case POSTGRES_DS_CLASS:
        this.handlePostgresORMProperties(properties);
        break;
      case MYSQL_DS_CLASS:
        this.handleMySQLORMProperties(properties);
        break;
      default:
        throw new ProvisionException(
            String.format(
                "%s is not supported, valid data sources are %s",
                dataSourceClassName,
                Arrays.asList(POSTGRES_DS_CLASS, MYSQL_DS_CLASS)
            )
        );
    }
    // different drivers requires different sets of properties

    // driver agnostic properties
    this.handleCommonORMProperties(properties);
    // driver agnostic properties

    return properties;
  }
 
Example #20
Source File: PersistenceModule.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public SessionFactory sessionFactory() {
  try {
    Configuration configuration = new Configuration();
    configuration.addAnnotatedClass(AlarmDb.class);
    configuration.addAnnotatedClass(AlarmDefinitionDb.class);
    configuration.addAnnotatedClass(AlarmMetricDb.class);
    configuration.addAnnotatedClass(MetricDefinitionDb.class);
    configuration.addAnnotatedClass(MetricDefinitionDimensionsDb.class);
    configuration.addAnnotatedClass(MetricDimensionDb.class);
    configuration.addAnnotatedClass(SubAlarmDefinitionDb.class);
    configuration.addAnnotatedClass(SubAlarmDefinitionDimensionDb.class);
    configuration.addAnnotatedClass(SubAlarmDb.class);
    configuration.addAnnotatedClass(AlarmActionDb.class);
    configuration.addAnnotatedClass(NotificationMethodDb.class);

    // retrieve hikari properties for right driver
    configuration.setProperties(this.getHikariProperties(this.dbConfig.getDriverClass()));

    final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .build();

    // builds a session factory from the service registry
    return configuration.buildSessionFactory(serviceRegistry);
  } catch (Throwable ex) {
    throw new ProvisionException("Failed to provision Hibernate DB", ex);
  }
}
 
Example #21
Source File: DBIProvider.java    From monasca-persister with Apache License 2.0 5 votes vote down vote up
@Override
public DBI get() {
  try {
    return new DBIFactory().build(environment, configuration.getDataSourceFactory(), "vertica");
  } catch (ClassNotFoundException e) {
    throw new ProvisionException("Failed to provision DBI", e);
  }
}
 
Example #22
Source File: SunriseDefaultHttpErrorHandler.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletionStage<Result> onDevServerError(final Http.RequestHeader request, final UsefulException exception) {
    return Optional.ofNullable(exception.getCause())
            .map(Throwable::getCause)
            .filter(e -> e instanceof ProvisionException)
            .map(e -> (ProvisionException) e)
            .filter(e -> e.getErrorMessages().stream()
                    .anyMatch(m -> m.getCause() instanceof SphereClientCredentialsException))
            .map(e -> renderDevErrorPage(exception))
            .orElseGet(() ->  super.onDevServerError(request, exception));
}
 
Example #23
Source File: DropwizardEnvironmentModule.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public T get() {
    if (configuration == null) {
        throw new ProvisionException(ILLEGAL_DROPWIZARD_MODULE_STATE);
    }
    return configuration;
}
 
Example #24
Source File: DropwizardEnvironmentModule.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Provides
public Environment providesEnvironment() {
    if (environment == null) {
        throw new ProvisionException(ILLEGAL_DROPWIZARD_MODULE_STATE);
    }
    return environment;
}
 
Example #25
Source File: SigningSignatureHandler.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public FileInputStream apply(String filename) {
  try {
    return new FileInputStream(filename);
  } catch (FileNotFoundException e) {
    throw new ProvisionException("could not read certificates", e);
  }
}
 
Example #26
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 #27
Source File: URIConverter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object convert(String value, TypeLiteral<?> toType) {
  try {
    return new URI(value);
  } catch (URISyntaxException e) {
    throw new ProvisionException(String.format("Invalid URI '%s'", value), e);
  }
}
 
Example #28
Source File: Injection.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static RuntimeException wrapException(Throwable e) {
    if(e instanceof RuntimeException) {
        throw (RuntimeException) e;
    } else if(e instanceof Error) {
        throw (Error) e;
    } else {
        throw new ProvisionException("Provisioning error", e);
    }
}
 
Example #29
Source File: URLConverter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object convert(String value, TypeLiteral<?> toType) {
  try {
    return new URL(value);
  } catch (MalformedURLException e) {
    throw new ProvisionException(String.format("Invalid URL '%s'", value), e);
  }
}
 
Example #30
Source File: DatabaseModule.java    From monasca-common with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
  bind(DataSourceFactory.class).toInstance(config);
  bind(DBI.class).toProvider(new Provider<DBI>() {
    @Override
    public DBI get() {
      try {
        return new DBIFactory().build(environment, config, "platform");
      } catch (ClassNotFoundException e) {
        throw new ProvisionException("Failed to provision DBI", e);
      }
    }
  }).in(Scopes.SINGLETON);
}