@Override public Void visit(ExposedBinding<? extends T> binding) { final PrivateBinder privateBinder = this.binder.newPrivateBinder(); final Scoper scoper = new Scoper(privateBinder, scoping); for(Element element : binding.getPrivateElements().getElements()) { if(element instanceof Binding) { ((Binding) element).acceptTargetVisitor(scoper); } else { element.applyTo(privateBinder); } } for(Key key : binding.getPrivateElements().getExposedKeys()) { privateBinder.expose(key); } return null; }
@SuppressWarnings("unchecked") @Override public <T> T getBean(String beanId) { Injector injector = ensureInjector(); Key<Object> nameKey = Key.get(Object.class, Names.named(beanId)); Binding<Object> binding = injector.getExistingBinding(nameKey); if( binding != null ) { return (T) binding.getProvider().get(); } ClassLoader classLoader = privatePluginService.getClassLoader(pluginId); try { Class<?> clazz = classLoader.loadClass(beanId); return (T) injector.getInstance(clazz); } catch( ClassNotFoundException e ) { throw new RuntimeException(e); } }
@Inject @SuppressWarnings("unchecked") public GuiceQueryPluginFactory(Injector injector) { m_injector = injector; Map<Key<?>, Binding<?>> bindings = injector.getAllBindings(); for (Key<?> key : bindings.keySet()) { Class<?> bindingClass = key.getTypeLiteral().getRawType(); if (QueryPlugin.class.isAssignableFrom(bindingClass)) { PluginName ann = (PluginName) bindingClass.getAnnotation(PluginName.class); if (ann == null) throw new IllegalStateException("Aggregator class " + bindingClass.getName() + " does not have required annotation " + PluginName.class.getName()); m_plugins.put(ann.name(), (Class<QueryPlugin>)bindingClass); } } }
public void startServices() throws KairosDBException { Map<Key<?>, Binding<?>> bindings = m_injector.getAllBindings(); for (Key<?> key : bindings.keySet()) { Class<?> bindingClass = key.getTypeLiteral().getRawType(); if (KairosDBService.class.isAssignableFrom(bindingClass)) { KairosDBService service = (KairosDBService) m_injector.getInstance(bindingClass); logger.info("Starting service " + bindingClass); service.start(); m_services.add(service); } } }
@Inject @SuppressWarnings("unchecked") public GuiceGroupByFactory(Injector injector) { this.injector = injector; Map<Key<?>, Binding<?>> bindings = injector.getAllBindings(); for (Key<?> key : bindings.keySet()) { Class<?> bindingClass = key.getTypeLiteral().getRawType(); if (GroupBy.class.isAssignableFrom(bindingClass)) { GroupByName name = (GroupByName)bindingClass.getAnnotation(GroupByName.class); if (name == null) throw new IllegalStateException("Aggregator class "+bindingClass.getName()+ " does not have required annotation "+GroupByName.class.getName()); groupBys.put(name.name(), (Class<GroupBy>)bindingClass); } } }
@Inject public HealthCheckServiceImpl(Injector injector) { checkNotNull(injector); Map<Key<?>, Binding<?>> bindings = injector.getAllBindings(); for (Key<?> key : bindings.keySet()) { Class<?> bindingClass = key.getTypeLiteral().getRawType(); if (HealthStatus.class.isAssignableFrom(bindingClass)) { checks.add((HealthStatus) injector.getInstance(bindingClass)); } } }
@Override public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider, ObjectLocator locator) { TypeLiteral<T> type = TypeLiteral.get(objectType); List<Binding<T>> bindings = injector.findBindingsByType(type); for (Binding<T> binding : bindings) { Class<? extends Annotation> annotationType = binding.getKey().getAnnotationType(); Annotation annotation = annotationType != null ? annotationProvider.getAnnotation(annotationType) : null; Key<T> key = annotation != null ? Key.get(type, annotation) : Key.get(type); if (key.equals(binding.getKey())) { return injector.getInstance(key); } } return null; }
@Test public void testConfigureEndpoints_withInterceptor() { Injector injector = Guice.createInjector(module, new InterceptorModule()); Visitor visitor = new Visitor(); for (Binding<?> binding : injector.getAllBindings().values()) { binding.acceptTargetVisitor(visitor); } assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size()); LinkedServletBinding servletBinding = visitor.linkedServlets.get(0); assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern()); assertEquals("Wrong initialization parameter provided", "false", servletBinding.getInitParams().get("restricted")); assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider); ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get(); Collection<Object> services = serviceMap.getServices(); assertEquals("Incorrect number of services provided", 1, services.size()); assertEquals("Service not enhanced correctly.", SERVICES.toArray()[0], ((Class<?>) services.toArray()[0].getClass()).getSuperclass()); }
@Test public void testConfigureEndpoints_withoutInterceptor() { Injector injector = Guice.createInjector(module, new DummyModule()); Visitor visitor = new Visitor(); for (Binding<?> binding : injector.getAllBindings().values()) { binding.acceptTargetVisitor(visitor); } assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size()); LinkedServletBinding servletBinding = visitor.linkedServlets.get(0); assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern()); assertEquals("Wrong initialization parameter provided", "false", servletBinding.getInitParams().get("restricted")); assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider); ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get(); Collection<Object> services = serviceMap.getServices(); assertEquals("Incorrect number of services provided", 1, services.size()); assertEquals("Service not provided correctly.", SERVICES.toArray()[0], services.toArray()[0].getClass()); }
@Singleton @Provides LinkRestRuntime provideLinkRestRuntime( Injector injector, Set<LrFeatureProvider> featureProviders, Set<LinkRestAdapter> adapters) { LinkRestBuilder builder; Binding<ServerRuntime> binding = injector.getExistingBinding(Key.get(ServerRuntime.class)); if (binding == null) { builder = new LinkRestBuilder().cayenneService(new PojoCayennePersister()); } else { ServerRuntime cayenneRuntime = binding.getProvider().get(); builder = new LinkRestBuilder().cayenneRuntime(cayenneRuntime); } featureProviders.forEach(builder::feature); adapters.forEach(builder::adapter); return builder.build(); }
@Inject @Toolable @SuppressWarnings("unchecked") void initialize(Injector injector) { final Binding<T> realBinding = injector.getBinding(this.rewritten); final Provider<T> realProvider = injector.getProvider(realBinding.getKey()); // The proxy will be a sub type of the source type of the binding final Class<T> proxyType = (Class<T>) realBinding.getKey() .getTypeLiteral().getRawType(); this.dependencies = Collections.singleton( Dependency.get(this.rewritten)); this.ref = InstanceBuilder.forType(proxyType) .withConstructionStrategy(this.strategy) .dispatchTo(realProvider) .create(injector); }
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); } }
protected Map<String, CamelContext> getCamelContextMap() { Map<String, CamelContext> answer = Maps.newHashMap(); if (injector != null) { Set<Map.Entry<Key<?>, Binding<?>>> entries = injector.getBindings().entrySet(); for (Map.Entry<Key<?>, Binding<?>> entry : entries) { Key<?> key = entry.getKey(); Class<?> keyType = Injectors.getKeyType(key); if (keyType != null && CamelContext.class.isAssignableFrom(keyType)) { Binding<?> binding = entry.getValue(); Object value = binding.getProvider().get(); if (value != null) { CamelContext castValue = CamelContext.class.cast(value); answer.put(key.toString(), castValue); } } } } return answer; }
/** * Returns a collection of all instances of the given base type * * @param baseClass * the base type of objects required * @param <T> * the base type * @return a set of objects returned from this injector */ public static <T> Set<T> getInstancesOf(Injector injector, Class<T> baseClass) { Set<T> answer = Sets.newHashSet(); Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings() .entrySet(); for (Entry<Key<?>, Binding<?>> entry : entries) { Key<?> key = entry.getKey(); Class<?> keyType = getKeyType(key); if (keyType != null && baseClass.isAssignableFrom(keyType)) { Binding<?> binding = entry.getValue(); Object value = binding.getProvider().get(); if (value != null) { T castValue = baseClass.cast(value); answer.add(castValue); } } } return answer; }
/** * Returns a collection of all instances matching the given matcher * * @param matcher * matches the types to return instances * @return a set of objects returned from this injector */ public static <T> Set<T> getInstancesOf(Injector injector, Matcher<Class> matcher) { Set<T> answer = Sets.newHashSet(); Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings() .entrySet(); for (Entry<Key<?>, Binding<?>> entry : entries) { Key<?> key = entry.getKey(); Class<?> keyType = getKeyType(key); if (keyType != null && matcher.matches(keyType)) { Binding<?> binding = entry.getValue(); Object value = binding.getProvider().get(); answer.add((T) value); } } return answer; }
/** * Returns a collection of all of the providers matching the given matcher * * @param matcher * matches the types to return instances * @return a set of objects returned from this injector */ public static <T> Set<Provider<T>> getProvidersOf(Injector injector, Matcher<Class> matcher) { Set<Provider<T>> answer = Sets.newHashSet(); Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings() .entrySet(); for (Entry<Key<?>, Binding<?>> entry : entries) { Key<?> key = entry.getKey(); Class<?> keyType = getKeyType(key); if (keyType != null && matcher.matches(keyType)) { Binding<?> binding = entry.getValue(); answer.add((Provider<T>) binding.getProvider()); } } return answer; }
/** * Returns a collection of all providers of the given base type * * @param baseClass * the base type of objects required * @param <T> * the base type * @return a set of objects returned from this injector */ public static <T> Set<Provider<T>> getProvidersOf(Injector injector, Class<T> baseClass) { Set<Provider<T>> answer = Sets.newHashSet(); Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings() .entrySet(); for (Entry<Key<?>, Binding<?>> entry : entries) { Key<?> key = entry.getKey(); Class<?> keyType = getKeyType(key); if (keyType != null && baseClass.isAssignableFrom(keyType)) { Binding<?> binding = entry.getValue(); answer.add((Provider<T>) binding.getProvider()); } } return answer; }
/** * Closes objects within the given scope using the currently registered * {@link Closer} implementations */ public static void close(Injector injector, Class<? extends Annotation> scopeAnnotationToClose, CloseErrors errors) throws CloseFailedException { Set<Closer> closers = getInstancesOf(injector, Closer.class); Closer closer = CompositeCloser.newInstance(closers); if (closer == null) { return; } Set<Entry<Key<?>, Binding<?>>> entries = injector.getBindings() .entrySet(); for (Entry<Key<?>, Binding<?>> entry : entries) { Key<?> key = entry.getKey(); Binding<?> binding = entry.getValue(); closeBinding(key, binding, scopeAnnotationToClose, closer, errors); } tryCloseJitBindings(closer, injector, scopeAnnotationToClose, errors); errors.throwIfNecessary(); }
@Override public <T> com.google.inject.Provider<T> scope( com.github.ruediste.salta.core.Binding binding, CoreDependencyKey<T> requestedKey, com.google.inject.Provider<T> unscoped) { return new com.google.inject.Provider<T>() { private T value; private int snapshotTime = -1; @Override public T get() { if (snapshotTime != now) { value = unscoped.get(); snapshotTime = now; } return value; } }; }
@Override public Object lookupByName(String name) { Object answer = null; Map<Key<?>, Binding<?>> bindings = injector.getBindings(); for (Key<?> key : bindings.keySet()) { Annotation annotation = key.getAnnotation(); if (annotation instanceof CamelBind) { if (((CamelBind) annotation).value().equals(name)) { answer = injector.getInstance(key); } } } if (answer == null) { try { Class clazz = Class.forName(name); answer = injector.getInstance(clazz); } catch (ClassNotFoundException e) { String msg = "Bean with " + name + " not found in Guice registry ..."; logger.info(msg); } } return answer; }
@Override public <T> Map<String, T> findByTypeWithName(Class<T> type) { Map<String, T> result = Maps.newHashMap(); Map<Key<?>, Binding<?>> bindings = injector.getBindings(); for (Key<?> key : bindings.keySet()) { if (key.getTypeLiteral().getRawType().isAssignableFrom(type)) { Annotation annotation = key.getAnnotation(); String name = null; Object inst = injector.getInstance(key); if (annotation != null && annotation instanceof CamelBind) { name = ((CamelBind) key.getAnnotation()).value(); } else { name = type.getName(); } logger.debug("Found binding for name: {} with value: {}", name, inst); result.put(name, type.cast(inst)); } } return result; }
protected void applyScoping(Binding<?> binding, final ScopedBindingBuilder scopedBindingBuilder) { binding.acceptScopingVisitor(new BindingScopingVisitor<Void>() { public Void visitEagerSingleton() { if (scopedBindingBuilder != null) { scopedBindingBuilder.asEagerSingleton(); } return null; } public Void visitScope(Scope scope) { scopedBindingBuilder.in(scope); return null; } public Void visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) { scopedBindingBuilder.in(scopeAnnotation); return null; } public Void visitNoScoping() { // do nothing return null; } }); }
@SuppressWarnings("unchecked") private ConcurrentMap<String, CommandProvider> createMap() { ConcurrentMap<String, CommandProvider> m = Maps.newConcurrentMap(); for (Binding<?> b : allCommands()) { final Annotation annotation = b.getKey().getAnnotation(); if (annotation instanceof CommandName) { final CommandName n = (CommandName) annotation; if (!Commands.CMD_ROOT.equals(n) && Commands.isChild(parent, n)) { String descr = null; if (annotation instanceof Commands.NestedCommandNameImpl) { Commands.NestedCommandNameImpl impl = ((Commands.NestedCommandNameImpl) annotation); descr = impl.descr(); } m.put(n.value(), new CommandProvider((Provider<Command>) b.getProvider(), descr)); } } } return m; }
public static Map<TypeLiteral<?>, DynamicItem<?>> dynamicItemsOf(Injector src) { Map<TypeLiteral<?>, DynamicItem<?>> m = new HashMap<>(); for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) { TypeLiteral<?> type = e.getKey().getTypeLiteral(); if (type.getRawType() == DynamicItem.class) { ParameterizedType p = (ParameterizedType) type.getType(); m.put( TypeLiteral.get(p.getActualTypeArguments()[0]), (DynamicItem<?>) e.getValue().getProvider().get()); } } if (m.isEmpty()) { return Collections.emptyMap(); } return Collections.unmodifiableMap(m); }
public static Map<TypeLiteral<?>, DynamicSet<?>> dynamicSetsOf(Injector src) { Map<TypeLiteral<?>, DynamicSet<?>> m = new HashMap<>(); for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) { TypeLiteral<?> type = e.getKey().getTypeLiteral(); if (type.getRawType() == DynamicSet.class) { ParameterizedType p = (ParameterizedType) type.getType(); m.put( TypeLiteral.get(p.getActualTypeArguments()[0]), (DynamicSet<?>) e.getValue().getProvider().get()); } } if (m.isEmpty()) { return Collections.emptyMap(); } return Collections.unmodifiableMap(m); }
public static Map<TypeLiteral<?>, DynamicMap<?>> dynamicMapsOf(Injector src) { Map<TypeLiteral<?>, DynamicMap<?>> m = new HashMap<>(); for (Map.Entry<Key<?>, Binding<?>> e : src.getBindings().entrySet()) { TypeLiteral<?> type = e.getKey().getTypeLiteral(); if (type.getRawType() == DynamicMap.class) { ParameterizedType p = (ParameterizedType) type.getType(); m.put( TypeLiteral.get(p.getActualTypeArguments()[0]), (DynamicMap<?>) e.getValue().getProvider().get()); } } if (m.isEmpty()) { return Collections.emptyMap(); } return Collections.unmodifiableMap(m); }
public void checkInjector(Module module, ElementVisitor<?>... visitors) { Injector injector = Guice.createInjector(module); List<Binding<?>> bindings = Lists.newArrayList(injector.getBindings().values()); for (Iterator<Binding<?>> i = bindings.iterator(); i.hasNext(); ) { if (BUILT_IN_BINDINGS.contains(i.next().getKey())) { i.remove(); } } Collections.sort(bindings, orderByKey); assertEquals(bindings.size(), visitors.length); for (int i = 0; i < visitors.length; i++) { ElementVisitor<?> visitor = visitors[i]; Binding<?> binding = bindings.get(i); binding.acceptVisitor(visitor); } }
@Override public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception { TypeLiteral<ComponentManager<?>> managerLiteral = (TypeLiteral<ComponentManager<?>>) TypeLiteral.get(Types.newParameterizedType(ComponentManager.class, argType)); Binding<ComponentManager<?>> managerBinding = injector.getExistingBinding(Key.get(managerLiteral)); if (managerBinding != null) { ComponentManager<?> manager = managerBinding.getProvider().get(); try { method.invoke(obj, manager.get(name)); return true; } catch (Exception e) { throw new Exception(String.format( "Unable to get component '%s' (%s) for property '%s' must be one of %s", name, argType.getSimpleName(), propertyName, manager.getIds()), e); } } return false; }
@Override public boolean execute(String name, Object obj, ConfigurationNode config, Class<?> argType, Injector injector, Method method) throws Exception { Binding<?> binding; Type pType = method.getGenericParameterTypes()[0]; if (pType != null) { binding = injector.getExistingBinding(Key.get(pType, Names.named(name))); } else { binding = injector.getExistingBinding(Key.get(argType, Names.named(name))); } if (binding != null) { method.invoke(obj, binding.getProvider().get()); return true; } return false; }
@Override protected void doInitialize(InjectorImpl injector, Errors errors) { ImmutableMap.Builder<K, Set<Provider<V>>> multimapOfProvidersBuilder = ImmutableMap.builder(); ImmutableSet.Builder<Dependency<?>> dependenciesBuilder = ImmutableSet.builder(); for (Map.Entry<K, Set<Binding<V>>> entry : bindingSelection.getMultimapBindings().entrySet()) { ImmutableSet.Builder<Provider<V>> providersBuilder = ImmutableSet.builder(); for (Binding<V> binding : entry.getValue()) { providersBuilder.add(binding.getProvider()); dependenciesBuilder.add(Dependency.get(getKeyOfProvider(binding.getKey()))); } multimapOfProvidersBuilder.put(entry.getKey(), providersBuilder.build()); } multimapOfProviders = multimapOfProvidersBuilder.build(); dependencies = dependenciesBuilder.build(); }
public void testBindToInstanceScope() { checkModule( new AbstractModule() { protected void configure() { bind(String.class).toInstance("A"); } }, new FailingElementVisitor() { @Override public <T> Void visit(Binding<T> binding) { assertEquals(Key.get(String.class), binding.getKey()); binding.acceptScopingVisitor(new FailingBindingScopingVisitor() { public Void visitEagerSingleton() { return null; } }); return null; } } ); }
private static String instantiation(Binding<?> binding) { if (binding instanceof InstanceBinding<?>) { return instanceLiteral((InstanceBinding<?>) binding); } else if (binding instanceof ProviderKeyBinding<?>) { return providerCall(((ProviderKeyBinding<?>) binding).getProviderKey()) + ".get()"; } else if (binding instanceof LinkedKeyBinding<?>) { return providerCall(((LinkedKeyBinding<?>) binding).getLinkedKey()); } else if (binding instanceof ConstructorBinding<?>) { return constructorCall((ConstructorBinding<?>) binding); } else if (binding instanceof ProviderBinding<?>) { return provider((ProviderBinding<?>) binding); } else if (binding instanceof ProviderInstanceBinding<?>) { return instantiation((ProviderInstanceBinding<?>) binding); } else { throw new DeguicifierException(); } }
public void testBindKeysWithAnnotationType() { FailingElementVisitor annotationChecker = new FailingElementVisitor() { @Override public <T> Void visit(Binding<T> command) { assertEquals(Key.get(String.class, SampleAnnotation.class), command.getKey()); return null; } }; checkModule( new AbstractModule() { @Override protected void configure() { bind(String.class).annotatedWith(SampleAnnotation.class).toInstance("A"); bind(new TypeLiteral<String>() {}) .annotatedWith(SampleAnnotation.class) .toInstance("B"); } }, annotationChecker, annotationChecker); }
public void testServletModuleReuse() { Module module = new Module(); Elements.getElements(module); // use the module once (to, say, introspect bindings) Injector injector = Guice.createInjector(module); // use it again. Visitor visitor = new Visitor(); // Validate only a single servlet binding & a single filter binding exist. for(Binding<?> binding : injector.getAllBindings().values()) { binding.acceptTargetVisitor(visitor); } assertEquals("wrong linked servlets: " + visitor.linkedServlets, 0, visitor.linkedServlets.size()); assertEquals("wrong linked filters: " + visitor.linkedFilters, 0, visitor.linkedFilters.size()); assertEquals("wrong instance servlets: " + visitor.instanceServlets, 1, visitor.instanceServlets.size()); assertEquals("wrong instance filters: " + visitor.instanceFilters, 1, visitor.instanceFilters.size()); }
boolean containsElement(com.google.inject.spi.Element element) { if (entrySetBinder.containsElement(element)) { return true; } else { Key<?> key; if (element instanceof Binding) { key = ((Binding<?>)element).getKey(); } else if (element instanceof ProviderLookup) { key = ((ProviderLookup<?>)element).getKey(); } else { return false; // cannot match; } return key.equals(mapKey) || key.equals(providerMapKey) || key.equals(javaxProviderMapKey) || key.equals(multimapKey) || key.equals(providerMultimapKey) || key.equals(entrySetBinder.getSetKey()) || matchesValueKey(key); } }
@Override public void init(FilterConfig servletConfig) throws ServletException { super.init(servletConfig); Registry registry = getDispatcher().getRegistry(); ResteasyProviderFactory providerFactory = getDispatcher().getProviderFactory(); for (final Binding<?> binding : injector.getBindings().values()) { Type type = binding.getKey().getTypeLiteral().getType(); if (type instanceof Class) { Class<?> beanClass = (Class<?>) type; if (GetRestful.isRootResource(beanClass)) { ResourceFactory resourceFactory = new GuiceResourceFactory(binding.getProvider(), beanClass); log.info("registering factory for {}", beanClass.getName()); registry.addResourceFactory(resourceFactory); } if (beanClass.isAnnotationPresent(Provider.class)) { log.info("registering provider instance for {}", beanClass.getName()); providerFactory.registerProviderInstance(binding.getProvider().get()); } } } }
public void testServletModuleReuse() { Module module = new Module(); Elements.getElements(module); // use the module once (to, say, introspect bindings) Injector injector = Guice.createInjector(module); // use it again. Visitor visitor = new Visitor(); // Validate only a single servlet binding & a single filter binding exist. for (Binding<?> binding : injector.getAllBindings().values()) { binding.acceptTargetVisitor(visitor); } assertEquals( "wrong linked servlets: " + visitor.linkedServlets, 0, visitor.linkedServlets.size()); assertEquals("wrong linked filters: " + visitor.linkedFilters, 0, visitor.linkedFilters.size()); assertEquals( "wrong instance servlets: " + visitor.instanceServlets, 1, visitor.instanceServlets.size()); assertEquals( "wrong instance filters: " + visitor.instanceFilters, 1, visitor.instanceFilters.size()); }