Search in sources :

Example 1 with Binding

use of com.google.inject.Binding in project gerrit by GerritCodeReview.

the class SiteProgram method getDbType.

private String getDbType(Provider<DataSource> dsProvider) {
    String dbProductName;
    try (Connection conn = dsProvider.get().getConnection()) {
        dbProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    List<Module> modules = new ArrayList<>();
    modules.add(new AbstractModule() {

        @Override
        protected void configure() {
            bind(Path.class).annotatedWith(SitePath.class).toInstance(getSitePath());
        }
    });
    modules.add(new GerritServerConfigModule());
    modules.add(new DataSourceModule());
    Injector i = Guice.createInjector(modules);
    List<Binding<DataSourceType>> dsTypeBindings = i.findBindingsByType(new TypeLiteral<DataSourceType>() {
    });
    for (Binding<DataSourceType> binding : dsTypeBindings) {
        Annotation annotation = binding.getKey().getAnnotation();
        if (annotation instanceof Named) {
            if (((Named) annotation).value().toLowerCase().contains(dbProductName)) {
                return ((Named) annotation).value();
            }
        }
    }
    throw new IllegalStateException(String.format("Cannot guess database type from the database product name '%s'", dbProductName));
}
Also used : Path(java.nio.file.Path) SitePath(com.google.gerrit.server.config.SitePath) Binding(com.google.inject.Binding) Named(com.google.inject.name.Named) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) AbstractModule(com.google.inject.AbstractModule) GerritServerConfigModule(com.google.gerrit.server.config.GerritServerConfigModule) Injector(com.google.inject.Injector) DataSourceType(com.google.gerrit.server.schema.DataSourceType) GitRepositoryManagerModule(com.google.gerrit.server.git.GitRepositoryManagerModule) Module(com.google.inject.Module) DataSourceModule(com.google.gerrit.server.schema.DataSourceModule) DatabaseModule(com.google.gerrit.server.schema.DatabaseModule) LifecycleModule(com.google.gerrit.lifecycle.LifecycleModule) SchemaModule(com.google.gerrit.server.schema.SchemaModule) GerritServerConfigModule(com.google.gerrit.server.config.GerritServerConfigModule) AbstractModule(com.google.inject.AbstractModule) DataSourceModule(com.google.gerrit.server.schema.DataSourceModule)

Example 2 with Binding

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

Example 3 with Binding

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

the class SpiUtils method setModuleTest.

@SuppressWarnings("unchecked")
private static <T> void setModuleTest(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));
    List<BindResult> bindResults = Lists.newArrayList(results);
    List<Element> elements = Elements.getElements(modules);
    Visitor<T> visitor = new Visitor<T>();
    MultibinderBinding<Set<T>> multibinder = null;
    for (Element element : elements) {
        if (element instanceof Binding && ((Binding) element).getKey().equals(setKey)) {
            multibinder = (MultibinderBinding<Set<T>>) ((Binding) element).acceptTargetVisitor(visitor);
            break;
        }
    }
    assertNotNull(multibinder);
    assertEquals(elementType, multibinder.getElementTypeLiteral());
    List<Object> otherMultibinders = Lists.newArrayList();
    Set<Element> otherContains = new HashSet<Element>();
    List<Element> otherElements = Lists.newArrayList();
    int duplicates = 0;
    Set<IndexedBinding> setOfIndexed = Sets.newHashSet();
    Indexer indexer = new Indexer(null);
    boolean collectionOfProvidersMatch = false;
    boolean collectionOfJavaxProvidersMatch = false;
    for (Element element : elements) {
        boolean contains = multibinder.containsElement(element);
        if (!contains) {
            otherElements.add(element);
        }
        boolean matched = false;
        Key key = null;
        if (element instanceof Binding) {
            Binding binding = (Binding) element;
            if (indexer.isIndexable(binding) && !setOfIndexed.add((IndexedBinding) binding.acceptTargetVisitor(indexer))) {
                duplicates++;
            }
            key = binding.getKey();
            Object visited = binding.acceptTargetVisitor(visitor);
            if (visited != null) {
                matched = true;
                if (visited.equals(multibinder)) {
                    assertTrue(contains);
                } else {
                    otherMultibinders.add(visited);
                }
            }
        }
        if (collectionOfProvidersKey.equals(key)) {
            assertTrue(contains);
            assertFalse(matched);
            collectionOfProvidersMatch = true;
        } else if (collectionOfJavaxProvidersKey.equals(key)) {
            assertTrue(contains);
            assertFalse(matched);
            collectionOfJavaxProvidersMatch = true;
        } else if (!matched && contains) {
            otherContains.add(element);
        }
    }
    if (allowDuplicates) {
        assertEquals("wrong contained elements: " + otherContains, bindResults.size() + 1 + duplicates, otherContains.size());
    } else {
        assertEquals("wrong contained elements: " + otherContains, bindResults.size() + duplicates, otherContains.size());
    }
    assertEquals("other multibindings found: " + otherMultibinders, otherMultibindings, otherMultibinders.size());
    assertTrue(collectionOfProvidersMatch);
    assertTrue(collectionOfJavaxProvidersMatch);
    // Validate that we can construct an injector out of the remaining bindings.
    Guice.createInjector(Elements.getModule(otherElements));
}
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) Element(com.google.inject.spi.Element) Key(com.google.inject.Key) HashSet(java.util.HashSet)

Example 4 with Binding

use of com.google.inject.Binding in project camel by apache.

the class Main method getCamelContextMap.

protected Map<String, CamelContext> getCamelContextMap() {
    Map<String, CamelContext> answer = Maps.newHashMap();
    if (injector != null) {
        Set<Map.Entry<Key<?>, Binding<?>>> entries = injector.getBindings().entrySet();
        for (Map.Entry<Key<?>, Binding<?>> entry : entries) {
            Key<?> key = entry.getKey();
            Class<?> keyType = Injectors.getKeyType(key);
            if (keyType != null && CamelContext.class.isAssignableFrom(keyType)) {
                Binding<?> binding = entry.getValue();
                Object value = binding.getProvider().get();
                if (value != null) {
                    CamelContext castValue = CamelContext.class.cast(value);
                    answer.put(key.toString(), castValue);
                }
            }
        }
    }
    return answer;
}
Also used : CamelContext(org.apache.camel.CamelContext) Binding(com.google.inject.Binding) Map(java.util.Map) Key(com.google.inject.Key)

Example 5 with Binding

use of com.google.inject.Binding in project shiro by apache.

the class ShiroAopModuleTest method testGetAnnotationResolver.

@Test
public void testGetAnnotationResolver() {
    final AnnotationResolver annotationResolver = new DefaultAnnotationResolver();
    ShiroAopModule underTest = new ShiroAopModule() {

        @Override
        protected AnnotationResolver createAnnotationResolver() {
            return annotationResolver;
        }

        @Override
        protected void configureDefaultInterceptors(AnnotationResolver resolver) {
            assertSame(annotationResolver, resolver);
            bind(Object.class).annotatedWith(Names.named("configureDefaultInterceptors"));
        }

        @Override
        protected void configureInterceptors(AnnotationResolver resolver) {
            assertSame(annotationResolver, resolver);
            bind(Object.class).annotatedWith(Names.named("configureInterceptors"));
        }
    };
    boolean calledDefault = false;
    boolean calledCustom = false;
    for (Element e : Elements.getElements(underTest)) {
        if (e instanceof Binding) {
            Key key = ((Binding) e).getKey();
            if (Named.class.isAssignableFrom(key.getAnnotation().annotationType()) && "configureInterceptors".equals(((Named) key.getAnnotation()).value()) && key.getTypeLiteral().getRawType().equals(Object.class)) {
                calledCustom = true;
            }
            if (Named.class.isAssignableFrom(key.getAnnotation().annotationType()) && "configureDefaultInterceptors".equals(((Named) key.getAnnotation()).value()) && key.getTypeLiteral().getRawType().equals(Object.class)) {
                calledDefault = true;
            }
        }
    }
}
Also used : Binding(com.google.inject.Binding) InterceptorBinding(com.google.inject.spi.InterceptorBinding) Element(com.google.inject.spi.Element) Key(com.google.inject.Key) Test(org.junit.Test)

Aggregations

Binding (com.google.inject.Binding)89 Injector (com.google.inject.Injector)51 Key (com.google.inject.Key)41 AbstractModule (com.google.inject.AbstractModule)34 InstanceBinding (com.google.inject.spi.InstanceBinding)26 Map (java.util.Map)23 Element (com.google.inject.spi.Element)20 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)20 Module (com.google.inject.Module)19 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)19 DefaultBindingTargetVisitor (com.google.inject.spi.DefaultBindingTargetVisitor)15 ProviderKeyBinding (com.google.inject.spi.ProviderKeyBinding)15 ImmutableMap (com.google.common.collect.ImmutableMap)13 MapBinderBinding (com.google.inject.multibindings.MapBinderBinding)13 HashMap (java.util.HashMap)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 TypeLiteral (com.google.inject.TypeLiteral)10 HashSet (java.util.HashSet)10 IndexedBinding (com.google.inject.internal.Indexer.IndexedBinding)9 MultibinderBinding (com.google.inject.multibindings.MultibinderBinding)9