Search in sources :

Example 16 with Element

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

the class AbstractProcessor method process.

public void process(InjectorImpl injector, List<Element> elements) {
    Errors errorsAnyElement = this.errors;
    this.injector = injector;
    try {
        for (Iterator<Element> i = elements.iterator(); i.hasNext(); ) {
            Element element = i.next();
            this.errors = errorsAnyElement.withSource(element.getSource());
            Boolean allDone = element.acceptVisitor(this);
            if (allDone) {
                i.remove();
            }
        }
    } finally {
        this.errors = errorsAnyElement;
        this.injector = null;
    }
}
Also used : Element(com.google.inject.spi.Element)

Example 17 with Element

use of com.google.inject.spi.Element 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 18 with Element

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

the class ScopesTest method indexBindings.

ImmutableMap<Key<?>, Binding<?>> indexBindings(Iterable<Element> elements) {
    ImmutableMap.Builder<Key<?>, Binding<?>> builder = ImmutableMap.builder();
    for (Element element : elements) {
        if (element instanceof Binding) {
            Binding<?> binding = (Binding<?>) element;
            builder.put(binding.getKey(), binding);
        } else if (element instanceof PrivateElements) {
            PrivateElements privateElements = (PrivateElements) element;
            Map<Key<?>, Binding<?>> privateBindings = indexBindings(privateElements.getElements());
            for (Key<?> exposed : privateElements.getExposedKeys()) {
                builder.put(exposed, privateBindings.get(exposed));
            }
        }
    }
    return builder.build();
}
Also used : PrivateElements(com.google.inject.spi.PrivateElements) Element(com.google.inject.spi.Element) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 19 with Element

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

the class Modules method extractScanners.

private static Module extractScanners(Iterable<Element> elements) {
    final List<ModuleAnnotatedMethodScannerBinding> scanners = Lists.newArrayList();
    ElementVisitor<Void> visitor = new DefaultElementVisitor<Void>() {

        @Override
        public Void visit(ModuleAnnotatedMethodScannerBinding binding) {
            scanners.add(binding);
            return null;
        }
    };
    for (Element element : elements) {
        element.acceptVisitor(visitor);
    }
    return new AbstractModule() {

        @Override
        protected void configure() {
            for (ModuleAnnotatedMethodScannerBinding scanner : scanners) {
                scanner.applyTo(binder());
            }
        }
    };
}
Also used : DefaultElementVisitor(com.google.inject.spi.DefaultElementVisitor) Element(com.google.inject.spi.Element) ModuleAnnotatedMethodScannerBinding(com.google.inject.spi.ModuleAnnotatedMethodScannerBinding) AbstractModule(com.google.inject.AbstractModule)

Example 20 with Element

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

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)

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