Java Code Examples for com.google.inject.ProvisionException

The following are top voted examples for showing how to use com.google.inject.ProvisionException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Equella   File: PropertiesModule.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> void bindClass(TypeLiteral<T> key, String property)
{
	String value = Strings.nullToEmpty(getPropString(property)).trim();
	if( !Check.isEmpty(value) )
	{
		try
		{
			Class<?> clazz = getClass().getClassLoader().loadClass(value);
			bind(key).annotatedWith(Names.named(property)).toInstance((T) clazz);
		}
		catch( ClassNotFoundException e )
		{
			throw new ProvisionException("Class not found in property: " + property);
		}
	}
}
 
Example 2
Project: Equella   File: PropertiesModule.java   Source Code and License 6 votes vote down vote up
protected <T> void bindNewInstance(String property, Class<T> type)
{
	String value = Strings.nullToEmpty(getPropString(property)).trim();
	if( !Check.isEmpty(value) )
	{
		try
		{
			bind(type).annotatedWith(Names.named(property)).toInstance(
				type.cast(getClass().getClassLoader().loadClass(value).newInstance()));
		}
		// In the interests of diagnostics, we'll allow an explicit catch of
		// generic exception
		catch( Exception e ) // NOSONAR
		{
			throw new ProvisionException("Class not found in property: " + property);
		}
	}
}
 
Example 3
Project: bromium   File: DefaultModuleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void ifCommmandIsInvalidExceptionIsThrown() 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 {
        RequestFilter instance = injector.getInstance(
                Key.get(new TypeLiteral<IOProvider<RequestFilter>>() {})).get();
    } catch (ProvisionException e) {
        assertTrue(e.getCause() instanceof NoSuchCommandException);
    }
}
 
Example 4
Project: bromium   File: DefaultModuleTest.java   Source Code and 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 5
Project: apiman-cli   File: AbstractCommand.java   Source Code and License 6 votes vote down vote up
/**
 * @param args   the arguments
 * @param parser the command line parser containing usage information
 * @return a child Command for the given args, or <code>null</code> if not found
 */
protected Command getChildAction(List<String> args, CmdLineParser parser) {
    final String commandName = args.get(0);

    // find implementation
    final Class<? extends Command> commandClass = commandMap.get(commandName);
    if (null != commandClass) {
        try {
            final Command command = InjectionUtil.getInjector().getInstance(commandClass);
            command.setParent(this);
            command.setCommandName(commandName);

            return command;
        } catch (ProvisionException | ConfigurationException e) {
            throw new CommandException(String.format("Error getting child command for args: %s", args), e);
        }
    }
    return null;
}
 
Example 6
Project: Camel   File: NamedProviderSupport.java   Source Code and License 6 votes vote down vote up
protected Object provideObjectFromNamedBindingOrJndi(
        TypeLiteral<?> requiredType, String name) {
    Binding<?> binding = Injectors.getBinding(injector,
            Key.get(requiredType, Names.named(name)));
    if (binding != null) {
        return binding.getProvider().get();
    }

    // TODO we may want to try avoid the dependency on JNDI classes
    // for better operation in GAE?
    try {
        if (context == null) {
            context = new InitialContext();
        }
        return context.lookup(name);
    } catch (NamingException e) {
        throw new ProvisionException("Failed to find name '" + name
                + "' in JNDI. Cause: " + e, e);
    }
}
 
Example 7
Project: nexus-public   File: ClientInfoProviderImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public ClientInfo getCurrentThreadClientInfo() {
  try {
    HttpServletRequest request = httpRequestProvider.get();
    return new ClientInfo(
        UserIdHelper.get(),
        request.getRemoteAddr(),
        request.getHeader(HttpHeaders.USER_AGENT)
    );
  }
  catch (ProvisionException | OutOfScopeException e) {
    // ignore; this happens when called out of scope of http request
    return null;
  }
}
 
Example 8
Project: sql-layer   File: Guicer.java   Source Code and License 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 9
Project: sql-layer   File: GuicerTest.java   Source Code and License 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 10
Project: guice-bootstrap   File: TestBootstrap.java   Source Code and License 6 votes vote down vote up
@Test
public void testDoesNotAllowCircularDependencies()
        throws Exception
{
    Bootstrap bootstrap = new Bootstrap(new Module()
    {
        @Override
        public void configure(Binder binder)
        {
            binder.bind(InstanceA.class);
            binder.bind(InstanceB.class);
        }
    });

    try {
        bootstrap.initialize().getInstance(InstanceA.class);
        Assert.fail("should not allow circular dependencies");
    }
    catch (ProvisionException e) {
        assertContains(e.getErrorMessages().iterator().next().getMessage(), "circular proxies are disabled");
    }
}
 
Example 11
Project: gerrit-ci-plugin   File: CiDataSourceProvider.java   Source Code and License 6 votes vote down vote up
@Inject
protected CiDataSourceProvider(SitePaths site,
    @PluginName String pluginName,
    @Nullable MetricMaker metrics,
    Context ctx,
    CiDataSourceType dst) {
  File file = site.gerrit_config.toFile();
  FileBasedConfig cfg = new FileBasedConfig(file, FS.DETECTED);
  try {
    cfg.load();
  } catch (IOException | ConfigInvalidException e) {
    throw new ProvisionException(e.getMessage(), e);
  }
  this.config = new PluginConfig(pluginName, cfg);
  this.metrics = metrics;
  this.ctx = ctx;
  this.dst = dst;
}
 
Example 12
Project: wsf-gtfsrealtime   File: WSFRealtimeMain.java   Source Code and License 6 votes vote down vote up
public static void main(String... args) {
  WSFRealtimeMain m = new WSFRealtimeMain();

  ArgumentParser parser = ArgumentParsers.newArgumentParser("wsf-gtfsrealtime");
  parser.description("Produces a GTFS-realtime feed from the Washington State Ferries API");
  parser.addArgument("--" + ARG_CONFIG_FILE).type(File.class).help("configuration file path");
  Namespace parsedArgs;

  try {
    parsedArgs = parser.parseArgs(args);
    File configFile = parsedArgs.get(ARG_CONFIG_FILE);
    m.run(configFile);
  } catch (CreationException | ConfigurationException | ProvisionException e) {
    _log.error("Error in startup:", e);
    System.exit(-1);
  } catch (ArgumentParserException ex) {
    parser.handleError(ex);
  }
}
 
Example 13
Project: google-gin   File: MemberLiteral.java   Source Code and License 6 votes vote down vote up
protected Annotation getBindingAnnotation(Annotation[] annotations) {
  Annotation bindingAnnotation = null;
  for (Annotation annotation : annotations) {
    if (annotation.annotationType().getAnnotation(BindingAnnotation.class) != null
        || annotation.annotationType() == Named.class) {
      if (bindingAnnotation != null) {
        throw new ProvisionException(
            String.format("More than one binding annotation found on %s: %s, %s.",
                 this, annotation, bindingAnnotation));
      }

      bindingAnnotation = annotation;

      // Keep going so we can find any rogue additional binding annotations
    }
  }

  return bindingAnnotation;
}
 
Example 14
Project: spoofax-intellij   File: JavaServiceProvider.java   Source Code and License 6 votes vote down vote up
@Override
public T get() {
    final ServiceLoader<T> loader = ServiceLoader.load(this.service);
    final Iterator<T> iterator = loader.iterator();

    if (!iterator.hasNext()) {
        throw LoggerUtils2.exception(this.logger, ProvisionException.class,
                "No implementations are registered for the class {}.",
                this.service
        );
    }

    final T obj = iterator.next();

    if (iterator.hasNext()) {
        throw LoggerUtils2.exception(this.logger, ProvisionException.class,
                "Multiple implementations are registered for the class {}.",
                this.service
        );
    }

    return obj;
}
 
Example 15
Project: gerrit   File: SignedPushModule.java   Source Code and License 6 votes vote down vote up
@Override
public PublicKeyStore get() {
  final Repository repo;
  try {
    repo = repoManager.openRepository(allUsers);
  } catch (IOException e) {
    throw new ProvisionException("Cannot open " + allUsers, e);
  }
  return new PublicKeyStore(repo) {
    @Override
    public void close() {
      try {
        super.close();
      } finally {
        repo.close();
      }
    }
  };
}
 
Example 16
Project: gerrit   File: DynamicItem.java   Source Code and License 6 votes vote down vote up
/**
 * Set the element to provide.
 *
 * @param impl the item to add to the collection. Must not be null.
 * @param pluginName name of the source providing the implementation.
 * @return handle to remove the item at a later point in time.
 */
public RegistrationHandle set(Provider<T> impl, String pluginName) {
  final NamedProvider<T> item = new NamedProvider<>(impl, pluginName);
  NamedProvider<T> old = null;
  while (!ref.compareAndSet(old, item)) {
    old = ref.get();
    if (old != null && !"gerrit".equals(old.pluginName)) {
      throw new ProvisionException(
          String.format(
              "%s already provided by %s, ignoring plugin %s",
              key.getTypeLiteral(), old.pluginName, pluginName));
    }
  }

  final NamedProvider<T> defaultItem = old;
  return new RegistrationHandle() {
    @Override
    public void remove() {
      ref.compareAndSet(item, defaultItem);
    }
  };
}
 
Example 17
Project: gerrit   File: DynamicItem.java   Source Code and License 6 votes vote down vote up
/**
 * Set the element that may be hot-replaceable in the future.
 *
 * @param key unique description from the item's Guice binding. This can be later obtained from
 *     the registration handle to facilitate matching with the new equivalent instance during a
 *     hot reload.
 * @param impl the item to set as our value right now. Must not be null.
 * @param pluginName the name of the plugin providing the item.
 * @return a handle that can remove this item later, or hot-swap the item.
 */
public ReloadableRegistrationHandle<T> set(Key<T> key, Provider<T> impl, String pluginName) {
  final NamedProvider<T> item = new NamedProvider<>(impl, pluginName);
  NamedProvider<T> old = null;
  while (!ref.compareAndSet(old, item)) {
    old = ref.get();
    if (old != null && !"gerrit".equals(old.pluginName) && !pluginName.equals(old.pluginName)) {
      // We allow to replace:
      // 1. Gerrit core items, e.g. websession cache
      //    can be replaced by plugin implementation
      // 2. Reload of current plugin
      throw new ProvisionException(
          String.format(
              "%s already provided by %s, ignoring plugin %s",
              this.key.getTypeLiteral(), old.pluginName, pluginName));
    }
  }
  return new ReloadableHandle(key, item, old);
}
 
Example 18
Project: gerrit   File: EmailMerge.java   Source Code and License 6 votes vote down vote up
@Override
public Provider<ReviewDb> getReviewDbProvider() {
  return new Provider<ReviewDb>() {
    @Override
    public ReviewDb get() {
      if (db == null) {
        try {
          db = schemaFactory.open();
        } catch (OrmException e) {
          throw new ProvisionException("Cannot open ReviewDb", e);
        }
      }
      return db;
    }
  };
}
 
Example 19
Project: gerrit   File: ChangeQueryBuilder.java   Source Code and License 6 votes vote down vote up
@Operator
public Predicate<ChangeData> watchedby(String who)
    throws QueryParseException, OrmException, IOException, ConfigInvalidException {
  Set<Account.Id> m = parseAccount(who);
  List<IsWatchedByPredicate> p = Lists.newArrayListWithCapacity(m.size());

  Account.Id callerId;
  try {
    CurrentUser caller = args.self.get();
    callerId = caller.isIdentifiedUser() ? caller.getAccountId() : null;
  } catch (ProvisionException e) {
    callerId = null;
  }

  for (Account.Id id : m) {
    // Each child IsWatchedByPredicate includes a visibility filter for the
    // corresponding user, to ensure that predicate subtree only returns
    // changes visible to that user. The exception is if one of the users is
    // the caller of this method, in which case visibility is already being
    // checked at the top level.
    p.add(new IsWatchedByPredicate(args.asUser(id), !id.equals(callerId)));
  }
  return Predicate.or(p);
}
 
Example 20
Project: gerrit   File: MailSoyTofuProvider.java   Source Code and License 6 votes vote down vote up
private void addTemplate(SoyFileSet.Builder builder, String name) throws ProvisionException {
  // Load as a file in the mail templates directory if present.
  Path tmpl = site.mail_dir.resolve(name);
  if (Files.isRegularFile(tmpl)) {
    String content;
    // TODO(davido): Consider using JGit's FileSnapshot to cache based on
    // mtime.
    try (Reader r = Files.newBufferedReader(tmpl, StandardCharsets.UTF_8)) {
      content = CharStreams.toString(r);
    } catch (IOException err) {
      throw new ProvisionException(
          "Failed to read template file " + tmpl.toAbsolutePath().toString(), err);
    }
    builder.add(content, tmpl.toAbsolutePath().toString());
    return;
  }

  // Otherwise load the template as a resource.
  String resourcePath = "com/google/gerrit/server/mail/" + name;
  builder.add(Resources.getResource(resourcePath));
}
 
Example 21
Project: gerrit   File: SingleVersionModule.java   Source Code and License 6 votes vote down vote up
private <K, V, I extends Index<K, V>> void start(IndexDefinition<K, V, I> def) {
  if (disabled.contains(def.getName())) {
    return;
  }
  Schema<V> schema;
  Integer v = singleVersions.get(def.getName());
  if (v == null) {
    schema = def.getLatest();
  } else {
    schema = def.getSchemas().get(v);
    if (schema == null) {
      throw new ProvisionException(
          String.format("Unrecognized %s schema version: %s", def.getName(), v));
    }
  }
  I index = def.getIndexFactory().create(schema);
  def.getIndexCollection().setSearchIndex(index);
  def.getIndexCollection().addWriteIndex(index);
}
 
Example 22
Project: gerrit   File: IndexModule.java   Source Code and License 6 votes vote down vote up
@Provides
Collection<IndexDefinition<?, ?, ?>> getIndexDefinitions(
    AccountIndexDefinition accounts,
    ChangeIndexDefinition changes,
    GroupIndexDefinition groups,
    ProjectIndexDefinition projects) {
  Collection<IndexDefinition<?, ?, ?>> result =
      ImmutableList.<IndexDefinition<?, ?, ?>>of(accounts, groups, changes, projects);
  Set<String> expected =
      FluentIterable.from(ALL_SCHEMA_DEFS).transform(SchemaDefinitions::getName).toSet();
  Set<String> actual = FluentIterable.from(result).transform(IndexDefinition::getName).toSet();
  if (!expected.equals(actual)) {
    throw new ProvisionException(
        "need index definitions for all schemas: " + expected + " != " + actual);
  }
  return result;
}
 
Example 23
Project: gerrit   File: GerritServerConfigProvider.java   Source Code and License 6 votes vote down vote up
private static void checkNoteDbConfig(FileBasedConfig noteDbConfig) {
  List<String> bad = new ArrayList<>();
  for (String section : noteDbConfig.getSections()) {
    if (section.equals(NotesMigration.SECTION_NOTE_DB)) {
      continue;
    }
    for (String subsection : noteDbConfig.getSubsections(section)) {
      noteDbConfig
          .getNames(section, subsection, false)
          .forEach(n -> bad.add(section + "." + subsection + "." + n));
    }
    noteDbConfig.getNames(section, false).forEach(n -> bad.add(section + "." + n));
  }
  if (!bad.isEmpty()) {
    throw new ProvisionException(
        "Non-NoteDb config options not allowed in "
            + noteDbConfig.getFile()
            + ":\n"
            + bad.stream().collect(joining("\n")));
  }
}
 
Example 24
Project: gerrit   File: GerritServerConfigModule.java   Source Code and License 6 votes vote down vote up
private static String getSecureStoreFromGerritConfig(Path sitePath) {
  AbstractModule m =
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(Path.class).annotatedWith(SitePath.class).toInstance(sitePath);
          bind(SitePaths.class);
        }
      };
  Injector injector = Guice.createInjector(m);
  SitePaths site = injector.getInstance(SitePaths.class);
  FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config.toFile(), FS.DETECTED);
  if (!cfg.getFile().exists()) {
    return DefaultSecureStore.class.getName();
  }

  try {
    cfg.load();
    String className = cfg.getString("gerrit", null, "secureStoreClass");
    return nullToDefault(className);
  } catch (IOException | ConfigInvalidException e) {
    throw new ProvisionException(e.getMessage(), e);
  }
}
 
Example 25
Project: gerrit   File: ProjectConfigEntry.java   Source Code and License 6 votes vote down vote up
public ProjectConfigEntry(
    String displayName,
    String defaultValue,
    ProjectConfigEntryType type,
    List<String> permittedValues,
    boolean inheritable,
    String description) {
  this.displayName = displayName;
  this.defaultValue = defaultValue;
  this.type = type;
  this.permittedValues = permittedValues;
  this.inheritable = inheritable;
  this.description = description;
  if (type == ProjectConfigEntryType.ARRAY && inheritable) {
    throw new ProvisionException("ARRAY doesn't support inheritable values");
  }
}
 
Example 26
Project: gerrit   File: EmailReviewComments.java   Source Code and License 6 votes vote down vote up
@Override
public Provider<ReviewDb> getReviewDbProvider() {
  return new Provider<ReviewDb>() {
    @Override
    public ReviewDb get() {
      if (db == null) {
        try {
          db = schemaFactory.open();
        } catch (OrmException e) {
          throw new ProvisionException("Cannot open ReviewDb", e);
        }
      }
      return db;
    }
  };
}
 
Example 27
Project: gerrit   File: DataSourceProvider.java   Source Code and License 6 votes vote down vote up
private DataSource intercept(String interceptor, DataSource ds) {
  if (interceptor == null) {
    return ds;
  }
  try {
    Constructor<?> c = Class.forName(interceptor).getConstructor();
    DataSourceInterceptor datasourceInterceptor = (DataSourceInterceptor) c.newInstance();
    return datasourceInterceptor.intercept("reviewDb", ds);
  } catch (ClassNotFoundException
      | SecurityException
      | NoSuchMethodException
      | IllegalArgumentException
      | InstantiationException
      | IllegalAccessException
      | InvocationTargetException e) {
    throw new ProvisionException("Cannot intercept datasource", e);
  }
}
 
Example 28
Project: gerrit   File: IdentifiedUser.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a materialized copy of the user with all dependencies.
 *
 * <p>Invoke all providers and factories of dependent objects and store the references to a copy
 * of the current identified user.
 *
 * @return copy of the identified user
 */
public IdentifiedUser materializedCopy() {
  Provider<SocketAddress> remotePeer;
  try {
    remotePeer = Providers.of(remotePeerProvider.get());
  } catch (OutOfScopeException | ProvisionException e) {
    remotePeer =
        new Provider<SocketAddress>() {
          @Override
          public SocketAddress get() {
            throw e;
          }
        };
  }
  return new IdentifiedUser(
      authConfig,
      realm,
      anonymousCowardName,
      Providers.of(canonicalUrl.get()),
      accountCache,
      groupBackend,
      disableReverseDnsLookup,
      remotePeer,
      state,
      realUser);
}
 
Example 29
Project: gerrit   File: IdentifiedUser.java   Source Code and License 6 votes vote down vote up
private String guessHost() {
  String host = null;
  SocketAddress remotePeer = null;
  try {
    remotePeer = remotePeerProvider.get();
  } catch (OutOfScopeException | ProvisionException e) {
    // Leave null.
  }
  if (remotePeer instanceof InetSocketAddress) {
    InetSocketAddress sa = (InetSocketAddress) remotePeer;
    InetAddress in = sa.getAddress();
    host = in != null ? getHost(in) : sa.getHostName();
  }
  if (Strings.isNullOrEmpty(host)) {
    return "unknown";
  }
  return host;
}
 
Example 30
Project: gerrit   File: ServerPluginInfoModule.java   Source Code and License 6 votes vote down vote up
@Provides
@PluginData
Path getPluginData() {
  if (!ready) {
    synchronized (dataDir) {
      if (!ready) {
        try {
          Files.createDirectories(dataDir);
        } catch (IOException e) {
          throw new ProvisionException(
              String.format(
                  "Cannot create %s for plugin %s", dataDir.toAbsolutePath(), plugin.getName()),
              e);
        }
        ready = true;
      }
    }
  }
  return dataDir;
}
 
Example 31
Project: gerrit   File: InMemoryModule.java   Source Code and License 6 votes vote down vote up
private Module indexModule(String moduleClassName) {
  try {
    Class<?> clazz = Class.forName(moduleClassName);
    Method m = clazz.getMethod("singleVersionWithExplicitVersions", Map.class, int.class);
    return (Module) m.invoke(null, getSingleSchemaVersions(), 0);
  } catch (ClassNotFoundException
      | SecurityException
      | NoSuchMethodException
      | IllegalArgumentException
      | IllegalAccessException
      | InvocationTargetException e) {
    e.printStackTrace();
    ProvisionException pe = new ProvisionException(e.getMessage());
    pe.initCause(e);
    throw pe;
  }
}
 
Example 32
Project: eEcology-Classification   File: MessagePrintingExceptionHandler.java   Source Code and License 6 votes vote down vote up
private void addMessageIfInformative(LinkedList<String> messages, Throwable cause) {
    if (cause instanceof ProvisionException) { // This technical exception is hidden. Only its causes should be shown.
        return;
    }
    if (cause instanceof ConfigurationException) { // A missing setting in settings.properties can cause this exception.
        ConfigurationException configurationException = (ConfigurationException) cause;
        addClearifiedErrorMessages(messages, configurationException.getErrorMessages());
        return;
    }
    if (cause instanceof CreationException) { // A missing setting in settings.properties can cause this exception.
        CreationException creationException = (CreationException) cause;
        addClearifiedErrorMessages(messages, creationException.getErrorMessages());
        return;
    }
    messages.add(cause.getMessage());
}
 
Example 33
Project: sangria   File: ContextSensitiveBinderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testContextRequired() {
    thrown.expect(ProvisionException.class);

    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            ContextSensitiveBinder.create(binder())
                    .bind(String.class)
                    .annotatedWith(Names.named("self"))
                    .toContextSensitiveProvider(RequiredContextProvider.class);
        }
    });

    HasSelf hasSelf = injector.getInstance(HasSelf.class);
    assertThat(hasSelf.self, equalTo("HasSelf"));
    hasSelf.selfProvider.get();
}
 
Example 34
Project: guice   File: Java8LanguageFeatureBindingTest.java   Source Code and License 6 votes vote down vote up
public void testProviderMethod_containingLambda_throwingException() throws Exception {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {

            @Provides
            public Callable<String> provideCallable() {
              if (Boolean.parseBoolean("false")) { // avoid dead code warnings
                return () -> "foo";
              } else {
                throw new RuntimeException("foo");
              }
            }
          });

  try {
    injector.getInstance(new Key<Callable<String>>() {});
  } catch (ProvisionException expected) {
    assertTrue(expected.getCause() instanceof RuntimeException);
    assertEquals("foo", expected.getCause().getMessage());
  }
}
 
Example 35
Project: guice   File: BoundFieldModuleTest.java   Source Code and License 6 votes vote down vote up
public void testFieldBoundAsProvider_lazy() {
  LazyProviderClass asProvider = new LazyProviderClass();
  Provider<Integer> provider =
      Guice.createInjector(BoundFieldModule.of(asProvider)).getProvider(Integer.class);
  assertNull(provider.get());
  asProvider.foo = Providers.of(1);
  assertEquals(1, provider.get().intValue());
  asProvider.foo =
      new Provider<Integer>() {
        @Override
        public Integer get() {
          throw new RuntimeException("boom");
        }
      };
  try {
    provider.get();
    fail();
  } catch (ProvisionException e) {
    assertContains(e.getMessage(), "boom");
  }
}
 
Example 36
Project: guice   File: ScopeRequestIntegrationTest.java   Source Code and License 6 votes vote down vote up
public final void testNullReplacement() throws Exception {
  Injector injector =
      Guice.createInjector(
          new ServletModule() {
            @Override
            protected void configureServlets() {
              bindConstant().annotatedWith(Names.named(SomeObject.INVALID)).to(SHOULDNEVERBESEEN);
              bind(SomeObject.class).in(RequestScoped.class);
            }
          });

  Callable<SomeObject> callable = injector.getInstance(Caller.class);
  try {
    assertNotNull(callable.call());
    fail();
  } catch (ProvisionException pe) {
    assertTrue(pe.getCause() instanceof OutOfScopeException);
  }

  // Validate that an actual null entry in the map results in a null injected object.
  Map<Key<?>, Object> map = Maps.newHashMap();
  map.put(Key.get(SomeObject.class), null);
  callable = ServletScopes.scopeRequest(injector.getInstance(Caller.class), map);
  assertNull(callable.call());
}
 
Example 37
Project: guice   File: ProviderMethodsTest.java   Source Code and License 6 votes vote down vote up
public void testScopedProviderMethodThrowsException() {
  Injector injector =
      Guice.createInjector(
          new AbstractModule() {

            @Provides
            @Singleton
            int provideInt() {
              throw new RuntimeException("boom");
            }
          });
  Provider<Integer> intProvider = injector.getProvider(Integer.class);
  try {
    intProvider.get();
    fail();
  } catch (ProvisionException pe) {
    // by default assertContains asserts that the last item doesn't repeat... which is the main
    // thing we are testing for
    assertContains(pe.getMessage(), "java.lang.RuntimeException: boom", "provideInt");
  }
}
 
Example 38
Project: guice   File: ProviderMethodsTest.java   Source Code and License 6 votes vote down vote up
private void validateNullableFails(Injector injector, Module module) {
  try {
    injector.getInstance(Integer.class);
    fail();
  } catch (ProvisionException expected) {
    assertContains(
        expected.getMessage(),
        "1) null returned by binding at " + module.getClass().getName() + ".configure(",
        "but the 1st parameter of " + module.getClass().getName() + ".fail(",
        "is not @Nullable",
        "while locating java.lang.String",
        "for the 1st parameter of " + module.getClass().getName() + ".fail(",
        "while locating java.lang.Integer");

    assertEquals(1, expected.getErrorMessages().size());
  }
}
 
Example 39
Project: guice   File: MapBinderTest.java   Source Code and License 6 votes vote down vote up
public void testMapBinderMapForbidsNullValues() {
  Module m =
      new AbstractModule() {
        @Override
        protected void configure() {
          MapBinder.newMapBinder(binder(), String.class, String.class)
              .addBinding("null")
              .toProvider(Providers.<String>of(null));
        }
      };
  Injector injector = Guice.createInjector(m);

  try {
    injector.getInstance(Key.get(mapOfString));
    fail();
  } catch (ProvisionException expected) {
    assertContains(
        expected.getMessage(),
        "1) Map injection failed due to null value for key \"null\", bound at: "
            + m.getClass().getName()
            + ".configure(");
  }
}
 
Example 40
Project: guice   File: MultibinderTest.java   Source Code and License 6 votes vote down vote up
public void testMultibinderSetForbidsNullElements() {
  Module m =
      new AbstractModule() {
        @Override
        protected void configure() {
          Multibinder.newSetBinder(binder(), String.class)
              .addBinding()
              .toProvider(Providers.<String>of(null));
        }
      };
  Injector injector = Guice.createInjector(m);

  try {
    injector.getInstance(Key.get(setOfString));
    fail();
  } catch (ProvisionException expected) {
    assertContains(
        expected.getMessage(),
        "1) Set injection failed due to null element bound at: "
            + m.getClass().getName()
            + ".configure(");
  }
}