Search in sources :

Example 21 with Binding

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

the class FactoryModuleBuilderTest method testFactoryBindingDependencies.

public void testFactoryBindingDependencies() {
    // validate dependencies work in all stages & as a raw element,
    // and that dependencies work for methods, fields, constructors,
    // and for @AssistedInject constructors too.
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            bind(Integer.class).toInstance(42);
            bind(Double.class).toInstance(4.2d);
            bind(Float.class).toInstance(4.2f);
            bind(String.class).annotatedWith(named("dog")).toInstance("dog");
            bind(String.class).annotatedWith(named("cat1")).toInstance("cat1");
            bind(String.class).annotatedWith(named("cat2")).toInstance("cat2");
            bind(String.class).annotatedWith(named("cat3")).toInstance("cat3");
            bind(String.class).annotatedWith(named("arbitrary")).toInstance("fail!");
            install(new FactoryModuleBuilder().implement(Animal.class, Dog.class).build(AnimalHouse.class));
        }
    };
    Set<Key<?>> expectedKeys = ImmutableSet.<Key<?>>of(Key.get(Integer.class), Key.get(Double.class), Key.get(Float.class), Key.get(String.class, named("dog")), Key.get(String.class, named("cat1")), Key.get(String.class, named("cat2")), Key.get(String.class, named("cat3")));
    Injector injector = Guice.createInjector(module);
    validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
    injector = Guice.createInjector(Stage.TOOL, module);
    validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
    List<Element> elements = Elements.getElements(module);
    boolean found = false;
    for (Element element : elements) {
        if (element instanceof Binding) {
            Binding<?> binding = (Binding<?>) element;
            if (binding.getKey().equals(Key.get(AnimalHouse.class))) {
                found = true;
                validateDependencies(expectedKeys, binding);
                break;
            }
        }
    }
    assertTrue(found);
}
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) AbstractModule(com.google.inject.AbstractModule) Key(com.google.inject.Key)

Example 22 with Binding

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

the class InjectorSpiTest method testExistingBinding.

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

        @Override
        protected void configure() {
            bind(Foo.class);
            bind(Baz.class);
        }
    });
    // Sanity check -- ensure we return the proper binding for all existing bindings.
    for (Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
        assertSame(entry.getValue(), injector.getExistingBinding(entry.getKey()));
    }
    // Now run through specifics...
    Binding<?> binding;
    // 1) non-Provider Foo.class
    binding = injector.getExistingBinding(Key.get(Foo.class));
    assertNotNull(binding);
    assertEquals(Foo.class, binding.getKey().getTypeLiteral().getRawType());
    // 2) Provider<Foo> class (should already exist, because Baz @Injects it).
    // the assertTrue is a bit stricter than necessary, but makes sure this works for pre-existing Provider bindings
    assertTrue(injector.getAllBindings().containsKey(Key.get(new TypeLiteral<Provider<Foo>>() {
    })));
    binding = injector.getExistingBinding(Key.get(new TypeLiteral<Provider<Foo>>() {
    }));
    assertNotNull(binding);
    assertEquals(Provider.class, binding.getKey().getTypeLiteral().getRawType());
    assertEquals(Foo.class, ((Provider) binding.getProvider().get()).get().getClass());
    // 3) non-Provider Baz.class
    binding = injector.getExistingBinding(Key.get(Baz.class));
    assertNotNull(binding);
    assertEquals(Baz.class, binding.getKey().getTypeLiteral().getRawType());
    // 4) Provider<Baz> class (should not already exist, because nothing used it yet).
    // the assertFalse is a bit stricter than necessary, but makes sure this works for non-pre-existing Provider bindings
    assertFalse(injector.getAllBindings().containsKey(Key.get(new TypeLiteral<Provider<Baz>>() {
    })));
    binding = injector.getExistingBinding(Key.get(new TypeLiteral<Provider<Baz>>() {
    }));
    assertNotNull(binding);
    assertEquals(Provider.class, binding.getKey().getTypeLiteral().getRawType());
    assertEquals(Baz.class, ((Provider) binding.getProvider().get()).get().getClass());
    // 5) non-Provider Bar, doesn't exist.
    assertNull(injector.getExistingBinding(Key.get(Bar.class)));
    // 6) Provider Bar, doesn't exist.
    assertNull(injector.getExistingBinding(Key.get(new TypeLiteral<Provider<Bar>>() {
    })));
}
Also used : Binding(com.google.inject.Binding) AbstractModule(com.google.inject.AbstractModule) Provider(com.google.inject.Provider) Injector(com.google.inject.Injector) Map(java.util.Map) Key(com.google.inject.Key)

Example 23 with Binding

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

the class ModuleRewriterTest method testRewriteBindings.

public void testRewriteBindings() {
    // create a module the binds String.class and CharSequence.class
    Module module = new AbstractModule() {

        protected void configure() {
            bind(String.class).toInstance("Pizza");
            bind(CharSequence.class).toInstance("Wine");
        }
    };
    // record the elements from that module
    List<Element> elements = Elements.getElements(module);
    // create a rewriter that rewrites the binding to 'Wine' with a binding to 'Beer'
    List<Element> rewritten = Lists.newArrayList();
    for (Element element : elements) {
        element = element.acceptVisitor(new DefaultElementVisitor<Element>() {

            @Override
            public <T> Element visit(Binding<T> binding) {
                T target = binding.acceptTargetVisitor(Elements.<T>getInstanceVisitor());
                if ("Wine".equals(target)) {
                    return null;
                } else {
                    return binding;
                }
            }
        });
        if (element != null) {
            rewritten.add(element);
        }
    }
    // create a module from the original list of elements and the rewriter
    Module rewrittenModule = Elements.getModule(rewritten);
    // the wine binding is dropped
    Injector injector = Guice.createInjector(rewrittenModule);
    try {
        injector.getInstance(CharSequence.class);
        fail();
    } catch (ConfigurationException expected) {
    }
}
Also used : Binding(com.google.inject.Binding) ConfigurationException(com.google.inject.ConfigurationException) Injector(com.google.inject.Injector) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule)

Example 24 with Binding

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

the class ServletPipelineRequestDispatcherTest method forwardToManagedServletFailureOnCommittedBuffer.

public final void forwardToManagedServletFailureOnCommittedBuffer() throws IOException, ServletException {
    String pattern = "blah.html";
    final ServletDefinition servletDefinition = new ServletDefinition(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 mockRequest = createMock(HttpServletRequest.class);
    final HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
    expect(mockResponse.isCommitted()).andReturn(true);
    final HttpServlet mockServlet = new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
            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(Key.get(HttpServlet.class))).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, mockRequest, mockResponse, 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);
    try {
        dispatcher.forward(mockRequest, mockResponse);
    } finally {
        verify(injector, mockRequest, mockResponse, 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 25 with Binding

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

the class ServletPipelineRequestDispatcherTest method testIncludeManagedServlet.

public final void testIncludeManagedServlet() throws IOException, ServletException {
    String pattern = "blah.html";
    final ServletDefinition servletDefinition = new ServletDefinition(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() {

        @Override
        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)

Aggregations

Binding (com.google.inject.Binding)91 Injector (com.google.inject.Injector)57 Key (com.google.inject.Key)35 AbstractModule (com.google.inject.AbstractModule)33 InstanceBinding (com.google.inject.spi.InstanceBinding)23 Map (java.util.Map)21 HttpServletRequest (javax.servlet.http.HttpServletRequest)21 Element (com.google.inject.spi.Element)18 Module (com.google.inject.Module)17 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