@Inject public GuiceQueryPreProcessor(Injector injector) { m_preProcessors = new ArrayList<>(); Map<Key<?>, Binding<?>> bindings = injector.getAllBindings(); for (Key<?> key : bindings.keySet()) { Class<?> bindingClass = key.getTypeLiteral().getRawType(); if (QueryPreProcessor.class.isAssignableFrom(bindingClass)) { m_preProcessors.add((QueryPreProcessor)injector.getInstance(bindingClass)); } } }
MvcWebSocket(final WebSocket ws, final Class handler) { Injector injector = ws.require(Injector.class) .createChildInjector(binder -> binder.bind(WebSocket.class).toInstance(ws)); this.handler = injector.getInstance(handler); this.messageType = TypeLiteral.get(messageType(handler)); }
public T get() final ParameterizedType mapType = Types.mapOf( String.class, Types.newParameterizedType(Provider.class, key.getTypeLiteral().getType()) ); if (key.getAnnotation() != null) { implsMap = (Map<String, Provider<T>>) injector.getInstance(Key.get(mapType, key.getAnnotation())); } else if (key.getAnnotationType() != null) { implsMap = (Map<String, Provider<T>>) injector.getInstance(Key.get(mapType, key.getAnnotationType())); } else { implsMap = (Map<String, Provider<T>>) injector.getInstance(Key.get(mapType));
@SuppressWarnings("unchecked") static <T> TypeLiteral<Optional<T>> optionalOf(TypeLiteral<T> type) { return (TypeLiteral<Optional<T>>) TypeLiteral.get(Types.newParameterizedType(Optional.class, type.getType())); }
@SuppressWarnings("unchecked") // a provider entry <K, V> is safely a Map.Entry<K, Provider<V>> static <K, V> TypeLiteral<Map.Entry<K, Provider<V>>> entryOfJavaxProviderOf( TypeLiteral<K> keyType, TypeLiteral<V> valueType) { return (TypeLiteral<Map.Entry<K, Provider<V>>>) TypeLiteral.get( newParameterizedTypeWithOwner( Map.class, Map.Entry.class, keyType.getType(), Types.javaxProviderOf(valueType.getType()))); }
@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()); }
@SuppressWarnings("unchecked") public static <T> void bindInstance( Binder binder, Key<T> bindKey, T instance ) { binder.bind(bindKey).toInstance(instance); final ParameterizedType supType = Types.newParameterizedType(Supplier.class, bindKey.getTypeLiteral().getType()); final Key supplierKey; if (bindKey.getAnnotationType() != null) { supplierKey = Key.get(supType, bindKey.getAnnotationType()); } else if (bindKey.getAnnotation() != null) { supplierKey = Key.get(supType, bindKey.getAnnotation()); } else { supplierKey = Key.get(supType); } binder.bind(supplierKey).toInstance(Suppliers.ofInstance(instance)); }
@SuppressWarnings({"unchecked", "rawtypes" }) @Override public void configure(final Env env, final Config conf, final Binder binder) { Config gconf = conf.hasPath(name) ? conf : ConfigFactory.empty(); gconf = gconf.withFallback( ConfigFactory.empty().withValue("caffeine.cache", ConfigValueFactory.fromAnyRef(""))); gconf.getObject(name).unwrapped().forEach((name, spec) -> { Caffeine<K, V> cb = (Caffeine<K, V>) Caffeine.from(toSpec(spec)); Object cache = callback.apply(name, cb); List<TypeLiteral> types = cacheType(name, cache, getClass().getGenericSuperclass()); types.forEach(type -> { binder.bind(Key.get(type, Names.named(name))) .toInstance(cache); if (name.equals("cache")) { // unnamed cache for default cache binder.bind(type).toInstance(cache); // raw type for default cache binder.bind(type.getRawType()).toInstance(cache); } if (name.equals("session")) { binder.bind(Key.get(type, Names.named(name))).toInstance(cache); binder.bind(Key.get(type.getRawType(), Names.named(name))).toInstance(cache); } }); }); }
@Override protected final void configureShiro() { bindBeanType(TypeLiteral.get(ServletContext.class), Key.get(ServletContext.class, Names.named(NAME))); bind(Key.get(ServletContext.class, Names.named(NAME))).toInstance(this.servletContext); bindWebSecurityManager(bind(WebSecurityManager.class)); bindWebEnvironment(bind(WebEnvironment.class)); bind(GuiceShiroFilter.class).asEagerSingleton(); expose(GuiceShiroFilter.class); this.configureShiroWeb(); bind(FilterChainResolver.class).toProvider(new FilterChainResolverProvider(setupFilterChainConfigs())); }
@Override public void bind(Binder b) { ParameterizedType pt = Types.newParameterizedType(genericClass, genericClassParams); Key k = Key.get(TypeLiteral.get(pt)); b.bind(k).to(to); } });
@Override public void bind(Binder b) { ParameterizedType pt = Types.newParameterizedType(genericClass, genericClassParams); Key k = Key.get(TypeLiteral.get(pt)); b.bind(k).toInstance(to); } });
public static <F> Provider<F> newFactory( TypeLiteral<F> factoryType, TypeLiteral<?> implementationType) { Map<Method, AssistedConstructor<?>> factoryMethodToConstructor = createMethodMapping(factoryType, implementationType); if (!factoryMethodToConstructor.isEmpty()) { return new FactoryProvider<F>(factoryType, implementationType, factoryMethodToConstructor); } else { BindingCollector collector = new BindingCollector(); // Preserving backwards-compatibility: Map all return types in a factory // interface to the passed implementation type. Errors errors = new Errors(); Key<?> implementationKey = Key.get(implementationType); try { for (Method method : factoryType.getRawType().getMethods()) { Key<?> returnType = getKey(factoryType.getReturnType(method), method, method.getAnnotations(), errors); if (!implementationKey.equals(returnType)) { collector.addBinding(returnType, implementationType); } } } catch (ErrorsException e) { throw new ConfigurationException(e.getErrors().getMessages()); } return new FactoryProvider2<F>(Key.get(factoryType), collector); } }
@Override public void configure(Binder binder) { for (Class clazz : mockableInjections) { binder.bind(clazz).toInstance(EasyMock.createNiceMock(clazz)); } for (Object obj : injectedObjs) { binder.bind((Class) obj.getClass()).toInstance(obj); } for (Key<?> key : mockableKeys) { binder.bind((Key<Object>) key).toInstance(EasyMock.createNiceMock(key.getTypeLiteral().getRawType())); } binder.bind(AuthConfig.class).toInstance(new AuthConfig()); } }
/** Creates a binding for a type annotated with @ImplementedBy. */ private <T> BindingImpl<T> createImplementedByBinding( Key<T> key, Scoping scoping, ImplementedBy implementedBy, Errors errors) throws ErrorsException { Class<?> rawType = key.getTypeLiteral().getRawType(); Class<?> implementationType = implementedBy.value(); // Make sure it's not the same type. TODO: Can we check for deeper cycles? if (implementationType == rawType) { throw errors.recursiveImplementationType().toException(); } // Make sure implementationType extends type. if (!rawType.isAssignableFrom(implementationType)) { throw errors.notASubtype(implementationType, rawType).toException(); } @SuppressWarnings("unchecked") // After the preceding check, this cast is safe. Class<? extends T> subclass = (Class<? extends T>) implementationType; // Look up the target binding. final Key<? extends T> targetKey = Key.get(subclass); Object source = rawType; FactoryProxy<T> factory = new FactoryProxy<>(this, key, targetKey, source); factory.notify(errors); // causes the factory to initialize itself internally return new LinkedBindingImpl<T>( this, key, source, Scoping.<T>scope(key, this, factory, source, scoping), scoping, targetKey); }
/** Creates a binding for a type annotated with @ProvidedBy. */ <T> BindingImpl<T> createProvidedByBinding( Key<T> key, Scoping scoping, ProvidedBy providedBy, Errors errors) throws ErrorsException { Class<?> rawType = key.getTypeLiteral().getRawType(); Class<? extends javax.inject.Provider<?>> providerType = providedBy.value(); // Make sure it's not the same type. TODO: Can we check for deeper loops? if (providerType == rawType) { throw errors.recursiveProviderType().toException(); } // Assume the provider provides an appropriate type. We double check at runtime. @SuppressWarnings("unchecked") Key<? extends Provider<T>> providerKey = (Key<? extends Provider<T>>) Key.get(providerType); ProvidedByInternalFactory<T> internalFactory = new ProvidedByInternalFactory<T>(rawType, providerType, providerKey); Object source = rawType; BindingImpl<T> binding = LinkedProviderBindingImpl.createWithInitializer( this, key, source, Scoping.<T>scope(key, this, internalFactory, source, scoping), scoping, providerKey, internalFactory); internalFactory.setProvisionListenerCallback(provisionListenerStore.get(binding)); return binding; }
private <U> void _find(Class<U> type, List<ExtensionComponent<U>> result, Injector container) { for (Entry<Key<?>, Binding<?>> e : container.getBindings().entrySet()) { if (type.isAssignableFrom(e.getKey().getTypeLiteral().getRawType())) { Annotation a = annotations.get(e.getKey()); Object o = e.getValue().getProvider().get(); if (o!=null) { GuiceExtensionAnnotation gea = a!=null ? extensionAnnotations.get(a.annotationType()) : null; result.add(new ExtensionComponent<>(type.cast(o), gea != null ? gea.getOrdinal(a) : 0)); } } } }
@SuppressWarnings("unchecked") private <T> ScopedBindingBuilder bindNewMockProvider(Key<T> key) { return bind(key).toProvider( new MockProvider<T>((Class<T>) key.getTypeLiteral().getRawType())); }
StringBuilder sb = new StringBuilder(); sb.append(format("No implementation for %s was bound.", key)); TypeLiteral<T> type = key.getTypeLiteral(); List<Binding<T>> sameTypes = injector.findBindingsByType(type); if (!sameTypes.isEmpty()) { sb.append(format("%n Did you mean?")); int howMany = Math.min(sameTypes.size(), MAX_MATCHING_TYPES_REPORTED); for (int i = 0; i < howMany; ++i) { sb.append(format("%n * %s", sameTypes.get(i).getKey())); String want = type.toString(); Map<Key<?>, Binding<?>> bindingMap = injector.getAllBindings(); for (Key<?> bindingKey : bindingMap.keySet()) { String have = bindingKey.getTypeLiteral().toString(); if (have.contains(want) || want.contains(have)) { Formatter fmt = new Formatter(); Messages.formatSource(fmt, bindingMap.get(bindingKey).getSource()); String match = String.format("%s bound%s", convert(bindingKey), fmt.toString()); possibleMatches.add(match); && key.getAnnotation() == null && COMMON_AMBIGUOUS_TYPES.contains(key.getTypeLiteral().getRawType())) { sb.append(format("%nThe key seems very generic, did you forget an annotation?"));
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; TypeLiteral<T> guiceProviderType = (TypeLiteral<T>) TypeLiteral.get(Types.providerOf(parameterizedType.getActualTypeArguments()[0])); return guiceProviderType; TypeLiteral<T> recreated = (TypeLiteral<T>) TypeLiteral.get(typeLiteral.getType()); return recreated;