Search in sources :

Example 86 with Binding

use of com.google.inject.Binding 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 87 with Binding

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

the class ServletDefinitionPathsTest method pathInfoWithRegexMatching.

public final void pathInfoWithRegexMatching(final String requestUri, final String contextPath, String mapping, final String expectedPathInfo, final String servletPath) throws IOException, ServletException {
    Injector injector = createMock(Injector.class);
    Binding binding = createMock(Binding.class);
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
    final boolean[] run = new boolean[1];
    //get an instance of this servlet
    expect(injector.getInstance(Key.get(HttpServlet.class))).andReturn(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest servletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
            final String path = servletRequest.getPathInfo();
            if (null == expectedPathInfo) {
                assertNull(String.format("expected [%s] but was [%s]", expectedPathInfo, path), path);
            } else {
                assertEquals(String.format("expected [%s] but was [%s]", expectedPathInfo, path), expectedPathInfo, path);
            }
            //assert memoizer
            //noinspection StringEquality
            assertSame("memo field did not work", path, servletRequest.getPathInfo());
            run[0] = true;
        }
    });
    expect(request.getRequestURI()).andReturn(requestUri);
    expect(request.getServletPath()).andReturn(servletPath).anyTimes();
    expect(request.getContextPath()).andReturn(contextPath);
    expect(request.getAttribute(REQUEST_DISPATCHER_REQUEST)).andReturn(null);
    replay(injector, binding, request);
    ServletDefinition servletDefinition = new ServletDefinition(mapping, Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.REGEX, mapping), new HashMap<String, String>(), null);
    servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
    servletDefinition.doService(request, response);
    assertTrue("Servlet did not run!", run[0]);
    verify(injector, binding, request);
}
Also used : Binding(com.google.inject.Binding) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Injector(com.google.inject.Injector) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException)

Example 88 with Binding

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

the class ServletDefinitionTest method testServletInitAndConfig.

public final void testServletInitAndConfig() throws ServletException {
    Injector injector = createMock(Injector.class);
    Binding binding = createMock(Binding.class);
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
    final HttpServlet mockServlet = new HttpServlet() {
    };
    expect(injector.getInstance(Key.get(HttpServlet.class))).andReturn(mockServlet).anyTimes();
    replay(injector, binding);
    //some init params
    //noinspection SSBasedInspection
    final Map<String, String> initParams = new ImmutableMap.Builder<String, String>().put("ahsd", "asdas24dok").put("ahssd", "asdasd124ok").build();
    String pattern = "/*";
    final ServletDefinition servletDefinition = new ServletDefinition(pattern, Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.SERVLET, pattern), initParams, null);
    ServletContext servletContext = createMock(ServletContext.class);
    final String contextName = "thing__!@@44__SRV" + getClass();
    expect(servletContext.getServletContextName()).andReturn(contextName);
    replay(servletContext);
    servletDefinition.init(servletContext, injector, Sets.<HttpServlet>newIdentityHashSet());
    assertNotNull(mockServlet.getServletContext());
    assertEquals(contextName, mockServlet.getServletContext().getServletContextName());
    assertEquals(Key.get(HttpServlet.class).toString(), mockServlet.getServletName());
    final ServletConfig servletConfig = mockServlet.getServletConfig();
    final Enumeration names = servletConfig.getInitParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        assertTrue(initParams.containsKey(name));
        assertEquals(initParams.get(name), servletConfig.getInitParameter(name));
    }
    verify(injector, binding, servletContext);
}
Also used : Binding(com.google.inject.Binding) Enumeration(java.util.Enumeration) Injector(com.google.inject.Injector) HttpServlet(javax.servlet.http.HttpServlet) ServletConfig(javax.servlet.ServletConfig) ServletContext(javax.servlet.ServletContext) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 89 with Binding

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

the class ServletPipelineRequestDispatcherTest method testIncludeManagedServlet.

public final void testIncludeManagedServlet() throws IOException, ServletException {
    String pattern = "blah.html";
    final ServletDefinition servletDefinition = new ServletDefinition(pattern, Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
    final Injector injector = createMock(Injector.class);
    final Binding binding = createMock(Binding.class);
    final HttpServletRequest requestMock = createMock(HttpServletRequest.class);
    expect(requestMock.getAttribute(A_KEY)).andReturn(A_VALUE);
    requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true);
    requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST);
    final boolean[] run = new boolean[1];
    final HttpServlet mockServlet = new HttpServlet() {

        protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
            run[0] = true;
            final Object o = request.getAttribute(A_KEY);
            assertEquals("Wrong attrib returned - " + o, A_VALUE, o);
        }
    };
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
    expect(injector.getInstance(HTTP_SERLVET_KEY)).andReturn(mockServlet);
    final Key<ServletDefinition> servetDefsKey = Key.get(TypeLiteral.get(ServletDefinition.class));
    Binding<ServletDefinition> mockBinding = createMock(Binding.class);
    expect(injector.findBindingsByType(eq(servetDefsKey.getTypeLiteral()))).andReturn(ImmutableList.<Binding<ServletDefinition>>of(mockBinding));
    Provider<ServletDefinition> bindingProvider = Providers.of(servletDefinition);
    expect(mockBinding.getProvider()).andReturn(bindingProvider);
    replay(injector, binding, requestMock, mockBinding);
    // Have to init the Servlet before we can dispatch to it.
    servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
    final RequestDispatcher dispatcher = new ManagedServletPipeline(injector).getRequestDispatcher(pattern);
    assertNotNull(dispatcher);
    dispatcher.include(requestMock, createMock(HttpServletResponse.class));
    assertTrue("Include did not dispatch to our servlet!", run[0]);
    verify(injector, requestMock, mockBinding);
}
Also used : Binding(com.google.inject.Binding) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Injector(com.google.inject.Injector) EasyMock.anyObject(org.easymock.EasyMock.anyObject)

Example 90 with Binding

use of com.google.inject.Binding 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)

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