Search in sources :

Example 66 with Binding

use of com.google.inject.Binding in project guice by google.

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 67 with Binding

use of com.google.inject.Binding in project guice by google.

the class Errors method missingImplementationWithHint.

/** Within guice's core, allow for better missing binding messages */
<T> Errors missingImplementationWithHint(Key<T> key, Injector injector) {
    StringBuilder sb = new StringBuilder();
    sb.append(format("No implementation for %s was bound.", key));
    // Keys which have similar strings as the desired key
    List<String> possibleMatches = new ArrayList<String>();
    // Check for other keys that may have the same type,
    // but not the same annotation
    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) {
            // TODO: Look into a better way to prioritize suggestions. For example, possbily
            // use levenshtein distance of the given annotation vs actual annotation.
            sb.append(format("%n    * %s", sameTypes.get(i).getKey()));
        }
        int remaining = sameTypes.size() - MAX_MATCHING_TYPES_REPORTED;
        if (remaining > 0) {
            String plural = (remaining == 1) ? "" : "s";
            sb.append(format("%n    %d more binding%s with other annotations.", remaining, plural));
        }
    } else {
        // For now, do a simple substring search for possibilities. This can help spot
        // issues when there are generics being used (such as a wrapper class) and the
        // user has forgotten they need to bind based on the wrapper, not the underlying
        // class. In the future, consider doing a strict in-depth type search.
        // TODO: Look into a better way to prioritize suggestions. For example, possbily
        // use levenshtein distance of the type literal strings.
        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();
                formatSource(fmt, bindingMap.get(bindingKey).getSource());
                String match = String.format("%s bound%s", convert(bindingKey), fmt.toString());
                possibleMatches.add(match);
                // don't suggest any.
                if (possibleMatches.size() > MAX_RELATED_TYPES_REPORTED) {
                    // Early exit if we have found more than we need.
                    break;
                }
            }
        }
        if ((possibleMatches.size() > 0) && (possibleMatches.size() <= MAX_RELATED_TYPES_REPORTED)) {
            sb.append(format("%n  Did you mean?"));
            for (String possibleMatch : possibleMatches) {
                sb.append(format("%n    %s", possibleMatch));
            }
        }
    }
    // annotations on simple types. This is usually a bad idea.
    if (sameTypes.isEmpty() && possibleMatches.isEmpty() && key.getAnnotation() == null && COMMON_AMBIGUOUS_TYPES.contains(key.getTypeLiteral().getRawType())) {
        // We don't recommend using such simple types without annotations.
        sb.append(format("%nThe key seems very generic, did you forget an annotation?"));
    }
    return addMessage(sb.toString());
}
Also used : Binding(com.google.inject.Binding) ScopeBinding(com.google.inject.spi.ScopeBinding) TypeListenerBinding(com.google.inject.spi.TypeListenerBinding) TypeConverterBinding(com.google.inject.spi.TypeConverterBinding) Formatter(java.util.Formatter) ArrayList(java.util.ArrayList) InjectionPoint(com.google.inject.spi.InjectionPoint) Key(com.google.inject.Key)

Example 68 with Binding

use of com.google.inject.Binding in project guice by google.

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);
    List<MapResult<?, ?>> mapResults = Lists.newArrayList(results);
    // Make sure the entries returned from getEntries(elements) are correct.
    // Because getEntries() can return duplicates, make sure to continue searching, even
    // after we find one match.
    List<Map.Entry<?, Binding<?>>> entries = Lists.newArrayList(mapbinder.getEntries(elements));
    for (MapResult<?, ?> result : mapResults) {
        List<Map.Entry<?, Binding<?>>> foundEntries = Lists.newArrayList();
        for (Map.Entry<?, Binding<?>> entry : entries) {
            Object key = entry.getKey();
            Binding<?> value = entry.getValue();
            if (key.equals(result.k) && matches(value, result.v)) {
                assertTrue("mapBinder doesn't contain: " + entry.getValue(), mapbinder.containsElement(entry.getValue()));
                foundEntries.add(entry);
            }
        }
        assertTrue("Could not find entry: " + result + " in remaining entries: " + entries, !foundEntries.isEmpty());
        entries.removeAll(foundEntries);
    }
    assertTrue("Found all entries of: " + mapResults + ", but more were left over: " + entries, entries.isEmpty());
    assertEquals(keyType, mapbinder.getKeyTypeLiteral());
    assertEquals(valueType, mapbinder.getValueTypeLiteral());
    Key<?> mapOfProvider = mapKey.ofType(mapOfProviderOf(keyType, valueType));
    Key<?> mapOfJavaxProvider = mapKey.ofType(mapOfJavaxProviderOf(keyType, valueType));
    Key<?> mapOfSetOfProvider = mapKey.ofType(mapOfSetOfProviderOf(keyType, valueType));
    Key<?> mapOfSetOfJavaxProvider = mapKey.ofType(mapOfSetOfJavaxProviderOf(keyType, valueType));
    Key<?> mapOfCollectionOfProvider = mapKey.ofType(mapOfCollectionOfProviderOf(keyType, valueType));
    Key<?> mapOfCollectionOfJavaxProvider = mapKey.ofType(mapOfCollectionOfJavaxProviderOf(keyType, valueType));
    Key<?> mapOfSet = mapKey.ofType(mapOf(keyType, setOf(valueType)));
    Key<?> setOfEntry = mapKey.ofType(setOf(entryOfProviderOf(keyType, valueType)));
    Key<?> setOfJavaxEntry = mapKey.ofType(setOf(entryOfJavaxProviderOf(keyType, valueType)));
    Key<?> collectionOfProvidersOfEntryOfProvider = mapKey.ofType(collectionOfProvidersOf(entryOfProviderOf(keyType, valueType)));
    Key<?> collectionOfJavaxProvidersOfEntryOfProvider = mapKey.ofType(collectionOfJavaxProvidersOf(entryOfProviderOf(keyType, valueType)));
    boolean entrySetMatch = false;
    boolean entrySetJavaxMatch = false;
    boolean mapProviderMatch = false;
    boolean mapJavaxProviderMatch = false;
    boolean mapSetMatch = false;
    boolean mapSetProviderMatch = false;
    boolean mapSetJavaxProviderMatch = false;
    boolean mapCollectionProviderMatch = false;
    boolean mapCollectionJavaxProviderMatch = false;
    boolean collectionOfProvidersOfEntryOfProviderMatch = false;
    boolean collectionOfJavaxProvidersOfEntryOfProviderMatch = 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(mapOfJavaxProvider)) {
                matched = true;
                assertTrue(contains);
                mapJavaxProviderMatch = 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(mapOfSetOfJavaxProvider)) {
                matched = true;
                assertTrue(contains);
                mapSetJavaxProviderMatch = true;
            } else if (key.equals(mapOfCollectionOfProvider)) {
                matched = true;
                assertTrue(contains);
                mapCollectionProviderMatch = true;
            } else if (key.equals(mapOfCollectionOfJavaxProvider)) {
                matched = true;
                assertTrue(contains);
                mapCollectionJavaxProviderMatch = 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(setOfJavaxEntry)) {
                matched = true;
                assertTrue(contains);
                entrySetJavaxMatch = true;
            } else if (key.equals(collectionOfProvidersOfEntryOfProvider)) {
                matched = true;
                assertTrue(contains);
                collectionOfProvidersOfEntryOfProviderMatch = true;
            } else if (key.equals(collectionOfJavaxProvidersOfEntryOfProvider)) {
                matched = true;
                assertTrue(contains);
                collectionOfJavaxProvidersOfEntryOfProviderMatch = true;
            }
        }
        if (!matched && contains) {
            otherMatches.add(element);
        }
    }
    int otherMatchesSize = otherMatches.size();
    if (allowDuplicates) {
        // allow for 1 duplicate binding
        otherMatchesSize--;
    }
    // Multiply by 2 because each has a value, and Map.Entry
    int expectedSize = (mapResults.size() + duplicates) * 2;
    assertEquals("incorrect number of contains, leftover matches:\n" + Joiner.on("\n\t").join(otherMatches), expectedSize, otherMatchesSize);
    assertTrue(entrySetMatch);
    assertTrue(entrySetJavaxMatch);
    assertTrue(mapProviderMatch);
    assertTrue(mapJavaxProviderMatch);
    assertTrue(collectionOfProvidersOfEntryOfProviderMatch);
    assertTrue(collectionOfJavaxProvidersOfEntryOfProviderMatch);
    assertEquals(allowDuplicates, mapSetMatch);
    assertEquals(allowDuplicates, mapSetProviderMatch);
    assertEquals(allowDuplicates, mapSetJavaxProviderMatch);
    assertEquals(allowDuplicates, mapCollectionProviderMatch);
    assertEquals(allowDuplicates, mapCollectionJavaxProviderMatch);
    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 : MultibindingsTargetVisitor(com.google.inject.multibindings.MultibindingsTargetVisitor) DefaultBindingTargetVisitor(com.google.inject.spi.DefaultBindingTargetVisitor) Element(com.google.inject.spi.Element) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) ProviderMapEntry(com.google.inject.internal.RealMapBinder.ProviderMapEntry) MultibinderBinding(com.google.inject.multibindings.MultibinderBinding) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) IndexedBinding(com.google.inject.internal.Indexer.IndexedBinding) Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) MapBinderBinding(com.google.inject.multibindings.MapBinderBinding) OptionalBinderBinding(com.google.inject.multibindings.OptionalBinderBinding) ProviderKeyBinding(com.google.inject.spi.ProviderKeyBinding) LinkedKeyBinding(com.google.inject.spi.LinkedKeyBinding) IndexedBinding(com.google.inject.internal.Indexer.IndexedBinding) MapBinderBinding(com.google.inject.multibindings.MapBinderBinding) ProviderMapEntry(com.google.inject.internal.RealMapBinder.ProviderMapEntry) MultibinderBinding(com.google.inject.multibindings.MultibinderBinding) ProviderLookup(com.google.inject.spi.ProviderLookup) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Key(com.google.inject.Key)

Example 69 with Binding

use of com.google.inject.Binding in project guice by google.

the class SpiUtils method mapInjectorTest.

@SuppressWarnings("unchecked")
private static <T> void mapInjectorTest(Key<T> mapKey, TypeLiteral<?> keyType, TypeLiteral<?> valueType, Iterable<? extends Module> modules, boolean allowDuplicates, int expectedMapBindings, MapResult... results) {
    Injector injector = Guice.createInjector(modules);
    Visitor<T> visitor = new Visitor<T>();
    Binding<T> mapBinding = injector.getBinding(mapKey);
    MapBinderBinding<T> mapbinder = (MapBinderBinding<T>) mapBinding.acceptTargetVisitor(visitor);
    assertNotNull(mapbinder);
    assertEquals(keyType, mapbinder.getKeyTypeLiteral());
    assertEquals(valueType, mapbinder.getValueTypeLiteral());
    assertEquals(allowDuplicates, mapbinder.permitsDuplicates());
    List<Map.Entry<?, Binding<?>>> entries = Lists.newArrayList(mapbinder.getEntries());
    List<MapResult> mapResults = Lists.newArrayList(results);
    assertEquals("wrong entries, expected: " + mapResults + ", but was: " + entries, mapResults.size(), entries.size());
    for (MapResult result : mapResults) {
        Map.Entry<?, Binding<?>> found = null;
        for (Map.Entry<?, Binding<?>> entry : entries) {
            Object key = entry.getKey();
            Binding<?> value = entry.getValue();
            if (key.equals(result.k) && matches(value, result.v)) {
                found = entry;
                break;
            }
        }
        if (found == null) {
            fail("Could not find entry: " + result + " in remaining entries: " + entries);
        } else {
            assertTrue("mapBinder doesn't contain: " + found.getValue(), mapbinder.containsElement(found.getValue()));
            entries.remove(found);
        }
    }
    if (!entries.isEmpty()) {
        fail("Found all entries of: " + mapResults + ", but more were left over: " + entries);
    }
    Key<?> mapOfJavaxProvider = mapKey.ofType(mapOfJavaxProviderOf(keyType, valueType));
    Key<?> mapOfProvider = mapKey.ofType(mapOfProviderOf(keyType, valueType));
    Key<?> mapOfSetOfProvider = mapKey.ofType(mapOfSetOfProviderOf(keyType, valueType));
    Key<?> mapOfSetOfJavaxProvider = mapKey.ofType(mapOfSetOfJavaxProviderOf(keyType, valueType));
    Key<?> mapOfCollectionOfProvider = mapKey.ofType(mapOfCollectionOfProviderOf(keyType, valueType));
    Key<?> mapOfCollectionOfJavaxProvider = mapKey.ofType(mapOfCollectionOfJavaxProviderOf(keyType, valueType));
    Key<?> mapOfSet = mapKey.ofType(mapOf(keyType, setOf(valueType)));
    Key<?> setOfEntry = mapKey.ofType(setOf(entryOfProviderOf(keyType, valueType)));
    Key<?> setOfJavaxEntry = mapKey.ofType(setOf(entryOfJavaxProviderOf(keyType, valueType)));
    Key<?> collectionOfProvidersOfEntryOfProvider = mapKey.ofType(collectionOfProvidersOf(entryOfProviderOf(keyType, valueType)));
    Key<?> collectionOfJavaxProvidersOfEntryOfProvider = mapKey.ofType(collectionOfJavaxProvidersOf(entryOfProviderOf(keyType, valueType)));
    boolean entrySetMatch = false;
    boolean javaxEntrySetMatch = false;
    boolean mapJavaxProviderMatch = false;
    boolean mapProviderMatch = false;
    boolean mapSetMatch = false;
    boolean mapSetProviderMatch = false;
    boolean mapSetJavaxProviderMatch = false;
    boolean mapCollectionProviderMatch = false;
    boolean mapCollectionJavaxProviderMatch = false;
    boolean collectionOfProvidersOfEntryOfProviderMatch = false;
    boolean collectionOfJavaxProvidersOfEntryOfProviderMatch = false;
    List<Object> otherMapBindings = Lists.newArrayList();
    List<Binding> otherMatches = Lists.newArrayList();
    Multimap<Object, IndexedBinding> indexedEntries = MultimapBuilder.hashKeys().hashSetValues().build();
    Indexer indexer = new Indexer(injector);
    int duplicates = 0;
    for (Binding b : injector.getAllBindings().values()) {
        boolean contains = mapbinder.containsElement(b);
        Object visited = b.acceptTargetVisitor(visitor);
        if (visited instanceof MapBinderBinding) {
            if (visited.equals(mapbinder)) {
                assertTrue(contains);
            } else {
                otherMapBindings.add(visited);
            }
        } else if (b.getKey().equals(mapOfProvider)) {
            assertTrue(contains);
            mapProviderMatch = true;
        } else if (b.getKey().equals(mapOfJavaxProvider)) {
            assertTrue(contains);
            mapJavaxProviderMatch = true;
        } else if (b.getKey().equals(mapOfSet)) {
            assertTrue(contains);
            mapSetMatch = true;
        } else if (b.getKey().equals(mapOfSetOfProvider)) {
            assertTrue(contains);
            mapSetProviderMatch = true;
        } else if (b.getKey().equals(mapOfSetOfJavaxProvider)) {
            assertTrue(contains);
            mapSetJavaxProviderMatch = true;
        } else if (b.getKey().equals(mapOfCollectionOfProvider)) {
            assertTrue(contains);
            mapCollectionProviderMatch = true;
        } else if (b.getKey().equals(mapOfCollectionOfJavaxProvider)) {
            assertTrue(contains);
            mapCollectionJavaxProviderMatch = true;
        } else if (b.getKey().equals(setOfEntry)) {
            assertTrue(contains);
            entrySetMatch = true;
            // Validate that this binding is also a MultibinderBinding.
            assertTrue(b.acceptTargetVisitor(visitor) instanceof MultibinderBinding);
        } else if (b.getKey().equals(setOfJavaxEntry)) {
            assertTrue(contains);
            javaxEntrySetMatch = true;
        } else if (b.getKey().equals(collectionOfProvidersOfEntryOfProvider)) {
            assertTrue(contains);
            collectionOfProvidersOfEntryOfProviderMatch = true;
        } else if (b.getKey().equals(collectionOfJavaxProvidersOfEntryOfProvider)) {
            assertTrue(contains);
            collectionOfJavaxProvidersOfEntryOfProviderMatch = true;
        } else if (contains) {
            if (b instanceof ProviderInstanceBinding) {
                ProviderInstanceBinding<?> pib = (ProviderInstanceBinding<?>) b;
                if (pib.getUserSuppliedProvider() instanceof ProviderMapEntry) {
                    // weird casting required to workaround compilation issues with jdk6
                    ProviderMapEntry<?, ?> pme = (ProviderMapEntry<?, ?>) (Provider) pib.getUserSuppliedProvider();
                    Binding<?> valueBinding = injector.getBinding(pme.getValueKey());
                    if (indexer.isIndexable(valueBinding) && !indexedEntries.put(pme.getKey(), valueBinding.acceptTargetVisitor(indexer))) {
                        duplicates++;
                    }
                }
            }
            otherMatches.add(b);
        }
    }
    int sizeOfOther = otherMatches.size();
    if (allowDuplicates) {
        // account for 1 duplicate binding
        sizeOfOther--;
    }
    // Multiply by two because each has a value and Map.Entry.
    int expectedSize = 2 * (mapResults.size() + duplicates);
    assertEquals("Incorrect other matches:\n\t" + Joiner.on("\n\t").join(otherMatches), expectedSize, sizeOfOther);
    assertTrue(entrySetMatch);
    assertTrue(javaxEntrySetMatch);
    assertTrue(mapProviderMatch);
    assertTrue(mapJavaxProviderMatch);
    assertTrue(collectionOfProvidersOfEntryOfProviderMatch);
    assertTrue(collectionOfJavaxProvidersOfEntryOfProviderMatch);
    assertEquals(allowDuplicates, mapSetMatch);
    assertEquals(allowDuplicates, mapSetProviderMatch);
    assertEquals(allowDuplicates, mapSetJavaxProviderMatch);
    assertEquals(allowDuplicates, mapCollectionJavaxProviderMatch);
    assertEquals(allowDuplicates, mapCollectionProviderMatch);
    assertEquals("other MapBindings found: " + otherMapBindings, expectedMapBindings, otherMapBindings.size());
}
Also used : MultibindingsTargetVisitor(com.google.inject.multibindings.MultibindingsTargetVisitor) DefaultBindingTargetVisitor(com.google.inject.spi.DefaultBindingTargetVisitor) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) ProviderMapEntry(com.google.inject.internal.RealMapBinder.ProviderMapEntry) Injector(com.google.inject.Injector) MultibinderBinding(com.google.inject.multibindings.MultibinderBinding) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) IndexedBinding(com.google.inject.internal.Indexer.IndexedBinding) Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) MapBinderBinding(com.google.inject.multibindings.MapBinderBinding) OptionalBinderBinding(com.google.inject.multibindings.OptionalBinderBinding) ProviderKeyBinding(com.google.inject.spi.ProviderKeyBinding) LinkedKeyBinding(com.google.inject.spi.LinkedKeyBinding) IndexedBinding(com.google.inject.internal.Indexer.IndexedBinding) MapBinderBinding(com.google.inject.multibindings.MapBinderBinding) ProviderMapEntry(com.google.inject.internal.RealMapBinder.ProviderMapEntry) MultibinderBinding(com.google.inject.multibindings.MultibinderBinding) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 70 with Binding

use of com.google.inject.Binding in project guice by google.

the class ElementsTest method testNewPrivateBinder.

public void testNewPrivateBinder() {
    final Key<Collection> collection = Key.get(Collection.class, SampleAnnotation.class);
    final Key<ArrayList> arrayList = Key.get(ArrayList.class);
    final ImmutableSet<Key<?>> collections = ImmutableSet.<Key<?>>of(arrayList, collection);
    final Key<?> a = Key.get(String.class, Names.named("a"));
    final Key<?> b = Key.get(String.class, Names.named("b"));
    final ImmutableSet<Key<?>> ab = ImmutableSet.of(a, b);
    checkModule(new AbstractModule() {

        @Override
        protected void configure() {
            PrivateBinder one = binder().newPrivateBinder();
            one.expose(ArrayList.class);
            one.expose(Collection.class).annotatedWith(SampleAnnotation.class);
            one.bind(List.class).to(ArrayList.class);
            PrivateBinder two = binder().withSource("1 FooBar").newPrivateBinder().withSource("2 FooBar");
            two.expose(String.class).annotatedWith(Names.named("a"));
            two.expose(b);
            two.bind(List.class).to(ArrayList.class);
        }
    }, new FailingElementVisitor() {

        @Override
        public Void visit(PrivateElements one) {
            assertEquals(collections, one.getExposedKeys());
            checkElements(one.getElements(), new FailingElementVisitor() {

                @Override
                public <T> Void visit(Binding<T> binding) {
                    assertEquals(Key.get(List.class), binding.getKey());
                    return null;
                }
            });
            return null;
        }
    }, new ExternalFailureVisitor() {

        @Override
        public Void visit(PrivateElements two) {
            assertEquals(ab, two.getExposedKeys());
            assertEquals("1 FooBar", two.getSource().toString());
            checkElements(two.getElements(), new ExternalFailureVisitor() {

                @Override
                public <T> Void visit(Binding<T> binding) {
                    assertEquals("2 FooBar", binding.getSource().toString());
                    assertEquals(Key.get(List.class), binding.getKey());
                    return null;
                }
            });
            return null;
        }
    });
}
Also used : Binding(com.google.inject.Binding) ArrayList(java.util.ArrayList) AbstractModule(com.google.inject.AbstractModule) PrivateBinder(com.google.inject.PrivateBinder) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) Key(com.google.inject.Key)

Aggregations

Binding (com.google.inject.Binding)92 Injector (com.google.inject.Injector)58 Key (com.google.inject.Key)36 AbstractModule (com.google.inject.AbstractModule)33 InstanceBinding (com.google.inject.spi.InstanceBinding)23 Map (java.util.Map)21 HttpServletRequest (javax.servlet.http.HttpServletRequest)21 Module (com.google.inject.Module)18 Element (com.google.inject.spi.Element)18 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)17 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)16 HttpServlet (javax.servlet.http.HttpServlet)14 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 DefaultBindingTargetVisitor (com.google.inject.spi.DefaultBindingTargetVisitor)12 ProviderKeyBinding (com.google.inject.spi.ProviderKeyBinding)12 ServletContext (javax.servlet.ServletContext)12 ImmutableMap (com.google.common.collect.ImmutableMap)11 HashMap (java.util.HashMap)11 TypeLiteral (com.google.inject.TypeLiteral)10 MapBinderBinding (com.google.inject.multibindings.MapBinderBinding)10