Java Code Examples for com.google.inject.Binding

The following are top voted examples for showing how to use com.google.inject.Binding. 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: ProjectAres   File: Scoper.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 2
Project: Equella   File: GuicePlugin.java   Source Code and License 6 votes vote down vote up
@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);
	}
}
 
Example 3
Project: abhot   File: GuiceQueryPluginFactory.java   Source Code and License 6 votes vote down vote up
@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);
		}
	}
}
 
Example 4
Project: abhot   File: Main.java   Source Code and License 6 votes vote down vote up
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);
		}
	}
}
 
Example 5
Project: abhot   File: GuiceGroupByFactory.java   Source Code and License 6 votes vote down vote up
@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);
		}
	}
}
 
Example 6
Project: abhot   File: HealthCheckServiceImpl.java   Source Code and License 6 votes vote down vote up
@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));
		}
	}
}
 
Example 7
Project: bootique-tapestry   File: GuiceObjectProvider.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 8
Project: endpoints-java   File: EndpointsModuleTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 9
Project: endpoints-java   File: EndpointsModuleTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 10
Project: bootique-linkrest   File: LinkRestModule.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 11
Project: guice-scoped-proxy-extension   File: ScopedProxyBinder.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 12
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 13
Project: Camel   File: Main.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 14
Project: Camel   File: Injectors.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: Camel   File: Injectors.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: Camel   File: Injectors.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 17
Project: Camel   File: Injectors.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 18
Project: Camel   File: Injectors.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 19
Project: salta   File: Jsr330Test.java   Source Code and License 6 votes vote down vote up
@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;
        }
    };
}
 
Example 20
Project: microservice-bundle   File: GuiceRegistry.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 21
Project: microservice-bundle   File: GuiceRegistry.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 22
Project: guiceberry   File: ModuleWriter.java   Source Code and License 6 votes vote down vote up
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;
    }
  });
}
 
Example 23
Project: guiceberry   File: ModuleWriter.java   Source Code and License 6 votes vote down vote up
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;
    }
  });
}
 
Example 24
Project: bootique-linkrest   File: LinkRestModule.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 25
Project: gerrit   File: DispatchCommandProvider.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 26
Project: gerrit   File: PrivateInternals_DynamicTypes.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 27
Project: gerrit   File: PrivateInternals_DynamicTypes.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 28
Project: gerrit   File: PrivateInternals_DynamicTypes.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 29
Project: guice-scoped-proxy-extension   File: ScopedProxyBinder.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 30
Project: guice   File: SpiBindingsTest.java   Source Code and License 6 votes vote down vote up
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);
  }
}
 
Example 31
Project: fabricator   File: NamedComponentManagerBinding.java   Source Code and License 6 votes vote down vote up
@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;    
}
 
Example 32
Project: fabricator   File: NamedBinding.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 33
Project: guice   File: RealMapBinder.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 34
Project: guice-old   File: ElementsTest.java   Source Code and License 6 votes vote down vote up
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;
        }
      }
    );
}
 
Example 35
Project: deguicifier   File: Generators.java   Source Code and License 6 votes vote down vote up
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();
  }
}
 
Example 36
Project: guice   File: ElementsTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 37
Project: guice-old   File: ServletModuleTest.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 38
Project: guice-old   File: MapBinder.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 39
Project: shiro-guice-resteasy-webapp   File: GuiceRestEasyFilterDispatcher.java   Source Code and License 6 votes vote down vote up
@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());
            }
        }
    }
}
 
Example 40
Project: guice   File: ServletModuleTest.java   Source Code and License 6 votes vote down vote up
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());
}