Search in sources :

Example 86 with TypeLiteral

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

use of com.google.inject.TypeLiteral 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 88 with TypeLiteral

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

the class InjectorImpl method createTypeLiteralBinding.

/**
   * Converts a binding for a {@code Key<TypeLiteral<T>>} to the value {@code TypeLiteral<T>}. It's
   * a bit awkward because we have to pull out the inner type in the type literal.
   */
private <T> BindingImpl<TypeLiteral<T>> createTypeLiteralBinding(Key<TypeLiteral<T>> key, Errors errors) throws ErrorsException {
    Type typeLiteralType = key.getTypeLiteral().getType();
    if (!(typeLiteralType instanceof ParameterizedType)) {
        throw errors.cannotInjectRawTypeLiteral().toException();
    }
    ParameterizedType parameterizedType = (ParameterizedType) typeLiteralType;
    Type innerType = parameterizedType.getActualTypeArguments()[0];
    // this proves problematic, we can probably fix TypeLiteral to support type variables
    if (!(innerType instanceof Class) && !(innerType instanceof GenericArrayType) && !(innerType instanceof ParameterizedType)) {
        throw errors.cannotInjectTypeLiteralOf(innerType).toException();
    }
    // by definition, innerType == T, so this is safe
    @SuppressWarnings("unchecked") TypeLiteral<T> value = (TypeLiteral<T>) TypeLiteral.get(innerType);
    InternalFactory<TypeLiteral<T>> factory = new ConstantFactory<TypeLiteral<T>>(Initializables.of(value));
    return new InstanceBindingImpl<TypeLiteral<T>>(this, key, SourceProvider.UNKNOWN_SOURCE, factory, ImmutableSet.<InjectionPoint>of(), value);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) TypeLiteral(com.google.inject.TypeLiteral) GenericArrayType(java.lang.reflect.GenericArrayType)

Example 89 with TypeLiteral

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

the class InjectorImpl method createMembersInjectorBinding.

private <T> BindingImpl<MembersInjector<T>> createMembersInjectorBinding(Key<MembersInjector<T>> key, Errors errors) throws ErrorsException {
    Type membersInjectorType = key.getTypeLiteral().getType();
    if (!(membersInjectorType instanceof ParameterizedType)) {
        throw errors.cannotInjectRawMembersInjector().toException();
    }
    // safe because T came from Key<MembersInjector<T>>
    @SuppressWarnings("unchecked") TypeLiteral<T> instanceType = (TypeLiteral<T>) TypeLiteral.get(((ParameterizedType) membersInjectorType).getActualTypeArguments()[0]);
    MembersInjector<T> membersInjector = membersInjectorStore.get(instanceType, errors);
    InternalFactory<MembersInjector<T>> factory = new ConstantFactory<MembersInjector<T>>(Initializables.of(membersInjector));
    return new InstanceBindingImpl<MembersInjector<T>>(this, key, SourceProvider.UNKNOWN_SOURCE, factory, ImmutableSet.<InjectionPoint>of(), membersInjector);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) TypeLiteral(com.google.inject.TypeLiteral) MembersInjector(com.google.inject.MembersInjector)

Example 90 with TypeLiteral

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

the class Errors method formatSource.

public static void formatSource(Formatter formatter, Object source, ElementSource elementSource) {
    String modules = moduleSourceString(elementSource);
    if (source instanceof Dependency) {
        Dependency<?> dependency = (Dependency<?>) source;
        InjectionPoint injectionPoint = dependency.getInjectionPoint();
        if (injectionPoint != null) {
            formatInjectionPoint(formatter, dependency, injectionPoint, elementSource);
        } else {
            formatSource(formatter, dependency.getKey(), elementSource);
        }
    } else if (source instanceof InjectionPoint) {
        formatInjectionPoint(formatter, null, (InjectionPoint) source, elementSource);
    } else if (source instanceof Class) {
        formatter.format("  at %s%s%n", StackTraceElements.forType((Class<?>) source), modules);
    } else if (source instanceof Member) {
        formatter.format("  at %s%s%n", StackTraceElements.forMember((Member) source), modules);
    } else if (source instanceof TypeLiteral) {
        formatter.format("  while locating %s%s%n", source, modules);
    } else if (source instanceof Key) {
        Key<?> key = (Key<?>) source;
        formatter.format("  while locating %s%n", convert(key, elementSource));
    } else {
        formatter.format("  at %s%s%n", source, modules);
    }
}
Also used : TypeLiteral(com.google.inject.TypeLiteral) InjectionPoint(com.google.inject.spi.InjectionPoint) Dependency(com.google.inject.spi.Dependency) Member(java.lang.reflect.Member) Key(com.google.inject.Key)

Aggregations

TypeLiteral (com.google.inject.TypeLiteral)112 AbstractModule (com.google.inject.AbstractModule)42 Injector (com.google.inject.Injector)37 Module (com.google.inject.Module)15 Map (java.util.Map)14 Key (com.google.inject.Key)12 Provider (com.google.inject.Provider)12 ParameterizedType (java.lang.reflect.ParameterizedType)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 Binding (com.google.inject.Binding)10 Annotation (java.lang.annotation.Annotation)10 HashMap (java.util.HashMap)10 Set (java.util.Set)10 Binder (com.google.inject.Binder)9 InjectionPoint (com.google.inject.spi.InjectionPoint)9 Method (java.lang.reflect.Method)9 Type (java.lang.reflect.Type)9 HashSet (java.util.HashSet)9 ProvisionException (com.google.inject.ProvisionException)7 FactoryModuleBuilder (com.google.inject.assistedinject.FactoryModuleBuilder)7