org.elasticsearch.common.inject.TypeLiteral Java Examples

The following examples show how to use org.elasticsearch.common.inject.TypeLiteral. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InjectionPoint.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
InjectionPoint(TypeLiteral<?> type, Field field) {
    this.member = field;

    Inject inject = field.getAnnotation(Inject.class);
    this.optional = inject.optional();

    Annotation[] annotations = field.getAnnotations();

    Errors errors = new Errors(field);
    Key<?> key = null;
    try {
        key = Annotations.getKey(type.getFieldType(field), field, annotations, errors);
    } catch (ErrorsException e) {
        errors.merge(e.getErrors());
    }
    errors.throwConfigurationExceptionIfErrorsExist();

    this.dependencies = Collections.<Dependency<?>>singletonList(
        newDependency(key, Nullability.allowsNull(annotations), -1));
}
 
Example #2
Source File: InjectionPoint.java    From crate with Apache License 2.0 6 votes vote down vote up
private static <M extends Member & AnnotatedElement> void addInjectorsForMembers(
        TypeLiteral<?> typeLiteral, Factory<M> factory, boolean statics,
        Collection<InjectionPoint> injectionPoints, Errors errors) {
    for (M member : factory.getMembers(getRawType(typeLiteral.getType()))) {
        if (isStatic(member) != statics) {
            continue;
        }

        Inject inject = member.getAnnotation(Inject.class);
        if (inject == null) {
            continue;
        }

        try {
            injectionPoints.add(factory.create(typeLiteral, member, errors));
        } catch (ConfigurationException ignorable) {
            if (!inject.optional()) {
                errors.merge(ignorable.getErrorMessages());
            }
        }
    }
}
 
Example #3
Source File: CommandModule.java    From elasticshell with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    Multibinder<Command> multiBinder = Multibinder.newSetBinder(binder(), Command.class);
    multiBinder.addBinding().to(ExitCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HelpCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(PrintCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(SaveCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HistoryCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(VersionCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(LoadCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpGetCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpHeadCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpPostCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpPutCommand.class).asEagerSingleton();
    multiBinder.addBinding().to(HttpDeleteCommand.class).asEagerSingleton();

    //Rhino specific commands
    multiBinder.addBinding().to(new TypeLiteral<ToJsonCommand<Object>>() {}).asEagerSingleton();
    multiBinder.addBinding().to(new TypeLiteral<TransportClientCommand<RhinoClientNativeJavaObject>>(){}).asEagerSingleton();
    multiBinder.addBinding().to(new TypeLiteral<NodeClientCommand<RhinoClientNativeJavaObject>>(){}).asEagerSingleton();
    multiBinder.addBinding().to(new TypeLiteral<LocalNodeCommand<RhinoClientNativeJavaObject, NativeObject, Object>>(){}).asEagerSingleton();

    bind(RhinoCommandRegistrar.class).asEagerSingleton();
}
 
Example #4
Source File: RhinoShellModule.java    From elasticshell with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    bind(ScriptLoader.class).to(RhinoScriptLoader.class).asEagerSingleton();
    bind(new TypeLiteral<JsonToString<NativeObject>>() {}).to(RhinoJsonToString.class).asEagerSingleton();
    bind(new TypeLiteral<StringToJson<Object>>(){}).to(RhinoStringToJson.class).asEagerSingleton();
    bind(Unwrapper.class).to(RhinoUnwrapper.class).asEagerSingleton();
    bind(new TypeLiteral<ShellScope<RhinoShellTopLevel>>(){}).to(RhinoShellScope.class).asEagerSingleton();
    bind(ScriptExecutor.class).to(RhinoScriptExecutor.class).asEagerSingleton();
    bind(InputAnalyzer.class).to(RhinoInputAnalyzer.class).asEagerSingleton();
    bind(Shell.class).to(RhinoShell.class).asEagerSingleton();

    bind(new TypeLiteral<ClientScopeSynchronizerFactory<RhinoClientNativeJavaObject>>(){})
            .to(RhinoClientScopeSynchronizerFactory.class).asEagerSingleton();

    bind(new TypeLiteral<ClientWrapper<RhinoClientNativeJavaObject, NativeObject, Object>>(){})
            .to(RhinoClientWrapper.class).asEagerSingleton();

    bind(new TypeLiteral<ClientFactory<RhinoClientNativeJavaObject>>() {})
            .to(new TypeLiteral<DefaultClientFactory<RhinoClientNativeJavaObject, NativeObject, Object>>() {})
            .asEagerSingleton();

    bind(new TypeLiteral<NodeFactory<RhinoClientNativeJavaObject, NativeObject, Object>>(){})
            .to(new TypeLiteral<DefaultNodeFactory<RhinoClientNativeJavaObject, NativeObject, Object>>() {})
            .asEagerSingleton();
}
 
Example #5
Source File: InjectionPoint.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private static <M extends Member & AnnotatedElement> void addInjectorsForMembers(
        TypeLiteral<?> typeLiteral, Factory<M> factory, boolean statics,
        Collection<InjectionPoint> injectionPoints, Errors errors) {
    for (M member : factory.getMembers(getRawType(typeLiteral.getType()))) {
        if (isStatic(member) != statics) {
            continue;
        }

        Inject inject = member.getAnnotation(Inject.class);
        if (inject == null) {
            continue;
        }

        try {
            injectionPoints.add(factory.create(typeLiteral, member, errors));
        } catch (ConfigurationException ignorable) {
            if (!inject.optional()) {
                errors.merge(ignorable.getErrorMessages());
            }
        }
    }
}
 
Example #6
Source File: AssistedConstructor.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public AssistedConstructor(Constructor<T> constructor, List<TypeLiteral<?>> parameterTypes) {
    this.constructor = constructor;

    Annotation[][] annotations = constructor.getParameterAnnotations();

    List<Type> typeList = new ArrayList<>();
    allParameters = new ArrayList<>();

    // categorize params as @Assisted or @Injected
    for (int i = 0; i < parameterTypes.size(); i++) {
        Parameter parameter = new Parameter(parameterTypes.get(i).getType(), annotations[i]);
        allParameters.add(parameter);
        if (parameter.isProvidedByFactory()) {
            typeList.add(parameter.getType());
        }
    }
    this.assistedParameters = new ParameterListKey(typeList);
}
 
Example #7
Source File: InjectionPoint.java    From crate with Apache License 2.0 6 votes vote down vote up
InjectionPoint(TypeLiteral<?> type, Field field) {
    this.member = field;

    Inject inject = field.getAnnotation(Inject.class);
    this.optional = inject.optional();

    Annotation[] annotations = field.getAnnotations();

    Errors errors = new Errors(field);
    Key<?> key = null;
    try {
        key = Annotations.getKey(type.getFieldType(field), field, annotations, errors);
    } catch (ErrorsException e) {
        errors.merge(e.getErrors());
    }
    errors.throwConfigurationExceptionIfErrorsExist();

    this.dependencies = Collections.<Dependency<?>>singletonList(
        newDependency(key, Nullability.allowsNull(annotations), -1));
}
 
Example #8
Source File: MapBinder.java    From crate with Apache License 2.0 5 votes vote down vote up
private RealMapBinder(Binder binder, TypeLiteral<V> valueType,
                      Key<Map<K, V>> mapKey, Key<Map<K, Provider<V>>> providerMapKey,
                      Multibinder<Map.Entry<K, Provider<V>>> entrySetBinder) {
    this.valueType = valueType;
    this.mapKey = mapKey;
    this.providerMapKey = providerMapKey;
    this.entrySetBinder = (RealMultibinder<Entry<K, Provider<V>>>) entrySetBinder;
    this.binder = binder;
}
 
Example #9
Source File: InjectionPoint.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private static <M extends Member & AnnotatedElement> void addInjectionPoints(TypeLiteral<?> type,
                                                                             Factory<M> factory, boolean statics, Collection<InjectionPoint> injectionPoints,
                                                                             Errors errors) {
    if (type.getType() == Object.class) {
        return;
    }

    // Add injectors for superclass first.
    TypeLiteral<?> superType = type.getSupertype(type.getRawType().getSuperclass());
    addInjectionPoints(superType, factory, statics, injectionPoints, errors);

    // Add injectors for all members next
    addInjectorsForMembers(type, factory, statics, injectionPoints, errors);
}
 
Example #10
Source File: Elements.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public <T> MembersInjector<T> getMembersInjector(final TypeLiteral<T> typeLiteral) {
    final MembersInjectorLookup<T> element
            = new MembersInjectorLookup<>(getSource(), typeLiteral);
    elements.add(element);
    return element.getMembersInjector();
}
 
Example #11
Source File: Elements.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public <T> MembersInjector<T> getMembersInjector(final TypeLiteral<T> typeLiteral) {
    final MembersInjectorLookup<T> element
            = new MembersInjectorLookup<>(getSource(), typeLiteral);
    elements.add(element);
    return element.getMembersInjector();
}
 
Example #12
Source File: InjectionPoint.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all static method and field injection points on {@code type}.
 *
 * @return a possibly empty set of injection points. The set has a specified iteration order. All
 *         fields are returned and then all methods. Within the fields, supertype fields are returned
 *         before subtype fields. Similarly, supertype methods are returned before subtype methods.
 * @throws ConfigurationException if there is a malformed injection point on {@code type}, such as
 *                                a field with multiple binding annotations. The exception's {@link
 *                                ConfigurationException#getPartialValue() partial value} is a {@code Set<InjectionPoint>}
 *                                of the valid injection points.
 */
public static Set<InjectionPoint> forStaticMethodsAndFields(TypeLiteral type) {
    List<InjectionPoint> sink = new ArrayList<>();
    Errors errors = new Errors();

    addInjectionPoints(type, Factory.FIELDS, true, sink, errors);
    addInjectionPoints(type, Factory.METHODS, true, sink, errors);

    ImmutableSet<InjectionPoint> result = ImmutableSet.copyOf(sink);
    if (errors.hasErrors()) {
        throw new ConfigurationException(errors.getMessages()).withPartialValue(result);
    }
    return result;
}
 
Example #13
Source File: InjectionPoint.java    From crate with Apache License 2.0 5 votes vote down vote up
private static <M extends Member & AnnotatedElement> void addInjectionPoints(TypeLiteral<?> type,
                                                                             Factory<M> factory, boolean statics, Collection<InjectionPoint> injectionPoints,
                                                                             Errors errors) {
    if (type.getType() == Object.class) {
        return;
    }

    // Add injectors for superclass first.
    TypeLiteral<?> superType = type.getSupertype(type.getRawType().getSuperclass());
    addInjectionPoints(superType, factory, statics, injectionPoints, errors);

    // Add injectors for all members next
    addInjectorsForMembers(type, factory, statics, injectionPoints, errors);
}
 
Example #14
Source File: Errors.java    From crate with Apache License 2.0 5 votes vote down vote up
public Errors errorNotifyingTypeListener(TypeListenerBinding listener,
                                         TypeLiteral<?> type, Throwable cause) {
    return errorInUserCode(cause,
            "Error notifying TypeListener %s (bound at %s) of %s.%n"
                    + " Reason: %s",
            listener.getListener(), convert(listener.getSource()), type, cause);
}
 
Example #15
Source File: Multibinder.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
 * itself bound with {@code annotation}.
 */
public static <T> Multibinder<T> newSetBinder(
        Binder binder, TypeLiteral<T> type, Annotation annotation) {
    binder = binder.skipSources(RealMultibinder.class, Multibinder.class);
    RealMultibinder<T> result = new RealMultibinder<>(binder, type, annotation.toString(),
            Key.get(Multibinder.<T>setOf(type), annotation));
    binder.install(result);
    return result;
}
 
Example #16
Source File: InjectionPoint.java    From crate with Apache License 2.0 5 votes vote down vote up
InjectionPoint(TypeLiteral<?> type, Method method) {
    this.member = method;

    Inject inject = method.getAnnotation(Inject.class);
    this.optional = inject.optional();

    this.dependencies = forMember(method, type, method.getParameterAnnotations());
}
 
Example #17
Source File: Errors.java    From crate with Apache License 2.0 5 votes vote down vote up
public Errors conversionError(String stringValue, Object source,
                              TypeLiteral<?> type, MatcherAndConverter matchingConverter, RuntimeException cause) {
    return errorInUserCode(cause, "Error converting '%s' (bound at %s) to %s%n"
            + " using %s.%n"
            + " Reason: %s",
            stringValue, convert(source), type, matchingConverter, cause);
}
 
Example #18
Source File: Errors.java    From crate with Apache License 2.0 5 votes vote down vote up
public static void formatSource(Formatter formatter, Object source) {
    if (source instanceof Dependency) {
        Dependency<?> dependency = (Dependency<?>) source;
        InjectionPoint injectionPoint = dependency.getInjectionPoint();
        if (injectionPoint != null) {
            formatInjectionPoint(formatter, dependency, injectionPoint);
        } else {
            formatSource(formatter, dependency.getKey());
        }

    } else if (source instanceof InjectionPoint) {
        formatInjectionPoint(formatter, null, (InjectionPoint) source);

    } else if (source instanceof Class) {
        formatter.format("  at %s%n", StackTraceElements.forType((Class<?>) source));

    } else if (source instanceof Member) {
        formatter.format("  at %s%n", StackTraceElements.forMember((Member) source));

    } else if (source instanceof TypeLiteral) {
        formatter.format("  while locating %s%n", source);

    } else if (source instanceof Key) {
        Key<?> key = (Key<?>) source;
        formatter.format("  while locating %s%n", convert(key));

    } else {
        formatter.format("  at %s%n", source);
    }
}
 
Example #19
Source File: Multibinder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
 * itself bound with no binding annotation.
 */
public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type) {
    binder = binder.skipSources(RealMultibinder.class, Multibinder.class);
    RealMultibinder<T> result = new RealMultibinder<>(binder, type, "",
            Key.get(Multibinder.<T>setOf(type)));
    binder.install(result);
    return result;
}
 
Example #20
Source File: MapBinder.java    From crate with Apache License 2.0 5 votes vote down vote up
private static <K, V> MapBinder<K, V> newMapBinder(Binder binder, TypeLiteral<V> valueType,
                                                   Key<Map<K, V>> mapKey, Key<Map<K, Provider<V>>> providerMapKey,
                                                   Multibinder<Entry<K, Provider<V>>> entrySetBinder) {
    RealMapBinder<K, V> mapBinder = new RealMapBinder<>(
            binder, valueType, mapKey, providerMapKey, entrySetBinder);
    binder.install(mapBinder);
    return mapBinder;
}
 
Example #21
Source File: FactoryProvider2.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * @param factoryType  a Java interface that defines one or more create methods.
 * @param producedType a concrete type that is assignable to the return types of all factory
 *                     methods.
 */
FactoryProvider2(TypeLiteral<F> factoryType, Key<?> producedType) {
    this.producedType = producedType;

    Errors errors = new Errors();

    @SuppressWarnings("unchecked") // we imprecisely treat the class literal of T as a Class<T>
            Class<F> factoryRawType = (Class) factoryType.getRawType();

    try {
        ImmutableMap.Builder<Method, Key<?>> returnTypesBuilder = ImmutableMap.builder();
        ImmutableMap.Builder<Method, List<Key<?>>> paramTypesBuilder
                = ImmutableMap.builder();
        // TODO: also grab methods from superinterfaces
        for (Method method : factoryRawType.getMethods()) {
            Key<?> returnType = getKey(
                    factoryType.getReturnType(method), method, method.getAnnotations(), errors);
            returnTypesBuilder.put(method, returnType);
            List<TypeLiteral<?>> params = factoryType.getParameterTypes(method);
            Annotation[][] paramAnnotations = method.getParameterAnnotations();
            int p = 0;
            List<Key<?>> keys = new ArrayList<>();
            for (TypeLiteral<?> param : params) {
                Key<?> paramKey = getKey(param, method, paramAnnotations[p++], errors);
                keys.add(assistKey(method, paramKey, errors));
            }
            paramTypesBuilder.put(method, Collections.unmodifiableList(keys));
        }
        returnTypesByMethod = returnTypesBuilder.build();
        paramTypes = paramTypesBuilder.build();
    } catch (ErrorsException e) {
        throw new ConfigurationException(e.getErrors().getMessages());
    }

    factory = factoryRawType.cast(Proxy.newProxyInstance(factoryRawType.getClassLoader(),
            new Class[]{factoryRawType}, this));
}
 
Example #22
Source File: InjectionPoint.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all static method and field injection points on {@code type}.
 *
 * @return a possibly empty set of injection points. The set has a specified iteration order. All
 *         fields are returned and then all methods. Within the fields, supertype fields are returned
 *         before subtype fields. Similarly, supertype methods are returned before subtype methods.
 * @throws ConfigurationException if there is a malformed injection point on {@code type}, such as
 *                                a field with multiple binding annotations. The exception's {@link
 *                                ConfigurationException#getPartialValue() partial value} is a {@code Set<InjectionPoint>}
 *                                of the valid injection points.
 */
public static Set<InjectionPoint> forStaticMethodsAndFields(TypeLiteral type) {
    Set<InjectionPoint> result = new HashSet<>();
    Errors errors = new Errors();

    addInjectionPoints(type, Factory.FIELDS, true, result, errors);
    addInjectionPoints(type, Factory.METHODS, true, result, errors);

    result = unmodifiableSet(result);
    if (errors.hasErrors()) {
        throw new ConfigurationException(errors.getMessages()).withPartialValue(result);
    }
    return result;
}
 
Example #23
Source File: Annotations.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a key for the given type, member and annotations.
 */
public static Key<?> getKey(TypeLiteral<?> type, Member member, Annotation[] annotations,
                            Errors errors) throws ErrorsException {
    int numErrorsBefore = errors.size();
    Annotation found = findBindingAnnotation(errors, member, annotations);
    errors.throwIfNewErrors(numErrorsBefore);
    return found == null ? Key.get(type) : Key.get(type, found);
}
 
Example #24
Source File: CrateCoreModule.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
    encounter.register(new InjectionListener<I>() {
        @Override
        public void afterInjection(I injectee) {
            try {
                CrateRestMainAction crateRestMainAction = instanceFuture.get(10, TimeUnit.SECONDS);
                crateRestMainAction.registerHandler();
            } catch (Exception e) {
                logger.error("Could not register CrateRestMainAction handler", e);
            }
        }
    });
}
 
Example #25
Source File: MoreTypes.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an equivalent type that's safe for use in a key. The returned type will be free of
 * primitive types. Type literals of primitives will return the corresponding wrapper types.
 *
 * @throws ConfigurationException if {@code type} contains a type variable
 */
public static <T> TypeLiteral<T> makeKeySafe(TypeLiteral<T> type) {
    if (!isFullySpecified(type.getType())) {
        String message = type + " cannot be used as a key; It is not fully specified.";
        throw new ConfigurationException(ImmutableSet.of(new Message(message)));
    }

    @SuppressWarnings("unchecked")
    TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER.get(type);
    return wrappedPrimitives != null
            ? wrappedPrimitives
            : type;
}
 
Example #26
Source File: Annotations.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a key for the given type, member and annotations.
 */
public static Key<?> getKey(TypeLiteral<?> type, Member member, Annotation[] annotations,
                            Errors errors) throws ErrorsException {
    int numErrorsBefore = errors.size();
    Annotation found = findBindingAnnotation(errors, member, annotations);
    errors.throwIfNewErrors(numErrorsBefore);
    return found == null ? Key.get(type) : Key.get(type, found);
}
 
Example #27
Source File: Multibinder.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is
 * itself bound with {@code annotationType}.
 */
public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type,
                                              Class<? extends Annotation> annotationType) {
    binder = binder.skipSources(RealMultibinder.class, Multibinder.class);
    RealMultibinder<T> result = new RealMultibinder<>(binder, type, "@" + annotationType.getName(),
            Key.get(Multibinder.<T>setOf(type), annotationType));
    binder.install(result);
    return result;
}
 
Example #28
Source File: Errors.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Errors ambiguousTypeConversion(String stringValue, Object source, TypeLiteral<?> type,
                                      MatcherAndConverter a, MatcherAndConverter b) {
    return addMessage("Multiple converters can convert '%s' (bound at %s) to %s:%n"
            + " %s and%n"
            + " %s.%n"
            + " Please adjust your type converter configuration to avoid overlapping matches.",
            stringValue, convert(source), type, a, b);
}
 
Example #29
Source File: Errors.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Errors errorNotifyingTypeListener(TypeListenerBinding listener,
                                         TypeLiteral<?> type, Throwable cause) {
    return errorInUserCode(cause,
            "Error notifying TypeListener %s (bound at %s) of %s.%n"
                    + " Reason: %s",
            listener.getListener(), convert(listener.getSource()), type, cause);
}
 
Example #30
Source File: Errors.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static void formatSource(Formatter formatter, Object source) {
    if (source instanceof Dependency) {
        Dependency<?> dependency = (Dependency<?>) source;
        InjectionPoint injectionPoint = dependency.getInjectionPoint();
        if (injectionPoint != null) {
            formatInjectionPoint(formatter, dependency, injectionPoint);
        } else {
            formatSource(formatter, dependency.getKey());
        }

    } else if (source instanceof InjectionPoint) {
        formatInjectionPoint(formatter, null, (InjectionPoint) source);

    } else if (source instanceof Class) {
        formatter.format("  at %s%n", StackTraceElements.forType((Class<?>) source));

    } else if (source instanceof Member) {
        formatter.format("  at %s%n", StackTraceElements.forMember((Member) source));

    } else if (source instanceof TypeLiteral) {
        formatter.format("  while locating %s%n", source);

    } else if (source instanceof Key) {
        Key<?> key = (Key<?>) source;
        formatter.format("  while locating %s%n", convert(key));

    } else {
        formatter.format("  at %s%n", source);
    }
}