Search in sources :

Example 81 with Binding

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

the class FilterDefinitionTest method testGetFilterIfMatching.

public void testGetFilterIfMatching() throws ServletException {
    String pattern = "/*";
    final FilterDefinition filterDef = new FilterDefinition(pattern, Key.get(Filter.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
    HttpServletRequest servletRequest = createMock(HttpServletRequest.class);
    ServletContext servletContext = createMock(ServletContext.class);
    Injector injector = createMock(Injector.class);
    Binding binding = createMock(Binding.class);
    final MockFilter mockFilter = new MockFilter() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        //suppress rest of chain...
        }
    };
    expect(injector.getBinding(Key.get(Filter.class))).andReturn(binding);
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getInstance(Key.get(Filter.class))).andReturn(mockFilter).anyTimes();
    expect(servletRequest.getContextPath()).andReturn("/a_context_path");
    expect(servletRequest.getRequestURI()).andReturn("/a_context_path/test.html");
    replay(servletRequest, binding, injector);
    filterDef.init(servletContext, injector, Sets.<Filter>newIdentityHashSet());
    Filter filter = filterDef.getFilterIfMatching(servletRequest);
    assertSame(filter, mockFilter);
    verify(servletRequest, binding, injector);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Binding(com.google.inject.Binding) ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletResponse(javax.servlet.ServletResponse) Filter(javax.servlet.Filter) Injector(com.google.inject.Injector) FilterChain(javax.servlet.FilterChain) ServletContext(javax.servlet.ServletContext)

Example 82 with Binding

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

the class FilterDefinitionTest method testGetFilterIfMatchingNotMatching.

public void testGetFilterIfMatchingNotMatching() throws ServletException {
    String pattern = "/*";
    final FilterDefinition filterDef = new FilterDefinition(pattern, Key.get(Filter.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
    HttpServletRequest servletRequest = createMock(HttpServletRequest.class);
    ServletContext servletContext = createMock(ServletContext.class);
    Injector injector = createMock(Injector.class);
    Binding binding = createMock(Binding.class);
    final MockFilter mockFilter = new MockFilter() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        //suppress rest of chain...
        }
    };
    expect(injector.getBinding(Key.get(Filter.class))).andReturn(binding);
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getInstance(Key.get(Filter.class))).andReturn(mockFilter).anyTimes();
    expect(servletRequest.getContextPath()).andReturn("/a_context_path");
    expect(servletRequest.getRequestURI()).andReturn("/test.html");
    replay(servletRequest, binding, injector);
    filterDef.init(servletContext, injector, Sets.<Filter>newIdentityHashSet());
    Filter filter = filterDef.getFilterIfMatching(servletRequest);
    assertNull(filter);
    verify(servletRequest, binding, injector);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Binding(com.google.inject.Binding) ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletResponse(javax.servlet.ServletResponse) Filter(javax.servlet.Filter) Injector(com.google.inject.Injector) FilterChain(javax.servlet.FilterChain) ServletContext(javax.servlet.ServletContext)

Example 83 with Binding

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

the class MapBinderTest method testTwoMapBindersAreDistinct.

public void testTwoMapBindersAreDistinct() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            MapBinder.newMapBinder(binder(), String.class, String.class).addBinding("A").toInstance("a");
            MapBinder.newMapBinder(binder(), Integer.class, String.class).addBinding(1).toInstance("b");
        }
    });
    Collector collector = new Collector();
    Binding<Map<String, String>> map1 = injector.getBinding(Key.get(mapOfString));
    map1.acceptTargetVisitor(collector);
    assertNotNull(collector.mapbinding);
    MapBinderBinding<?> map1Binding = collector.mapbinding;
    Binding<Map<Integer, String>> map2 = injector.getBinding(Key.get(mapOfIntString));
    map2.acceptTargetVisitor(collector);
    assertNotNull(collector.mapbinding);
    MapBinderBinding<?> map2Binding = collector.mapbinding;
    List<Binding<String>> bindings = injector.findBindingsByType(stringType);
    assertEquals("should have two elements: " + bindings, 2, bindings.size());
    Binding<String> a = bindings.get(0);
    Binding<String> b = bindings.get(1);
    assertEquals("a", ((InstanceBinding<String>) a).getInstance());
    assertEquals("b", ((InstanceBinding<String>) b).getInstance());
    // Make sure the correct elements belong to their own sets.
    assertTrue(map1Binding.containsElement(a));
    assertFalse(map1Binding.containsElement(b));
    assertFalse(map2Binding.containsElement(a));
    assertTrue(map2Binding.containsElement(b));
}
Also used : Binding(com.google.inject.Binding) InstanceBinding(com.google.inject.spi.InstanceBinding) AbstractModule(com.google.inject.AbstractModule) Injector(com.google.inject.Injector) Map(java.util.Map) HashMap(java.util.HashMap)

Example 84 with Binding

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

the class SpiUtils method optionalInjectorTest.

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> void optionalInjectorTest(Key<T> keyType, Iterable<? extends Module> modules, int expectedOtherOptionalBindings, BindResult<?> expectedDefault, BindResult<?> expectedActual, BindResult<?> expectedUserLinkedActual) {
    if (expectedUserLinkedActual != null) {
        assertNull("cannot have actual if expecting user binding", expectedActual);
        assertNull("cannot have default if expecting user binding", expectedDefault);
    }
    Key<Optional<T>> optionalKey = keyType.ofType(OptionalBinder.optionalOf(keyType.getTypeLiteral()));
    Key<?> javaOptionalKey = HAS_JAVA_OPTIONAL ? keyType.ofType(OptionalBinder.javaOptionalOf(keyType.getTypeLiteral())) : null;
    Injector injector = Guice.createInjector(modules);
    Binding<Optional<T>> optionalBinding = injector.getBinding(optionalKey);
    Visitor visitor = new Visitor();
    OptionalBinderBinding<Optional<T>> optionalBinder = (OptionalBinderBinding<Optional<T>>) optionalBinding.acceptTargetVisitor(visitor);
    assertNotNull(optionalBinder);
    assertEquals(optionalKey, optionalBinder.getKey());
    Binding<?> javaOptionalBinding = null;
    OptionalBinderBinding<?> javaOptionalBinder = null;
    if (HAS_JAVA_OPTIONAL) {
        javaOptionalBinding = injector.getBinding(javaOptionalKey);
        javaOptionalBinder = (OptionalBinderBinding<?>) javaOptionalBinding.acceptTargetVisitor(visitor);
        assertNotNull(javaOptionalBinder);
        assertEquals(javaOptionalKey, javaOptionalBinder.getKey());
    }
    if (expectedDefault == null) {
        assertNull("did not expect a default binding", optionalBinder.getDefaultBinding());
        if (HAS_JAVA_OPTIONAL) {
            assertNull("did not expect a default binding", javaOptionalBinder.getDefaultBinding());
        }
    } else {
        assertTrue("expectedDefault: " + expectedDefault + ", actualDefault: " + optionalBinder.getDefaultBinding(), matches(optionalBinder.getDefaultBinding(), expectedDefault));
        if (HAS_JAVA_OPTIONAL) {
            assertTrue("expectedDefault: " + expectedDefault + ", actualDefault: " + javaOptionalBinder.getDefaultBinding(), matches(javaOptionalBinder.getDefaultBinding(), expectedDefault));
        }
    }
    if (expectedActual == null && expectedUserLinkedActual == null) {
        assertNull(optionalBinder.getActualBinding());
        if (HAS_JAVA_OPTIONAL) {
            assertNull(javaOptionalBinder.getActualBinding());
        }
    } else if (expectedActual != null) {
        assertTrue("expectedActual: " + expectedActual + ", actualActual: " + optionalBinder.getActualBinding(), matches(optionalBinder.getActualBinding(), expectedActual));
        if (HAS_JAVA_OPTIONAL) {
            assertTrue("expectedActual: " + expectedActual + ", actualActual: " + javaOptionalBinder.getActualBinding(), matches(javaOptionalBinder.getActualBinding(), expectedActual));
        }
    } else if (expectedUserLinkedActual != null) {
        assertTrue("expectedUserLinkedActual: " + expectedUserLinkedActual + ", actualActual: " + optionalBinder.getActualBinding(), matches(optionalBinder.getActualBinding(), expectedUserLinkedActual));
        if (HAS_JAVA_OPTIONAL) {
            assertTrue("expectedUserLinkedActual: " + expectedUserLinkedActual + ", actualActual: " + javaOptionalBinder.getActualBinding(), matches(javaOptionalBinder.getActualBinding(), expectedUserLinkedActual));
        }
    }
    Key<Optional<javax.inject.Provider<T>>> optionalJavaxProviderKey = keyType.ofType(optionalOfJavaxProvider(keyType.getTypeLiteral()));
    Key<?> javaOptionalJavaxProviderKey = HAS_JAVA_OPTIONAL ? keyType.ofType(javaOptionalOfJavaxProvider(keyType.getTypeLiteral())) : null;
    Key<Optional<Provider<T>>> optionalProviderKey = keyType.ofType(optionalOfProvider(keyType.getTypeLiteral()));
    Key<?> javaOptionalProviderKey = HAS_JAVA_OPTIONAL ? keyType.ofType(javaOptionalOfProvider(keyType.getTypeLiteral())) : null;
    boolean keyMatch = false;
    boolean optionalKeyMatch = false;
    boolean javaOptionalKeyMatch = false;
    boolean optionalJavaxProviderKeyMatch = false;
    boolean javaOptionalJavaxProviderKeyMatch = false;
    boolean optionalProviderKeyMatch = false;
    boolean javaOptionalProviderKeyMatch = false;
    boolean defaultMatch = false;
    boolean actualMatch = false;
    List<Object> otherOptionalBindings = Lists.newArrayList();
    List<Binding> otherMatches = Lists.newArrayList();
    for (Binding b : injector.getAllBindings().values()) {
        boolean contains = optionalBinder.containsElement(b);
        if (HAS_JAVA_OPTIONAL) {
            assertEquals(contains, javaOptionalBinder.containsElement(b));
        }
        Object visited = b.acceptTargetVisitor(visitor);
        if (visited instanceof OptionalBinderBinding) {
            if (visited.equals(optionalBinder)) {
                assertTrue(contains);
            } else if (HAS_JAVA_OPTIONAL && visited.equals(javaOptionalBinder)) {
                assertTrue(contains);
            } else {
                otherOptionalBindings.add(visited);
            }
        }
        if (b.getKey().equals(keyType)) {
            // keyType might match because a user bound it
            // (which is possible in a purely absent OptionalBinder)
            assertEquals(expectedDefault != null || expectedActual != null, contains);
            if (contains) {
                keyMatch = true;
            }
        } else if (b.getKey().equals(optionalKey)) {
            assertTrue(contains);
            optionalKeyMatch = true;
        } else if (b.getKey().equals(javaOptionalKey)) {
            assertTrue(contains);
            javaOptionalKeyMatch = true;
        } else if (b.getKey().equals(optionalJavaxProviderKey)) {
            assertTrue(contains);
            optionalJavaxProviderKeyMatch = true;
        } else if (b.getKey().equals(javaOptionalJavaxProviderKey)) {
            assertTrue(contains);
            javaOptionalJavaxProviderKeyMatch = true;
        } else if (b.getKey().equals(optionalProviderKey)) {
            assertTrue(contains);
            optionalProviderKeyMatch = true;
        } else if (b.getKey().equals(javaOptionalProviderKey)) {
            assertTrue(contains);
            javaOptionalProviderKeyMatch = true;
        } else if (expectedDefault != null && matches(b, expectedDefault)) {
            assertTrue(contains);
            defaultMatch = true;
        } else if (expectedActual != null && matches(b, expectedActual)) {
            assertTrue(contains);
            actualMatch = true;
        } else if (contains) {
            otherMatches.add(b);
        }
    }
    assertEquals(otherMatches.toString(), 0, otherMatches.size());
    // only expect a keymatch if either default or actual are set
    assertEquals(expectedDefault != null || expectedActual != null, keyMatch);
    assertTrue(optionalKeyMatch);
    assertTrue(optionalJavaxProviderKeyMatch);
    assertTrue(optionalProviderKeyMatch);
    assertEquals(HAS_JAVA_OPTIONAL, javaOptionalKeyMatch);
    assertEquals(HAS_JAVA_OPTIONAL, javaOptionalJavaxProviderKeyMatch);
    assertEquals(HAS_JAVA_OPTIONAL, javaOptionalProviderKeyMatch);
    assertEquals(expectedDefault != null, defaultMatch);
    assertEquals(expectedActual != null, actualMatch);
    assertEquals("other OptionalBindings found: " + otherOptionalBindings, expectedOtherOptionalBindings, otherOptionalBindings.size());
}
Also used : 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) Optional(com.google.common.base.Optional) DefaultBindingTargetVisitor(com.google.inject.spi.DefaultBindingTargetVisitor) Injector(com.google.inject.Injector)

Example 85 with Binding

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

the class SpiUtils method setInjectorTest.

@SuppressWarnings("unchecked")
private static <T> void setInjectorTest(Key<Set<T>> setKey, Key<Collection<Provider<T>>> collectionOfProvidersKey, TypeLiteral<?> elementType, Iterable<? extends Module> modules, boolean allowDuplicates, int otherMultibindings, BindResult... results) {
    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;
    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 (contains) {
            if (!indexer.isIndexable(b) || !setOfIndexed.contains(b.acceptTargetVisitor(indexer))) {
                otherContains.add(b);
            }
        }
    }
    assertTrue(collectionOfProvidersMatch);
    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 : 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) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) DefaultBindingTargetVisitor(com.google.inject.spi.DefaultBindingTargetVisitor) IndexedBinding(com.google.inject.multibindings.Indexer.IndexedBinding) Injector(com.google.inject.Injector) Key(com.google.inject.Key) HashSet(java.util.HashSet)

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