Search in sources :

Example 1 with InstanceBinding

use of com.google.inject.spi.InstanceBinding in project roboguice by roboguice.

the class MultibinderTest method testSetAndMapValueAreDistinctInSpi.

// See issue 670
public void testSetAndMapValueAreDistinctInSpi() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            Multibinder.newSetBinder(binder(), String.class).addBinding().toInstance("A");
            MapBinder.newMapBinder(binder(), String.class, String.class).addBinding("B").toInstance("b");
            OptionalBinder.newOptionalBinder(binder(), String.class).setDefault().toInstance("C");
        }
    });
    Collector collector = new Collector();
    Binding<Map<String, String>> mapbinding = injector.getBinding(Key.get(mapOfStringString));
    mapbinding.acceptTargetVisitor(collector);
    assertNotNull(collector.mapbinding);
    Binding<Set<String>> setbinding = injector.getBinding(Key.get(setOfString));
    setbinding.acceptTargetVisitor(collector);
    assertNotNull(collector.setbinding);
    Binding<Optional<String>> optionalbinding = injector.getBinding(Key.get(optionalOfString));
    optionalbinding.acceptTargetVisitor(collector);
    assertNotNull(collector.optionalbinding);
    // There should only be three instance bindings for string types
    // (but because of the OptionalBinder, there's 2 ProviderInstanceBindings also).
    // We also know the InstanceBindings will be in the order: A, b, C because that's
    // how we bound them, and binding order is preserved.
    List<Binding<String>> bindings = FluentIterable.from(injector.findBindingsByType(stringType)).filter(Predicates.instanceOf(InstanceBinding.class)).toList();
    assertEquals(bindings.toString(), 3, bindings.size());
    Binding<String> a = bindings.get(0);
    Binding<String> b = bindings.get(1);
    Binding<String> c = bindings.get(2);
    assertEquals("A", ((InstanceBinding<String>) a).getInstance());
    assertEquals("b", ((InstanceBinding<String>) b).getInstance());
    assertEquals("C", ((InstanceBinding<String>) c).getInstance());
    // Make sure the correct elements belong to their own sets.
    assertFalse(collector.mapbinding.containsElement(a));
    assertTrue(collector.mapbinding.containsElement(b));
    assertFalse(collector.mapbinding.containsElement(c));
    assertTrue(collector.setbinding.containsElement(a));
    assertFalse(collector.setbinding.containsElement(b));
    assertFalse(collector.setbinding.containsElement(c));
    assertFalse(collector.optionalbinding.containsElement(a));
    assertFalse(collector.optionalbinding.containsElement(b));
    assertTrue(collector.optionalbinding.containsElement(c));
}
Also used : Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) LinkedKeyBinding(com.google.inject.spi.LinkedKeyBinding) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) Optional(com.google.common.base.Optional) AbstractModule(com.google.inject.AbstractModule) Injector(com.google.inject.Injector) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 2 with InstanceBinding

use of com.google.inject.spi.InstanceBinding in project roboguice by roboguice.

the class MultibinderTest method testMultibinderDependenciesInToolStage.

/**
   * We just want to make sure that multibinder's binding depends on each of its values. We don't
   * really care about the underlying structure of those bindings, which are implementation details.
   */
public void testMultibinderDependenciesInToolStage() {
    Injector injector = Guice.createInjector(Stage.TOOL, new AbstractModule() {

        protected void configure() {
            Multibinder<String> multibinder = Multibinder.newSetBinder(binder(), String.class);
            multibinder.addBinding().toInstance("A");
            multibinder.addBinding().to(Key.get(String.class, Names.named("b")));
            bindConstant().annotatedWith(Names.named("b")).to("B");
        }
    });
    Binding<Set<String>> binding = injector.getBinding(new Key<Set<String>>() {
    });
    HasDependencies withDependencies = (HasDependencies) binding;
    InstanceBinding<?> instanceBinding = null;
    LinkedKeyBinding<?> linkedBinding = null;
    // the Key of @Named("b") String=B
    for (Dependency<?> dependency : withDependencies.getDependencies()) {
        Binding<?> b = injector.getBinding(dependency.getKey());
        if (b instanceof InstanceBinding) {
            if (instanceBinding != null) {
                fail("Already have an instance binding of: " + instanceBinding + ", and now want to add: " + b);
            } else {
                instanceBinding = (InstanceBinding) b;
            }
        } else if (b instanceof LinkedKeyBinding) {
            if (linkedBinding != null) {
                fail("Already have a linked binding of: " + linkedBinding + ", and now want to add: " + b);
            } else {
                linkedBinding = (LinkedKeyBinding) b;
            }
        } else {
            fail("Unexpected dependency of: " + dependency);
        }
    }
    assertNotNull(instanceBinding);
    assertNotNull(linkedBinding);
    assertEquals("A", instanceBinding.getInstance());
    assertEquals(Key.get(String.class, Names.named("b")), linkedBinding.getLinkedKey());
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) HasDependencies(com.google.inject.spi.HasDependencies) AbstractModule(com.google.inject.AbstractModule) InstanceBinding(com.google.inject.spi.InstanceBinding) Injector(com.google.inject.Injector) LinkedKeyBinding(com.google.inject.spi.LinkedKeyBinding)

Example 3 with InstanceBinding

use of com.google.inject.spi.InstanceBinding in project roboguice by roboguice.

the class MapBinderTest method recurseForDependencies.

private Set<String> recurseForDependencies(Injector injector, HasDependencies hasDependencies) {
    Set<String> elements = Sets.newHashSet();
    for (Dependency<?> dependency : hasDependencies.getDependencies()) {
        Binding<?> binding = injector.getBinding(dependency.getKey());
        HasDependencies deps = (HasDependencies) binding;
        if (binding instanceof InstanceBinding) {
            elements.add((String) ((InstanceBinding<?>) binding).getInstance());
        } else {
            elements.addAll(recurseForDependencies(injector, deps));
        }
    }
    return elements;
}
Also used : InstanceBinding(com.google.inject.spi.InstanceBinding) HasDependencies(com.google.inject.spi.HasDependencies)

Example 4 with InstanceBinding

use of com.google.inject.spi.InstanceBinding in project roboguice by roboguice.

the class OptionalBinderTest method recurseForDependencies.

@SuppressWarnings("rawtypes")
private Set<String> recurseForDependencies(Injector injector, HasDependencies hasDependencies) {
    Set<String> elements = Sets.newHashSet();
    for (Dependency<?> dependency : hasDependencies.getDependencies()) {
        Binding<?> binding = injector.getBinding(dependency.getKey());
        HasDependencies deps = (HasDependencies) binding;
        if (binding instanceof InstanceBinding) {
            elements.add((String) ((InstanceBinding) binding).getInstance());
        } else {
            elements.addAll(recurseForDependencies(injector, deps));
        }
    }
    return elements;
}
Also used : InstanceBinding(com.google.inject.spi.InstanceBinding) HasDependencies(com.google.inject.spi.HasDependencies)

Example 5 with InstanceBinding

use of com.google.inject.spi.InstanceBinding in project guice by google.

the class InjectorImpl method convertConstantStringBinding.

/**
   * Converts a constant string binding to the required type.
   *
   * @return the binding if it could be resolved, or null if the binding doesn't exist
   * @throws com.google.inject.internal.ErrorsException if there was an error resolving the binding
   */
private <T> BindingImpl<T> convertConstantStringBinding(Key<T> key, Errors errors) throws ErrorsException {
    // Find a constant string binding.
    Key<String> stringKey = key.ofType(STRING_TYPE);
    BindingImpl<String> stringBinding = state.getExplicitBinding(stringKey);
    if (stringBinding == null || !stringBinding.isConstant()) {
        return null;
    }
    // We can't call getProvider().get() because this InstanceBinding may not have been inintialized
    // yet (because we may have been called during InternalInjectorCreator.initializeStatically and
    // instance binding validation hasn't happened yet.)
    @SuppressWarnings("unchecked") String stringValue = ((InstanceBinding<String>) stringBinding).getInstance();
    Object source = stringBinding.getSource();
    // Find a matching type converter.
    TypeLiteral<T> type = key.getTypeLiteral();
    TypeConverterBinding typeConverterBinding = state.getConverter(stringValue, type, errors, source);
    if (typeConverterBinding == null) {
        // No converter can handle the given type.
        return null;
    }
    // Try to convert the string. A failed conversion results in an error.
    try {
        // This cast is safe because we double check below.
        @SuppressWarnings("unchecked") T converted = (T) typeConverterBinding.getTypeConverter().convert(stringValue, type);
        if (converted == null) {
            throw errors.converterReturnedNull(stringValue, source, type, typeConverterBinding).toException();
        }
        if (!type.getRawType().isInstance(converted)) {
            throw errors.conversionTypeError(stringValue, source, type, typeConverterBinding, converted).toException();
        }
        return new ConvertedConstantBindingImpl<T>(this, key, converted, stringBinding, typeConverterBinding);
    } catch (ErrorsException e) {
        throw e;
    } catch (RuntimeException e) {
        throw errors.conversionError(stringValue, source, type, typeConverterBinding, e).toException();
    }
}
Also used : InstanceBinding(com.google.inject.spi.InstanceBinding) TypeConverterBinding(com.google.inject.spi.TypeConverterBinding)

Aggregations

InstanceBinding (com.google.inject.spi.InstanceBinding)18 AbstractModule (com.google.inject.AbstractModule)12 Binding (com.google.inject.Binding)6 Injector (com.google.inject.Injector)6 Module (com.google.inject.Module)6 HasDependencies (com.google.inject.spi.HasDependencies)6 Map (java.util.Map)6 ImmutableSet (com.google.common.collect.ImmutableSet)4 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)4 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)4 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 List (java.util.List)4 Set (java.util.Set)4 MapBinderBinding (com.google.inject.multibindings.MapBinderBinding)3 Optional (com.google.common.base.Optional)2 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 ProviderMapEntry (com.google.inject.internal.RealMapBinder.ProviderMapEntry)2 ProgramType (co.cask.cdap.proto.ProgramType)1