Search in sources :

Example 21 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class CheckedProviderTest method testProvisionExceptionOnDependenciesOfCxtor.

public void testProvisionExceptionOnDependenciesOfCxtor() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            ThrowingProviderBinder.create(binder()).bind(RemoteProvider.class, Foo.class).providing(ProvisionExceptionFoo.class);
            bindScope(BadScope.class, new Scope() {

                @Override
                public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
                    return new Provider<T>() {

                        @Override
                        public T get() {
                            throw new OutOfScopeException("failure");
                        }
                    };
                }
            });
        }
    });
    try {
        injector.getInstance(Key.get(remoteProviderOfFoo)).get();
        fail();
    } catch (ProvisionException pe) {
        assertEquals(2, pe.getErrorMessages().size());
        List<Message> messages = Lists.newArrayList(pe.getErrorMessages());
        assertEquals("Error in custom provider, com.google.inject.OutOfScopeException: failure", messages.get(0).getMessage());
        assertEquals("Error in custom provider, com.google.inject.OutOfScopeException: failure", messages.get(1).getMessage());
    }
}
Also used : ProvisionException(com.google.inject.ProvisionException) Scope(com.google.inject.Scope) Injector(com.google.inject.Injector) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) OutOfScopeException(com.google.inject.OutOfScopeException) Key(com.google.inject.Key) AbstractModule(com.google.inject.AbstractModule) Provider(com.google.inject.Provider)

Example 22 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class ServletScopesTest method indexBindings.

private 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 : Binding(com.google.inject.Binding) 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) Key(com.google.inject.Key)

Example 23 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class TransferRequestIntegrationTest method testTransferNonHttpRequest_concurrentUseBlocks.

public void testTransferNonHttpRequest_concurrentUseBlocks() throws Exception {
    Callable<Boolean> callable = new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            try {
                Future<Boolean> future = executor.submit(ServletScopes.transferRequest(FALSE_CALLABLE));
                try {
                    return future.get(100, TimeUnit.MILLISECONDS);
                } catch (TimeoutException e) {
                    return true;
                }
            } finally {
                executor.shutdownNow();
            }
        }
    };
    ImmutableMap<Key<?>, Object> seedMap = ImmutableMap.of();
    assertTrue(ServletScopes.scopeRequest(callable, seedMap).call());
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) Callable(java.util.concurrent.Callable) Key(com.google.inject.Key) TimeoutException(java.util.concurrent.TimeoutException)

Example 24 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class BoundFieldModuleTest method testBindingWithGenerics.

public void testBindingWithGenerics() {
    final List<Integer> testIntList = Arrays.asList(new Integer[] { 1, 2, 3 });
    final List<Boolean> testBoolList = Arrays.asList(new Boolean[] { true, true, false });
    Object instance = new Object() {

        @Bind
        private List<Integer> anIntList = testIntList;

        @Bind
        private List<Boolean> aBoolList = testBoolList;
    };
    BoundFieldModule module = BoundFieldModule.of(instance);
    Injector injector = Guice.createInjector(module);
    assertEquals(testIntList, injector.getInstance(new Key<List<Integer>>() {
    }));
    assertEquals(testBoolList, injector.getInstance(new Key<List<Boolean>>() {
    }));
}
Also used : Injector(com.google.inject.Injector) List(java.util.List) Key(com.google.inject.Key)

Example 25 with Key

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

the class SpiUtils method setInjectorTest.

@SuppressWarnings("unchecked")
private static <T> void setInjectorTest(Key<Set<T>> setKey, TypeLiteral<?> elementType, Iterable<? extends Module> modules, boolean allowDuplicates, int otherMultibindings, BindResult... results) {
    Key<?> collectionOfProvidersKey = setKey.ofType(collectionOfProvidersOf(elementType));
    Key<?> collectionOfJavaxProvidersKey = setKey.ofType(collectionOfJavaxProvidersOf(elementType));
    Injector injector = Guice.createInjector(modules);
    Visitor<Set<T>> visitor = new Visitor<Set<T>>();
    Binding<Set<T>> binding = injector.getBinding(setKey);
    MultibinderBinding<Set<T>> multibinder = (MultibinderBinding<Set<T>>) binding.acceptTargetVisitor(visitor);
    assertNotNull(multibinder);
    assertEquals(elementType, multibinder.getElementTypeLiteral());
    assertEquals(allowDuplicates, multibinder.permitsDuplicates());
    List<Binding<?>> elements = Lists.newArrayList(multibinder.getElements());
    List<BindResult> bindResults = Lists.newArrayList(results);
    assertEquals("wrong bind elements, expected: " + bindResults + ", but was: " + multibinder.getElements(), bindResults.size(), elements.size());
    for (BindResult result : bindResults) {
        Binding found = null;
        for (Binding item : elements) {
            if (matches(item, result)) {
                found = item;
                break;
            }
        }
        if (found == null) {
            fail("Could not find element: " + result + " in remaining elements: " + elements);
        } else {
            elements.remove(found);
        }
    }
    if (!elements.isEmpty()) {
        fail("Found all elements of: " + bindResults + ", but more were left over: " + elements);
    }
    Set<Binding> setOfElements = new HashSet<Binding>(multibinder.getElements());
    Set<IndexedBinding> setOfIndexed = Sets.newHashSet();
    Indexer indexer = new Indexer(injector);
    for (Binding<?> oneBinding : setOfElements) {
        setOfIndexed.add(oneBinding.acceptTargetVisitor(indexer));
    }
    List<Object> otherMultibinders = Lists.newArrayList();
    List<Binding> otherContains = Lists.newArrayList();
    boolean collectionOfProvidersMatch = false;
    boolean collectionOfJavaxProvidersMatch = false;
    for (Binding b : injector.getAllBindings().values()) {
        boolean contains = multibinder.containsElement(b);
        Key key = b.getKey();
        Object visited = b.acceptTargetVisitor(visitor);
        if (visited != null) {
            if (visited.equals(multibinder)) {
                assertTrue(contains);
            } else {
                otherMultibinders.add(visited);
            }
        } else if (setOfElements.contains(b)) {
            assertTrue(contains);
        } else if (key.equals(collectionOfProvidersKey)) {
            assertTrue(contains);
            collectionOfProvidersMatch = true;
        } else if (key.equals(collectionOfJavaxProvidersKey)) {
            assertTrue(contains);
            collectionOfJavaxProvidersMatch = true;
        } else if (contains) {
            if (!indexer.isIndexable(b) || !setOfIndexed.contains(b.acceptTargetVisitor(indexer))) {
                otherContains.add(b);
            }
        }
    }
    assertTrue(collectionOfProvidersMatch);
    assertTrue(collectionOfJavaxProvidersMatch);
    if (allowDuplicates) {
        assertEquals("contained more than it should: " + otherContains, 1, otherContains.size());
    } else {
        assertTrue("contained more than it should: " + otherContains, otherContains.isEmpty());
    }
    assertEquals("other multibindings found: " + otherMultibinders, otherMultibindings, otherMultibinders.size());
}
Also used : 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) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) MultibindingsTargetVisitor(com.google.inject.multibindings.MultibindingsTargetVisitor) DefaultBindingTargetVisitor(com.google.inject.spi.DefaultBindingTargetVisitor) IndexedBinding(com.google.inject.internal.Indexer.IndexedBinding) MultibinderBinding(com.google.inject.multibindings.MultibinderBinding) Injector(com.google.inject.Injector) Key(com.google.inject.Key) HashSet(java.util.HashSet)

Aggregations

Key (com.google.inject.Key)106 AbstractModule (com.google.inject.AbstractModule)55 Injector (com.google.inject.Injector)52 Binding (com.google.inject.Binding)36 Module (com.google.inject.Module)20 Provider (com.google.inject.Provider)18 Element (com.google.inject.spi.Element)16 Map (java.util.Map)16 HasDependencies (com.google.inject.spi.HasDependencies)14 InstanceBinding (com.google.inject.spi.InstanceBinding)13 List (java.util.List)13 TypeLiteral (com.google.inject.TypeLiteral)12 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)10 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)9 PrivateModule (com.google.inject.PrivateModule)8 DefaultBindingTargetVisitor (com.google.inject.spi.DefaultBindingTargetVisitor)8 Dependency (com.google.inject.spi.Dependency)8 ProviderKeyBinding (com.google.inject.spi.ProviderKeyBinding)8 ImmutableList (com.google.common.collect.ImmutableList)7 InjectionPoint (com.google.inject.spi.InjectionPoint)7