Search in sources :

Example 31 with ProvisionException

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

the class GuiceyFruitModule method configure.

protected void configure() {
    // lets find all of the configures methods
    List<Method> configureMethods = getConfiguresMethods();
    if (!configureMethods.isEmpty()) {
        final GuiceyFruitModule moduleInstance = this;
        final Class<? extends GuiceyFruitModule> moduleType = getClass();
        TypeLiteral<? extends GuiceyFruitModule> type = TypeLiteral.get(moduleType);
        for (final Method method : configureMethods) {
            int size = method.getParameterTypes().length;
            if (size == 0) {
                throw new ProvisionException("No arguments on @Configures method " + method);
            } else if (size > 1) {
                throw new ProvisionException("Too many arguments " + size + " on @Configures method " + method);
            }
            final Class<?> paramType = getParameterType(type, method, 0);
            bindListener(new AbstractMatcher<TypeLiteral<?>>() {

                public boolean matches(TypeLiteral<?> typeLiteral) {
                    return typeLiteral.getRawType().equals(paramType);
                }
            }, new TypeListener() {

                public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) {
                    encounter.register(new MembersInjector<I>() {

                        public void injectMembers(I injectee) {
                            // lets invoke the configures method
                            try {
                                method.setAccessible(true);
                                method.invoke(moduleInstance, injectee);
                            } catch (IllegalAccessException e) {
                                throw new ProvisionException("Failed to invoke @Configures method " + method + ". Reason: " + e, e);
                            } catch (InvocationTargetException ie) {
                                Throwable e = ie.getTargetException();
                                throw new ProvisionException("Failed to invoke @Configures method " + method + ". Reason: " + e, e);
                            }
                        }
                    });
                }
            });
        }
    }
}
Also used : Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ProvisionException(com.google.inject.ProvisionException) TypeLiteral(com.google.inject.TypeLiteral) TypeListener(com.google.inject.spi.TypeListener) MembersInjector(com.google.inject.MembersInjector)

Example 32 with ProvisionException

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

the class GuiceyFruitModule method bindAnnotationInjector.

private <A extends Annotation> void bindAnnotationInjector(final Class<A> annotationType, final EncounterProvider<AnnotationMemberProvider> memberProviderProvider) {
    bindListener(any(), new TypeListener() {

        Provider<? extends AnnotationMemberProvider> providerProvider;

        public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) {
            Set<Field> boundFields = Sets.newHashSet();
            Map<MethodKey, Method> boundMethods = Maps.newHashMap();
            TypeLiteral<?> startType = injectableType;
            while (true) {
                Class<?> type = startType.getRawType();
                if (type == Object.class) {
                    break;
                }
                Field[] fields = type.getDeclaredFields();
                for (Field field : fields) {
                    if (boundFields.add(field)) {
                        bindAnnotationInjectorToField(encounter, startType, field);
                    }
                }
                Method[] methods = type.getDeclaredMethods();
                for (final Method method : methods) {
                    MethodKey key = new MethodKey(method);
                    if (boundMethods.get(key) == null) {
                        boundMethods.put(key, method);
                        bindAnnotationInjectionToMember(encounter, startType, method);
                    }
                }
                Class<?> supertype = type.getSuperclass();
                if (supertype == Object.class) {
                    break;
                }
                startType = startType.getSupertype(supertype);
            }
        }

        protected <I> void bindAnnotationInjectionToMember(final TypeEncounter<I> encounter, final TypeLiteral<?> type, final Method method) {
            // TODO lets exclude methods with @Inject?
            final A annotation = method.getAnnotation(annotationType);
            if (annotation != null) {
                if (providerProvider == null) {
                    providerProvider = memberProviderProvider.get(encounter);
                }
                encounter.register(new MembersInjector<I>() {

                    public void injectMembers(I injectee) {
                        AnnotationMemberProvider provider = providerProvider.get();
                        int size = method.getParameterTypes().length;
                        Object[] values = new Object[size];
                        for (int i = 0; i < size; i++) {
                            Class<?> paramType = getParameterType(type, method, i);
                            Object value = provider.provide(annotation, type, method, paramType, i);
                            checkInjectedValueType(value, paramType, encounter);
                            // things
                            if (value == null && !provider.isNullParameterAllowed(annotation, method, paramType, i)) {
                                return;
                            }
                            values[i] = value;
                        }
                        try {
                            method.setAccessible(true);
                            method.invoke(injectee, values);
                        } catch (IllegalAccessException e) {
                            throw new ProvisionException("Failed to inject method " + method + ". Reason: " + e, e);
                        } catch (InvocationTargetException ie) {
                            Throwable e = ie.getTargetException();
                            throw new ProvisionException("Failed to inject method " + method + ". Reason: " + e, e);
                        }
                    }
                });
            }
        }

        protected <I> void bindAnnotationInjectorToField(final TypeEncounter<I> encounter, final TypeLiteral<?> type, final Field field) {
            // TODO lets exclude fields with @Inject?
            final A annotation = field.getAnnotation(annotationType);
            if (annotation != null) {
                if (providerProvider == null) {
                    providerProvider = memberProviderProvider.get(encounter);
                }
                encounter.register(new InjectionListener<I>() {

                    public void afterInjection(I injectee) {
                        AnnotationMemberProvider provider = providerProvider.get();
                        Object value = provider.provide(annotation, type, field);
                        checkInjectedValueType(value, field.getType(), encounter);
                        try {
                            field.setAccessible(true);
                            field.set(injectee, value);
                        } catch (IllegalAccessException e) {
                            throw new ProvisionException("Failed to inject field " + field + ". Reason: " + e, e);
                        }
                    }
                });
            }
        }
    });
}
Also used : Set(java.util.Set) InjectionListener(com.google.inject.spi.InjectionListener) Field(java.lang.reflect.Field) ProvisionException(com.google.inject.ProvisionException) TypeLiteral(com.google.inject.TypeLiteral) MethodKey(org.apache.camel.guice.support.internal.MethodKey) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) TypeListener(com.google.inject.spi.TypeListener) MembersInjector(com.google.inject.MembersInjector) Map(java.util.Map)

Example 33 with ProvisionException

use of com.google.inject.ProvisionException in project hudson-2.x by hudson.

the class SezPozExtensionModule method bindProvider.

private void bindProvider(final Binder binder, final SpaceIndexItem item, final Key key) {
    binder.bind(key).toProvider(new Provider() {

        public Object get() {
            try {
                return item.instance();
            } catch (final InstantiationException e) {
                throw new ProvisionException(e.toString(), e);
            }
        }
    }).in(Scopes.SINGLETON);
    bindHierarchy(binder, key);
}
Also used : ProvisionException(com.google.inject.ProvisionException) Provider(com.google.inject.Provider)

Example 34 with ProvisionException

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

the class MultibinderTest method testConcurrentMutation_bindingsDiffentAtInjectorCreation.

/*
   * Verify through gratuitous mutation that key hashCode snapshots and whatnot happens at the right
   * times, by binding two lists that are different at injector creation, but compare equal when the
   * module is configured *and* when the set is instantiated.
   */
public void testConcurrentMutation_bindingsDiffentAtInjectorCreation() {
    // We initially bind two equal lists
    final List<String> list1 = Lists.newArrayList();
    final List<String> list2 = Lists.newArrayList();
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings);
            multibinder.addBinding().toInstance(list1);
            multibinder.addBinding().toInstance(list2);
        }
    };
    List<Element> elements = Elements.getElements(module);
    // Now we change the lists so they no longer match, and create the injector.
    list1.add("A");
    list2.add("B");
    Injector injector = Guice.createInjector(Elements.getModule(elements));
    // Now we change the lists so they compare equal again, and create the set.
    list1.add(1, "B");
    list2.add(0, "A");
    try {
        injector.getInstance(Key.get(setOfListOfStrings));
        fail();
    } catch (ProvisionException e) {
        assertEquals(1, e.getErrorMessages().size());
        assertContains(Iterables.getOnlyElement(e.getErrorMessages()).getMessage().toString(), "Set injection failed due to duplicated element \"[A, B]\"");
    }
    // Finally, we change the lists again so they are once more different, and ensure the set
    // contains both.
    list1.remove("A");
    list2.remove("B");
    Set<List<String>> set = injector.getInstance(Key.get(setOfListOfStrings));
    assertEquals(ImmutableSet.of(ImmutableList.of("A"), ImmutableList.of("B")), set);
}
Also used : ProvisionException(com.google.inject.ProvisionException) Injector(com.google.inject.Injector) Element(com.google.inject.spi.Element) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule)

Example 35 with ProvisionException

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

the class MultibinderTest method testMultibinderSetForbidsDuplicateElements.

public void testMultibinderSetForbidsDuplicateElements() {
    Module module1 = new AbstractModule() {

        @Override
        protected void configure() {
            final Multibinder<String> multibinder = Multibinder.newSetBinder(binder(), String.class);
            multibinder.addBinding().toProvider(Providers.of("A"));
        }
    };
    Module module2 = new AbstractModule() {

        @Override
        protected void configure() {
            final Multibinder<String> multibinder = Multibinder.newSetBinder(binder(), String.class);
            multibinder.addBinding().toInstance("A");
        }
    };
    Injector injector = Guice.createInjector(module1, module2);
    try {
        injector.getInstance(Key.get(setOfString));
        fail();
    } catch (ProvisionException expected) {
        assertContains(expected.getMessage(), "1) Set injection failed due to duplicated element \"A\"", "Bound at " + module1.getClass().getName(), "Bound at " + module2.getClass().getName());
    }
    // But we can still visit the module!
    assertSetVisitor(Key.get(setOfString), stringType, setOf(module1, module2), MODULE, false, 0, instance("A"), instance("A"));
}
Also used : ProvisionException(com.google.inject.ProvisionException) Injector(com.google.inject.Injector) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule) AbstractModule(com.google.inject.AbstractModule)

Aggregations

ProvisionException (com.google.inject.ProvisionException)57 Injector (com.google.inject.Injector)22 AbstractModule (com.google.inject.AbstractModule)20 Module (com.google.inject.Module)11 Provider (com.google.inject.Provider)9 OutOfScopeException (com.google.inject.OutOfScopeException)6 TypeLiteral (com.google.inject.TypeLiteral)6 Key (com.google.inject.Key)5 Message (com.google.inject.spi.Message)5 ImmutableList (com.google.common.collect.ImmutableList)4 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)4 OrmException (com.google.gwtorm.server.OrmException)4 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Provides (com.google.inject.Provides)3 Dependency (com.google.inject.spi.Dependency)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Method (java.lang.reflect.Method)3 Path (java.nio.file.Path)3