Search in sources :

Example 26 with Element

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

the class SpiUtils method mapModuleTest.

@SuppressWarnings("unchecked")
private static <T> void mapModuleTest(Key<T> mapKey, TypeLiteral<?> keyType, TypeLiteral<?> valueType, Iterable<? extends Module> modules, boolean allowDuplicates, int expectedMapBindings, MapResult... results) {
    Set<Element> elements = ImmutableSet.copyOf(Elements.getElements(modules));
    Visitor<T> visitor = new Visitor<T>();
    MapBinderBinding<T> mapbinder = null;
    Map<Key<?>, Binding<?>> keyMap = Maps.newHashMap();
    for (Element element : elements) {
        if (element instanceof Binding) {
            Binding<?> binding = (Binding<?>) element;
            keyMap.put(binding.getKey(), binding);
            if (binding.getKey().equals(mapKey)) {
                mapbinder = (MapBinderBinding<T>) ((Binding<T>) binding).acceptTargetVisitor(visitor);
            }
        }
    }
    assertNotNull(mapbinder);
    assertEquals(keyType, mapbinder.getKeyTypeLiteral());
    assertEquals(valueType, mapbinder.getValueTypeLiteral());
    List<MapResult> mapResults = Lists.newArrayList(results);
    Key<?> mapOfProvider = mapKey.ofType(mapOfProviderOf(keyType, valueType));
    Key<?> mapOfSetOfProvider = mapKey.ofType(mapOfSetOfProviderOf(keyType, valueType));
    Key<?> mapOfSet = mapKey.ofType(mapOf(keyType, setOf(valueType)));
    Key<?> setOfEntry = mapKey.ofType(setOf(entryOfProviderOf(keyType, valueType)));
    Key<?> collectionOfProvidersOfEntry = mapKey.ofType(collectionOfProvidersOf(entryOfProviderOf(keyType, valueType)));
    boolean entrySetMatch = false;
    boolean entryProviderCollectionMatch = false;
    boolean mapProviderMatch = false;
    boolean mapSetMatch = false;
    boolean mapSetProviderMatch = false;
    List<Object> otherMapBindings = Lists.newArrayList();
    List<Element> otherMatches = Lists.newArrayList();
    List<Element> otherElements = Lists.newArrayList();
    Indexer indexer = new Indexer(null);
    Multimap<Object, IndexedBinding> indexedEntries = MultimapBuilder.hashKeys().hashSetValues().build();
    int duplicates = 0;
    for (Element element : elements) {
        boolean contains = mapbinder.containsElement(element);
        if (!contains) {
            otherElements.add(element);
        }
        boolean matched = false;
        Key key = null;
        Binding b = null;
        if (element instanceof Binding) {
            b = (Binding) element;
            if (b instanceof ProviderInstanceBinding) {
                ProviderInstanceBinding<?> pb = (ProviderInstanceBinding<?>) b;
                if (pb.getUserSuppliedProvider() instanceof ProviderMapEntry) {
                    // weird casting required to workaround jdk6 compilation problems
                    ProviderMapEntry<?, ?> pme = (ProviderMapEntry<?, ?>) (Provider) pb.getUserSuppliedProvider();
                    Binding<?> valueBinding = keyMap.get(pme.getValueKey());
                    if (indexer.isIndexable(valueBinding) && !indexedEntries.put(pme.getKey(), valueBinding.acceptTargetVisitor(indexer))) {
                        duplicates++;
                    }
                }
            }
            key = b.getKey();
            Object visited = b.acceptTargetVisitor(visitor);
            if (visited instanceof MapBinderBinding) {
                matched = true;
                if (visited.equals(mapbinder)) {
                    assertTrue(contains);
                } else {
                    otherMapBindings.add(visited);
                }
            }
        } else if (element instanceof ProviderLookup) {
            key = ((ProviderLookup) element).getKey();
        }
        if (!matched && key != null) {
            if (key.equals(mapOfProvider)) {
                matched = true;
                assertTrue(contains);
                mapProviderMatch = true;
            } else if (key.equals(mapOfSet)) {
                matched = true;
                assertTrue(contains);
                mapSetMatch = true;
            } else if (key.equals(mapOfSetOfProvider)) {
                matched = true;
                assertTrue(contains);
                mapSetProviderMatch = true;
            } else if (key.equals(setOfEntry)) {
                matched = true;
                assertTrue(contains);
                entrySetMatch = true;
                // Validate that this binding is also a MultibinderBinding.
                if (b != null) {
                    assertTrue(b.acceptTargetVisitor(visitor) instanceof MultibinderBinding);
                }
            } else if (key.equals(collectionOfProvidersOfEntry)) {
                matched = true;
                assertTrue(contains);
                entryProviderCollectionMatch = true;
            }
        }
        if (!matched && contains) {
            otherMatches.add(element);
        }
    }
    int otherMatchesSize = otherMatches.size();
    if (allowDuplicates) {
        // allow for 1 duplicate binding
        otherMatchesSize--;
    }
    // value, ProviderLookup per value, Map.Entry per value
    otherMatchesSize = otherMatchesSize / 3;
    assertEquals("incorrect number of contains, leftover matches: " + otherMatches, mapResults.size() + duplicates, otherMatchesSize);
    assertTrue(entrySetMatch);
    assertTrue(entryProviderCollectionMatch);
    assertTrue(mapProviderMatch);
    assertEquals(allowDuplicates, mapSetMatch);
    assertEquals(allowDuplicates, mapSetProviderMatch);
    assertEquals("other MapBindings found: " + otherMapBindings, expectedMapBindings, otherMapBindings.size());
    // Validate that we can construct an injector out of the remaining bindings.
    Guice.createInjector(Elements.getModule(otherElements));
}
Also used : DefaultBindingTargetVisitor(com.google.inject.spi.DefaultBindingTargetVisitor) Element(com.google.inject.spi.Element) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) IndexedBinding(com.google.inject.multibindings.Indexer.IndexedBinding) Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) ProviderKeyBinding(com.google.inject.spi.ProviderKeyBinding) LinkedKeyBinding(com.google.inject.spi.LinkedKeyBinding) IndexedBinding(com.google.inject.multibindings.Indexer.IndexedBinding) ProviderMapEntry(com.google.inject.multibindings.MapBinder.RealMapBinder.ProviderMapEntry) ProviderLookup(com.google.inject.spi.ProviderLookup) Key(com.google.inject.Key)

Example 27 with Element

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

the class ServletScopesTest method testIsRequestScopedPositive.

public void testIsRequestScopedPositive() {
    final Key<String> a = Key.get(String.class, named("A"));
    final Key<String> b = Key.get(String.class, named("B"));
    final Key<String> c = Key.get(String.class, named("C"));
    final Key<String> d = Key.get(String.class, named("D"));
    final Key<Object> e = Key.get(Object.class, named("E"));
    final Key<String> f = Key.get(String.class, named("F"));
    final Key<String> g = Key.get(String.class, named("G"));
    Module requestScopedBindings = new AbstractModule() {

        @Override
        protected void configure() {
            bind(a).to(b);
            bind(b).to(c);
            bind(c).toProvider(Providers.of("c")).in(ServletScopes.REQUEST);
            bind(d).toProvider(Providers.of("d")).in(RequestScoped.class);
            bind(e).to(AnnotatedRequestScopedClass.class);
            install(new PrivateModule() {

                @Override
                protected void configure() {
                    bind(f).toProvider(Providers.of("f")).in(RequestScoped.class);
                    expose(f);
                }
            });
        }

        @Provides
        @Named("G")
        @RequestScoped
        String provideG() {
            return "g";
        }
    };
    // we know the module contains only bindings
    @SuppressWarnings("unchecked") List<Element> moduleBindings = Elements.getElements(requestScopedBindings);
    ImmutableMap<Key<?>, Binding<?>> map = indexBindings(moduleBindings);
    // linked bindings are not followed by modules
    assertFalse(ServletScopes.isRequestScoped(map.get(a)));
    assertFalse(ServletScopes.isRequestScoped(map.get(b)));
    assertTrue(ServletScopes.isRequestScoped(map.get(c)));
    assertTrue(ServletScopes.isRequestScoped(map.get(d)));
    // annotated classes are not followed by modules
    assertFalse(ServletScopes.isRequestScoped(map.get(e)));
    assertTrue(ServletScopes.isRequestScoped(map.get(f)));
    assertTrue(ServletScopes.isRequestScoped(map.get(g)));
    Injector injector = Guice.createInjector(requestScopedBindings, new ServletModule());
    assertTrue(ServletScopes.isRequestScoped(injector.getBinding(a)));
    assertTrue(ServletScopes.isRequestScoped(injector.getBinding(b)));
    assertTrue(ServletScopes.isRequestScoped(injector.getBinding(c)));
    assertTrue(ServletScopes.isRequestScoped(injector.getBinding(d)));
    assertTrue(ServletScopes.isRequestScoped(injector.getBinding(e)));
    assertTrue(ServletScopes.isRequestScoped(injector.getBinding(f)));
    assertTrue(ServletScopes.isRequestScoped(injector.getBinding(g)));
}
Also used : Binding(com.google.inject.Binding) Element(com.google.inject.spi.Element) AbstractModule(com.google.inject.AbstractModule) Injector(com.google.inject.Injector) Module(com.google.inject.Module) PrivateModule(com.google.inject.PrivateModule) AbstractModule(com.google.inject.AbstractModule) PrivateModule(com.google.inject.PrivateModule) Key(com.google.inject.Key)

Example 28 with Element

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

the class MultibinderTest method testConcurrentMutation_bindingsDiffentAtInjectorCreation.

/*
   * Verify through gratuitous mutation that key hashCode snapshots and whatnot happens at the right
   * times, by binding two lists that are different at injector creation, but compare equal when the
   * module is configured *and* when the set is instantiated.
   */
public void testConcurrentMutation_bindingsDiffentAtInjectorCreation() {
    // We initially bind two equal lists
    final List<String> list1 = Lists.newArrayList();
    final List<String> list2 = Lists.newArrayList();
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings);
            multibinder.addBinding().toInstance(list1);
            multibinder.addBinding().toInstance(list2);
        }
    };
    List<Element> elements = Elements.getElements(module);
    // Now we change the lists so they no longer match, and create the injector.
    list1.add("A");
    list2.add("B");
    Injector injector = Guice.createInjector(Elements.getModule(elements));
    // Now we change the lists so they compare equal again, and create the set.
    list1.add(1, "B");
    list2.add(0, "A");
    try {
        injector.getInstance(Key.get(setOfListOfStrings));
        fail();
    } catch (ProvisionException e) {
        assertEquals(1, e.getErrorMessages().size());
        assertContains(Iterables.getOnlyElement(e.getErrorMessages()).getMessage().toString(), "Set injection failed due to duplicated element \"[A, B]\"");
    }
    // Finally, we change the lists again so they are once more different, and ensure the set
    // contains both.
    list1.remove("A");
    list2.remove("B");
    Set<List<String>> set = injector.getInstance(Key.get(setOfListOfStrings));
    assertEquals(ImmutableSet.of(ImmutableList.of("A"), ImmutableList.of("B")), set);
}
Also used : ProvisionException(com.google.inject.ProvisionException) Injector(com.google.inject.Injector) Element(com.google.inject.spi.Element) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule)

Example 29 with Element

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

the class MultibinderTest method testConcurrentMutation_bindingsSameAtInjectorCreation.

/*
   * Verify through gratuitous mutation that key hashCode snapshots and whatnot happen at the right
   * times, by binding two lists that compare equal at injector creation, but are different when the
   * module is configured *and* when the set is instantiated.
   */
public void testConcurrentMutation_bindingsSameAtInjectorCreation() {
    // We initially bind two distinct lists
    final List<String> list1 = Lists.newArrayList("A");
    final List<String> list2 = Lists.newArrayList("B");
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings);
            multibinder.addBinding().toInstance(list1);
            multibinder.addBinding().toInstance(list2);
        }
    };
    List<Element> elements = Elements.getElements(module);
    // Now we change the lists so they compare equal, and create the injector.
    list1.add(1, "B");
    list2.add(0, "A");
    Injector injector = Guice.createInjector(Elements.getModule(elements));
    // Now we change the lists again so they are once more different, and create the set.
    list1.remove("A");
    list2.remove("B");
    Set<List<String>> set = injector.getInstance(Key.get(setOfListOfStrings));
    // The set will contain just one of the two lists.
    // (In fact, it will be the first one we bound, but we don't promise that, so we won't test it.)
    assertTrue(ImmutableSet.of(ImmutableList.of("A")).equals(set) || ImmutableSet.of(ImmutableList.of("B")).equals(set));
}
Also used : Injector(com.google.inject.Injector) Element(com.google.inject.spi.Element) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule)

Aggregations

Element (com.google.inject.spi.Element)29 Binding (com.google.inject.Binding)18 Key (com.google.inject.Key)16 AbstractModule (com.google.inject.AbstractModule)13 Injector (com.google.inject.Injector)10 Module (com.google.inject.Module)10 ImmutableMap (com.google.common.collect.ImmutableMap)7 Map (java.util.Map)7 DefaultBindingTargetVisitor (com.google.inject.spi.DefaultBindingTargetVisitor)6 InstanceBinding (com.google.inject.spi.InstanceBinding)6 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)6 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)6 ProviderKeyBinding (com.google.inject.spi.ProviderKeyBinding)6 ImmutableList (com.google.common.collect.ImmutableList)4 PrivateModule (com.google.inject.PrivateModule)4 PrivateElements (com.google.inject.spi.PrivateElements)4 ProviderLookup (com.google.inject.spi.ProviderLookup)4 List (java.util.List)4 IndexedBinding (com.google.inject.internal.Indexer.IndexedBinding)3 IndexedBinding (com.google.inject.multibindings.Indexer.IndexedBinding)3