@Test public void testNotExposed() { final Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { DuplexBinder.create(this.binder()).install(new DuplexModule() { @Override protected void configure() { this.bind(Thing.class).annotatedWith(Names.named("r0")).toInstance(new Thing("r0")); } }); } }); try { injector.getInstance(ShouldNotWork.class); } catch(final ConfigurationException expected) { final String message = expected.getMessage(); if(message.contains("It was already configured on one or more child injectors or private modules") && message.contains("If it was in a PrivateModule, did you forget to expose the binding?")) { return; } } fail("should not be exposed"); }
private void analyzeImplementation(final TypeLiteral<?> type, boolean ignoreConstructor) { if( !scannedTypes.contains(type) ) { try { if( (type.getRawType().getModifiers() & (Modifier.INTERFACE | Modifier.ABSTRACT)) == 0 ) { analyzeInjectionPoints(InjectionPoint.forInstanceMethodsAndFields(type)); if( !ignoreConstructor ) { analyzeDependencies(InjectionPoint.forConstructorOf(type).getDependencies()); } } } catch( ConfigurationException ce ) { errors.merge(ce.getErrorMessages()); } scannedTypes.add(type); } }
@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 } } }
/** * This method produces value for the field. It constructs the context for the creation out of * paren't context and the field's own frame info. */ @Override public Optional<Object> provideValue(Object pageObject, Field field, PageObjectContext context) { By selector = PageObjectProviderHelper.getSelectorFromPageObject(field); ElementLocatorFactory elementLocatorFactory = new NestedSelectorScopedLocatorFactory(webDriver, selector, context.getElementLocatorFactory(), AnnotationsHelper.isGlobal(field)); final FramePath framePath = frameMap.get(pageObject); contextStack.push(new PageObjectContext(elementLocatorFactory, framePath)); Object scopedPageObject = null; try { scopedPageObject = injector.getInstance(field.getType()); } catch (Exception e) { if (e instanceof ConfigurationException) { ConfigurationException ce = (ConfigurationException) e; throw new BobcatRuntimeException( "Configuration exception: " + ce.getErrorMessages().toString(), e); } throw new BobcatRuntimeException(e.getMessage(), e); } finally { contextStack.pop(); } return Optional.ofNullable(scopedPageObject); }
/** * This method produces value for the field. It constructs the context for the creation out of * parent's context and the field's own frame info. */ @Override public Optional<Object> provideValue(Object pageObject, Field field, PageObjectContext context) { final ElementLocatorFactory elementLocatorFactory = new ScopedElementLocatorFactory(webDriver, context.getElementLocatorFactory(), field); final FramePath framePath = frameMap.get(pageObject); contextStack.push(new PageObjectContext(elementLocatorFactory, framePath)); Object scopedPageObject = null; try { scopedPageObject = injector.getInstance(field.getType()); } catch (Exception e) { if (e instanceof ConfigurationException) { ConfigurationException ce = (ConfigurationException) e; throw new BobcatRuntimeException( "Configuration exception: " + ce.getErrorMessages().toString(), e); } throw new BobcatRuntimeException(e.getMessage(), e); } finally { contextStack.pop(); } return Optional.ofNullable(scopedPageObject); }
/** * @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; }
@Override public Object resolve(Injectee injectee, ServiceHandle<?> serviceHandle) { if (injectee.getRequiredType() instanceof Class) { TypeLiteral<?> typeLiteral = TypeLiteral.get(injectee.getRequiredType()); Errors errors = new Errors(injectee.getParent()); Key<?> key; try { key = Annotations.getKey(typeLiteral, (Member) injectee.getParent(), injectee.getParent().getDeclaredAnnotations(), errors); } catch (ErrorsException e) { errors.merge(e.getErrors()); throw new ConfigurationException(errors.getMessages()); } return injector.getInstance(key); } throw new IllegalStateException("Can't process injection point: " + injectee.getRequiredType()); }
/** * 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; }
private Optional<String> getCurrentTestLogFileName() { Optional<TestContext> testContext = testContextIfSet(); try { String testName = "SUITE"; if (testContext.isPresent()) { Optional<TestMetadata> testMetadata = testContext.get().getOptionalDependency(TestMetadata.class); if (testMetadata.isPresent()) { testName = testMetadata.get().testName; } } return Optional.of(logsDirectory + "/" + testName); } catch (ConfigurationException e) { System.err.append("Could not load TestMetadata from guice context"); return Optional.empty(); } }
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); } }
private void createBindingsForFactories(GinjectorBindings bindings) { for (final FactoryModule<?> factoryModule : bindings.getFactoryModules()) { FactoryBinding binding; try { binding = bindingFactory.getFactoryBinding( factoryModule.getBindings(), factoryModule.getFactoryType(), Context.forText(factoryModule.getSource())); } catch (ConfigurationException e) { errorManager.logError("Factory %s could not be created", e, factoryModule.getFactoryType()); continue; } bindings.addBinding(factoryModule.getFactoryType(), binding); } }
private static TestWrapper buildTestWrapperInstance(Injector injector) { TestWrapper result = NoOpTestScopeListener.NO_OP_INSTANCE; try { boolean hasTestScopeListenerBinding = hasTestScopeListenerBinding(injector); boolean hasDeprecatedTestScopeListenerBinding = hasDeprecatedTestScopeListenerBinding(injector); if (hasTestScopeListenerBinding && hasDeprecatedTestScopeListenerBinding) { throw new RuntimeException( "Your GuiceBerry Env has bindings for both the new TestScopeListener and the deprecated one. Please fix."); } else if (hasTestScopeListenerBinding) { result = injector.getInstance(TestWrapper.class); } else if (hasDeprecatedTestScopeListenerBinding) { result = adapt( injector.getInstance(com.google.inject.testing.guiceberry.TestScopeListener.class), injector.getInstance(TearDownAccepter.class)); } } catch (ConfigurationException e) { String msg = String.format("Error while creating a TestWrapper: '%s'.", e.getMessage()); throw new RuntimeException(msg, e); } return result; }
/** * This test makes sure that if the test has a missing binding, GuiceBerry * will fail before it runs the {@link GuiceBerryEnvMain#run()} method. */ @Test public void testFailsInjectionBeforeRunningGuiceBerryEnvMain_MissingTestBinding() { GuiceBerryEnvSelector guiceBerryEnvSelector = DefaultEnvSelector.of(MyGuiceBerryEnvWithGuiceBerryEnvMainThatThrows.class); TestDescription testDescription = new TestDescription(new ClassWithUnsatisfiedDependency(), "bogus test case"); GuiceBerryUniverse.TestCaseScaffolding testCaseScaffolding = new GuiceBerryUniverse.TestCaseScaffolding(testDescription, guiceBerryEnvSelector, universe); try { testCaseScaffolding.runBeforeTest(); Assert.fail("The test has an unsatisfied injection, and the GuiceBerryEnvMain " + "throws an Exception. Either of these reasons should have prevented the " + "test from having gotten here."); } catch (MyGuiceBerryEnvWithGuiceBerryEnvMainThatThrows.GuiceBerryEnvMainWasExecutedException toThrow) { throw toThrow; } catch (RuntimeException maybeExpected) { Assert.assertEquals(ConfigurationException.class, maybeExpected.getCause().getClass()); } testCaseScaffolding.runAfterTest(); }
public void testGbeThatHasMissingBindingsThrowsException() { try { TestWithGbeThatHasMissingBindings test = TestWithGbeThatHasMissingBindings.createInstance(); instance().doSetUp(test); fail(); } catch (RuntimeException expectedActualException) { //TODO: we should assert expected's cause is ConfigurationException, but //that exception is private Throwable actualCause = expectedActualException.getCause(); assertEquals(ConfigurationException.class, actualCause.getClass()); assertEquals(String.format( "Binding error in the GuiceBerry Env '%s': '%s'.", GuiceBerryEnvWithoutBindingsForFooOrBar.GUICE_BERRY_ENV_WITHOUT_BINDINGS_FOR_FOO_OR_BAR, actualCause.getMessage()), expectedActualException.getMessage()); String configurationExceptionMeat = String.format( "No implementation for %s was bound.", BarService.class.getName()); assertTrue(actualCause.getMessage().contains(configurationExceptionMeat)); } }
private <E> List<E> provide(TypeLiteral<Set<E>> type) { List<E> collection; try { Set<E> retrieved = injector.getInstance(Key.get(type)); collection = retrieved.stream().filter(Objects::nonNull).collect(toList()); if (collection.isEmpty()) { throw new ConfigurationException(new ArrayList<>()); } } catch (ConfigurationException ce) { log.info(() -> "There is no registered instance of the type: "); collection = new ArrayList<>(); } return collection; }
public synchronized void shutdown() { if (plugins != null) { Arrays.stream(plugins).forEach(plugin -> plugin.destroy()); } onShutdown.forEach(Runnable::run); if (injector != null) { // shutdown the database connection pool try { DatabaseConnection connection = injector.getInstance(DatabaseConnection.class); if (connection != null) connection.close(); } catch (ConfigurationException ignore) { } catch (Exception e) { e.printStackTrace(); } // signal the framework that we are closing down FrameworkEngine engine = injector.getInstance(FrameworkEngine.class); engine.onFrameworkShutdown(); injector = null; engine = null; } }
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()); }
@Override public <C extends IRequestablePage> C newPage(final Class<C> pageClass) { LOG.debug("Creating new {} page without parameters", pageClass.getName()); if (!Application.get().getSecuritySettings().getAuthorizationStrategy().isInstantiationAuthorized(pageClass)) { throw new RestartResponseAtInterceptPageException(wicketSettings.getLoginPageClass()); } try { final C pageInstance = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(PageParameters.class).toInstance(new PageParameters()); } }).getInstance(pageClass); return pageInstance; } catch(final ConfigurationException e) { LOG.debug("Could not create page {} through Guice, trying manually: {}", pageClass, e.getMessage()); return createOrThrow(pageClass, null); } }
@Override public <C extends IRequestablePage> C newPage(final Class<C> pageClass, final PageParameters parameters) { LOG.debug("Creating new {} page with parameters: {}", pageClass.getName(), parameters); try { final C pageInstance = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(PageParameters.class).toInstance(parameters); } }).getInstance(pageClass); return pageInstance; } catch(final ConfigurationException e) { LOG.debug("Could not create page {} through Guice, trying manually: {}", pageClass, e.getMessage()); return createOrThrow(pageClass, parameters); } }
public void testBindingSuperTypeAccessSubType() { final Integer testValue = 1024; Object instance = new Object() { @Bind(to = Number.class) private Integer anInt = testValue; }; BoundFieldModule module = BoundFieldModule.of(instance); Injector injector = Guice.createInjector(module); try { injector.getInstance(Integer.class); fail(); } catch (ConfigurationException e) { assertContains(e.getMessage(), "Could not find a suitable constructor in java.lang.Integer"); } }
public void testProviderSubclassesDoNotBindParameterizedType() { final Integer testValue = 1024; Object instance = new Object() { @Bind private IntegerProvider anIntProvider = new IntegerProvider(testValue); }; BoundFieldModule module = BoundFieldModule.of(instance); Injector injector = Guice.createInjector(module); try { injector.getInstance(Integer.class); fail(); } catch (ConfigurationException e) { assertContains(e.getMessage(), "Could not find a suitable constructor in java.lang.Integer."); } }
/** * Returns all static method and field injection points on {@code type}. * * @return a possibly empty set of injection points. The set has a specified iteration order. All * fields are returned and then all methods. Within the fields, supertype fields are returned * before subtype fields. Similarly, supertype methods are returned before subtype methods. * @throws ConfigurationException if there is a malformed injection point on {@code type}, such as * a field with multiple binding annotations. The exception's {@link * ConfigurationException#getPartialValue() partial value} is a {@code Set<InjectionPoint>} of * the valid injection points. */ public static Set<InjectionPoint> forStaticMethodsAndFields(TypeLiteral<?> type) { Errors errors = new Errors(); Set<InjectionPoint> result; if (type.getRawType().isInterface()) { errors.staticInjectionOnInterface(type.getRawType()); result = null; } else { result = getInjectionPoints(type, true, errors); } if (errors.hasErrors()) { throw new ConfigurationException(errors.getMessages()).withPartialValue(result); } return result; }
/** Returns a set of dependencies that can be iterated over to clean up stray JIT bindings. */ Set<Dependency<?>> getInternalDependencies() { ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder(); if (factory.constructorInjector == null) { builder.add(constructorInjectionPoint); // If the below throws, it's OK -- we just ignore those dependencies, because no one // could have used them anyway. try { builder.addAll( InjectionPoint.forInstanceMethodsAndFields( constructorInjectionPoint.getDeclaringType())); } catch (ConfigurationException ignored) { } } else { builder.add(getConstructor()).addAll(getInjectableMembers()); } return Dependency.forInjectionPoints(builder.build()); }
@Override public void toInstance(T instance) { checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; if (instance != null) { try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(instance.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } } else { binder.addError(BINDING_TO_NULL); injectionPoints = ImmutableSet.of(); } BindingImpl<T> base = getBinding(); setBinding( new InstanceBindingImpl<T>( base.getSource(), base.getKey(), Scoping.EAGER_SINGLETON, injectionPoints, instance)); }
@Override public BindingBuilder<T> toProvider(javax.inject.Provider<? extends T> provider) { checkNotNull(provider, "provider"); checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(provider.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } BindingImpl<T> base = getBinding(); setBinding( new ProviderInstanceBindingImpl<T>( base.getSource(), base.getKey(), base.getScoping(), injectionPoints, provider)); return this; }
void validate() { Errors errorsForMember = errors.withSource(source); Set<InjectionPoint> injectionPoints; try { injectionPoints = request.getInjectionPoints(); } catch (ConfigurationException e) { errorsForMember.merge(e.getErrorMessages()); injectionPoints = e.getPartialValue(); } if (injectionPoints != null) { memberInjectors = injector.membersInjectorStore.getInjectors(injectionPoints, errorsForMember); } else { memberInjectors = ImmutableList.of(); } errors.merge(errorsForMember); }
/** * 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); } }
/** * At injector-creation time, we initialize the invocation handler. At this time we make sure * all factory methods will be able to build the target types. */ @Inject @Toolable void initialize(Injector injector) { if (this.injector != null) { throw new ConfigurationException(ImmutableList.of(new Message(FactoryProvider2.class, "Factories.create() factories may only be used in one Injector!"))); } this.injector = injector; for (Map.Entry<Method, AssistData> entry : assistDataByMethod.entrySet()) { Method method = entry.getKey(); AssistData data = entry.getValue(); Object[] args; if(!data.optimized) { args = new Object[method.getParameterTypes().length]; Arrays.fill(args, "dummy object for validating Factories"); } else { args = null; // won't be used -- instead will bind to data.providers. } getBindingFromNewInjector(method, args, data); // throws if the binding isn't properly configured } }
/** * Returns all static method and field injection points on {@code type}. * * @return a possibly empty set of injection points. The set has a specified iteration order. All * fields are returned and then all methods. Within the fields, supertype fields are returned * before subtype fields. Similarly, supertype methods are returned before subtype methods. * @throws ConfigurationException if there is a malformed injection point on {@code type}, such as * a field with multiple binding annotations. The exception's {@link * ConfigurationException#getPartialValue() partial value} is a {@code Set<InjectionPoint>} * of the valid injection points. */ public static Set<InjectionPoint> forStaticMethodsAndFields(TypeLiteral<?> type) { Errors errors = new Errors(); Set<InjectionPoint> result; if (type.getRawType().isInterface()) { errors.staticInjectionOnInterface(type.getRawType()); result = null; } else { result = getInjectionPoints(type, true, errors); } if (errors.hasErrors()) { throw new ConfigurationException(errors.getMessages()).withPartialValue(result); } return result; }
/** Returns a set of dependencies that can be iterated over to clean up stray JIT bindings. */ Set<Dependency<?>> getInternalDependencies() { ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder(); if(factory.constructorInjector == null) { builder.add(constructorInjectionPoint); // If the below throws, it's OK -- we just ignore those dependencies, because no one // could have used them anyway. try { builder.addAll(InjectionPoint.forInstanceMethodsAndFields(constructorInjectionPoint.getDeclaringType())); } catch(ConfigurationException ignored) {} } else { builder.add(getConstructor()) .addAll(getInjectableMembers()); } return Dependency.forInjectionPoints(builder.build()); }
public void toInstance(T instance) { checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; if (instance != null) { try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(instance.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } } else { binder.addError(BINDING_TO_NULL); injectionPoints = ImmutableSet.of(); } BindingImpl<T> base = getBinding(); setBinding(new InstanceBindingImpl<T>( base.getSource(), base.getKey(), Scoping.EAGER_SINGLETON, injectionPoints, instance)); }
public BindingBuilder<T> toProvider(javax.inject.Provider<? extends T> provider) { checkNotNull(provider, "provider"); checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(provider.getClass()); } catch (ConfigurationException e) { copyErrorsToBinder(e); injectionPoints = e.getPartialValue(); } BindingImpl<T> base = getBinding(); setBinding(new ProviderInstanceBindingImpl<T>( base.getSource(), base.getKey(), base.getScoping(), injectionPoints, provider)); return this; }
/** * Returns an type that's appropriate for use in a key. * * <p>If the raw type of {@code typeLiteral} is a {@code javax.inject.Provider}, this returns a * {@code com.google.inject.Provider} with the same type parameters. * * <p>If the type is a primitive, the corresponding wrapper type will be returned. * * @throws ConfigurationException if {@code type} contains a type variable */ public static <T> TypeLiteral<T> canonicalizeForKey(TypeLiteral<T> typeLiteral) { Type type = typeLiteral.getType(); if (!isFullySpecified(type)) { Errors errors = new Errors().keyNotFullySpecified(typeLiteral); throw new ConfigurationException(errors.getMessages()); } if (typeLiteral.getRawType() == javax.inject.Provider.class) { ParameterizedType parameterizedType = (ParameterizedType) type; // the following casts are generally unsafe, but com.google.inject.Provider extends // javax.inject.Provider and is covariant @SuppressWarnings("unchecked") TypeLiteral<T> guiceProviderType = (TypeLiteral<T>) TypeLiteral.get( Types.providerOf(parameterizedType.getActualTypeArguments()[0])); return guiceProviderType; } @SuppressWarnings("unchecked") TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER.get(typeLiteral); return wrappedPrimitives != null ? wrappedPrimitives : typeLiteral; }
void validate() { Errors errorsForMember = errors.withSource(source); Set<InjectionPoint> injectionPoints; try { injectionPoints = request.getInjectionPoints(); } catch (ConfigurationException e) { errorsForMember.merge(e.getErrorMessages()); injectionPoints = e.getPartialValue(); } if (injectionPoints != null) { memberInjectors = injector.membersInjectorStore.getInjectors( injectionPoints, errorsForMember); } else { memberInjectors = ImmutableList.of(); } errors.merge(errorsForMember); }
@SuppressWarnings("rawtypes") @Test public void oneCache() throws Exception { Config conf = ConfigFactory.empty() .withValue("caffeine.cache", ConfigValueFactory.fromAnyRef("")); new MockUnit(Env.class) .run(unit -> { Injector injector = Guice.createInjector(binder -> { new CaffeineCache() { }.configure(unit.get(Env.class), conf, binder); }); injector.getInstance(RequireCache.class); try { injector.getInstance(CaffeineSessionStore.class); fail("No session found"); } catch (ConfigurationException ex) { // OK } }); }
@SuppressWarnings("rawtypes") @Test public void cacheWithObjectSpec() throws Exception { Config conf = ConfigFactory.empty() .withValue("caffeine.cache.maximumSize", ConfigValueFactory.fromAnyRef(10)); new MockUnit(Env.class) .run(unit -> { Injector injector = Guice.createInjector(binder -> { new CaffeineCache() { }.configure(unit.get(Env.class), conf, binder); }); injector.getInstance(RequireCache.class); try { injector.getInstance(CaffeineSessionStore.class); fail("No session found"); } catch (ConfigurationException ex) { // OK } }); }
@SuppressWarnings("rawtypes") @Test public void oneCache() throws Exception { Config conf = ConfigFactory.empty() .withValue("guava.cache", ConfigValueFactory.fromAnyRef("")); new MockUnit(Env.class) .run(unit -> { Injector injector = Guice.createInjector(binder -> { new GuavaCache() { }.configure(unit.get(Env.class), conf, binder); }); injector.getInstance(RequireCache.class); try { injector.getInstance(GuavaSessionStore.class); fail("No session found"); } catch (ConfigurationException ex) { // OK } }); }