Java Code Examples for com.google.inject.util.Types

The following examples show how to use com.google.inject.util.Types. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public Type getGenericType(ApiImplicitParam apiImplicitParam) {
  Type dataTypeClass = apiImplicitParam.dataTypeClass();
  if (ReflectionUtils.isVoid(dataTypeClass)) {
    if (StringUtils.isEmpty(apiImplicitParam.dataType())) {
      return null;
    }

    dataTypeClass = ReflectionUtils.typeFromString(apiImplicitParam.dataType());
  }

  if ("array".equals(apiImplicitParam.type())) {
    return Types.arrayOf(dataTypeClass);
  }

  return dataTypeClass;
}
 
Example 2
protected BespokeFormatStoreModule() {
  // first fetch the store types captured by this module
  Type[] typeArguments = typeArguments(getClass(), BespokeFormatStoreModule.class);
  int numTypes = typeArguments.length;

  // next extract the DAO types captured by each store type
  daoClasses = new Class[numTypes];
  for (int i = 0; i < numTypes; i++) {
    daoClasses[i] = (Class<?>) typeArguments(typeArguments[i], ContentStoreSupport.class)[0];
  }

  // combine store and DAO types to get the factory 'spec' for Assisted-Inject
  Type[] factorySpec = new Type[numTypes * 2];
  System.arraycopy(typeArguments, 0, factorySpec, 0, numTypes);
  System.arraycopy(daoClasses, 0, factorySpec, numTypes, numTypes);

  // apply spec to our Assisted-Inject generic template to get the required factory API
  Type factoryType = Types.newParameterizedType(FormatStoreFactory.class, factorySpec);

  Named qualifier = getClass().getAnnotation(Named.class);
  checkArgument(qualifier != null && qualifier.value().length() > 0,
      getClass() + " must be annotated with @Named(\"myformat\")");

  factoryKey = Key.get(factoryType, qualifier);
}
 
Example 3
public void addGenericBinding(
        final Type genericClass,
        final Class to,
        final Type... genericClassParams)
{
    if (ObjectUtils.anyNull(genericClass, genericClassParams, to))
        throw new NullPointerException();

    this.bindings.add(new BindingAction()
    {
        @Override
        public void bind(Binder b)
        {
            ParameterizedType pt = Types.newParameterizedType(genericClass, genericClassParams);
            Key k = Key.get(TypeLiteral.get(pt));
            b.bind(k).to(to);
        }
    });
}
 
Example 4
public void addGenericBinding(
        final Type genericClass,
        final Object to,
        final Type... genericClassParams)
{
    if (ObjectUtils.anyNull(genericClass, genericClassParams, to))
        throw new NullPointerException();

    this.bindings.add(new BindingAction()
    {
        @Override
        public void bind(Binder b)
        {
            ParameterizedType pt = Types.newParameterizedType(genericClass, genericClassParams);
            Key k = Key.get(TypeLiteral.get(pt));
            b.bind(k).toInstance(to);
        }
    });
}
 
Example 5
@Override
public List<Node> marshalParameters(Algorithm alg, Document doc) throws UnsupportedAlgorithmException
{
    AlgorithmParametersMarshaller marshaller;
    try
    {
        ParameterizedType pt = Types.newParameterizedType(AlgorithmParametersMarshaller.class, alg.getClass());
        marshaller = (AlgorithmParametersMarshaller) injector.getInstance(Key.get(TypeLiteral.get(pt)));
    } catch (RuntimeException ex)
    {
        throw new UnsupportedAlgorithmException("AlgorithmParametersMarshaller not available", alg.getUri(), ex);
    }

    List<Node> params = marshaller.marshalParameters(alg, doc);
    if (params != null && params.isEmpty())
    {
        throw new IllegalArgumentException(String.format("Parameter marshaller returned empty parameter list for algorithm %s", alg.getUri()));
    }
    return params;
}
 
Example 6
Source Project: seed   Source File: GenericBindingStrategy.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void resolve(Binder binder) {
    // Bind all the possible types for one class or interface.
    // For instance: Repository<Customer,String>, Repository<Order, Long>, etc.
    FactoryModuleBuilder guiceFactoryBuilder = new FactoryModuleBuilder();

    if (constructorParamsMap != null) {
        for (Map.Entry<Type[], Key<?>> entry : constructorParamsMap.entrySet()) {
            bindKey(binder, guiceFactoryBuilder, entry.getKey(), entry.getValue());
        }
    } else {
        for (Type[] params : constructorParams) {
            bindKey(binder, guiceFactoryBuilder, params, null);
        }
    }

    TypeLiteral<?> guiceAssistedFactory = TypeLiteral.get(
            Types.newParameterizedType(DEFAULT_IMPL_FACTORY_CLASS, genericImplClass));
    binder.install(guiceFactoryBuilder.build(guiceAssistedFactory));
}
 
Example 7
Source Project: wisdom   Source File: HttpParameterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHeaderWithMultipleValues() {
    Request request = mock(Request.class);
    Context ctx = mock(Context.class);
    when(ctx.request()).thenReturn(request);
    when(request.data()).thenReturn(Collections.<String, Object>emptyMap());
    when(ctx.headers("header")).thenReturn(ImmutableList.of("value1", "value2"));
    when(ctx.header("header")).thenReturn("value1");
    when(ctx.headers("count")).thenReturn(ImmutableList.of("1"));
    when(ctx.header("count")).thenReturn("1");
    ActionParameter argument = new ActionParameter("header", Source.HTTP, List.class, Types.listOf(String.class));
    assertThat((List) Bindings.create(argument, ctx, engine)).contains("value1", "value2");
    argument = new ActionParameter("header", Source.HTTP, String.class, null);
    assertThat(Bindings.create(argument, ctx, engine)).isEqualTo("value1");
    argument = new ActionParameter("count", Source.HTTP, Integer.class);
    assertThat(Bindings.create(argument, ctx, engine)).isEqualTo(1);
    argument = new ActionParameter("count", Source.HTTP, List.class, Types.listOf(Integer.class));
    assertThat((List) Bindings.create(argument, ctx, engine)).containsExactly(1);
}
 
Example 8
Source Project: druid-api   Source File: JsonConfigProvider.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> void bind(
    Binder binder,
    String propertyBase,
    Class<T> classToProvide,
    Class<? extends Annotation> annotation
)
{
  bind(
      binder,
      propertyBase,
      classToProvide,
      Key.get(classToProvide, annotation),
      (Key) Key.get(Types.newParameterizedType(Supplier.class, classToProvide), annotation)
  );
}
 
Example 9
Source Project: druid-api   Source File: JsonConfigProvider.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> void bindInstance(
    Binder binder,
    Key<T> bindKey,
    T instance
)
{
  binder.bind(bindKey).toInstance(instance);

  final ParameterizedType supType = Types.newParameterizedType(Supplier.class, bindKey.getTypeLiteral().getType());
  final Key supplierKey;

  if (bindKey.getAnnotationType() != null) {
    supplierKey = Key.get(supType, bindKey.getAnnotationType());
  }
  else if (bindKey.getAnnotation() != null) {
    supplierKey = Key.get(supType, bindKey.getAnnotation());
  }
  else {
    supplierKey = Key.get(supType);
  }

  binder.bind(supplierKey).toInstance(Suppliers.<T>ofInstance(instance));
}
 
Example 10
Source Project: proteus   Source File: ConfigModule.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void bindConfig(final Config config)
{
    traverse(this.binder(), "", config.root());

    for (Entry<String, ConfigValue> entry : config.entrySet()) {
        String name = entry.getKey();
        Named named = Names.named(name);
        Object value = entry.getValue().unwrapped();

        if (value instanceof List) {
            List<Object> values = (List<Object>) value;
            Type listType = (values.size() == 0)
                    ? String.class
                    : Types.listOf(values.iterator().next().getClass());
            Key<Object> key = (Key<Object>) Key.get(listType, Names.named(name));

            this.binder().bind(key).toInstance(values);
        } else {
            this.binder().bindConstant().annotatedWith(named).to(value.toString());
        }
    }

    Config referenceConfig = ConfigFactory.load(ConfigFactory.defaultReference());

    this.config = ConfigFactory.load(config).withFallback(referenceConfig);

    log.debug(this.config.toString());

    this.binder().bind(Config.class).toInstance(config);
}
 
Example 11
private void initRepeatedConverter(Type genericParamType) {
  if (genericParamType instanceof JavaType) {
    genericParamType = Types.newParameterizedType(((JavaType) genericParamType).getRawClass(),
        ((JavaType) genericParamType).getContentType());
  }
  converter = partsToTargetConverters.get(genericParamType);
}
 
Example 12
Source Project: emodb   Source File: JobStatusUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypeReference<JobStatus<?, ?>> load(final JobType<?, ?> jobType)
        throws Exception {
    return new TypeReference<JobStatus<?, ?>>() {
        private Type _type = Types.newParameterizedType(
                JobStatus.class, jobType.getRequestType(), jobType.getResultType());

        @Override
        public Type getType() {
            return _type;
        }
    };
}
 
Example 13
Source Project: xtext-core   Source File: GenericModuleTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testParameterizedTypes() throws Exception {
	ParameterizedTypeModule module = new ParameterizedTypeModule();
	Injector createInjector = Guice.createInjector(module);
	Object bindToType = createInjector.getInstance(Key.get(Types.newParameterizedType(Comparable.class, ParameterizedTypeModule.X.class)));
	assertTrue(bindToType instanceof ParameterizedTypeModule.X);
	Object bindToInstance = createInjector.getInstance(Key.get(Types.newParameterizedType(Iterator.class, ParameterizedTypeModule.X.class)));
	assertSame(module.BIND_X,bindToInstance);
	Object provide = createInjector.getInstance(Key.get(Types.newParameterizedType(Iterable.class, ParameterizedTypeModule.X.class)));
	assertSame(module.PROVIDE_X,provide );
}
 
Example 14
@Override
public <TProp extends QualifyingProperty> PropertyDataObjectGenerator<TProp> getGenerator(
        TProp p) throws PropertyDataGeneratorNotAvailableException
{
    try
    {
        ParameterizedType pt = Types.newParameterizedType(PropertyDataObjectGenerator.class, p.getClass());
        return (PropertyDataObjectGenerator)injector.getInstance(Key.get(TypeLiteral.get(pt)));
    } catch (RuntimeException ex)
    {
        throw new PropertyDataGeneratorNotAvailableException(p, ex);
    }
}
 
Example 15
private <TData extends PropertyDataObject> void bindBuiltInVerifier(
        Class<TData> dataObjectClass,
        Class<? extends QualifyingPropertyVerifier<TData>> verifierClass)
{
    ParameterizedType pt = Types.newParameterizedType(QualifyingPropertyVerifier.class, dataObjectClass);
    TypeLiteral<QualifyingPropertyVerifier<TData>> tl = (TypeLiteral<QualifyingPropertyVerifier<TData>>)TypeLiteral.get(pt);
    
    bind(tl).to(verifierClass);
    bind(tl).annotatedWith(BuiltIn.class).to(verifierClass);
}
 
Example 16
Source Project: james-project   Source File: LifeCycleStageModule.java    License: Apache License 2.0 5 votes vote down vote up
private static <A extends Annotation> TypeLiteral<Stager<A>> type(Class<A> stage) {
    ParameterizedType parameterizedType = Types.newParameterizedTypeWithOwner(null, Stager.class, stage);
    //noinspection unchecked
    @SuppressWarnings("unchecked") // TODO
        TypeLiteral<Stager<A>> stagerType = (TypeLiteral<Stager<A>>) TypeLiteral.get(parameterizedType);
    return stagerType;
}
 
Example 17
@SuppressWarnings("unchecked")
private <S extends Specification<?>> Key<SpecificationConverter<S, C, T>> buildKey(
        Class<? extends Specification> specificationClass) {
    if (qualifier != null) {
        return Key.get((TypeLiteral<SpecificationConverter<S, C, T>>) TypeLiteral.get(
                Types.newParameterizedType(SpecificationConverter.class, specificationClass, contextClass,
                        targetClass)), qualifier);
    } else {
        return Key.get((TypeLiteral<SpecificationConverter<S, C, T>>) TypeLiteral.get(
                Types.newParameterizedType(SpecificationConverter.class, specificationClass, contextClass,
                        targetClass)));
    }
}
 
Example 18
Source Project: business   Source File: SpecificationModule.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Key<T> buildKey(Class<T> someInterface, Class<? extends T> someClass) {
    return getQualifier(someClass).map(annotation -> Key.get((TypeLiteral<T>) TypeLiteral.get(
            Types.newParameterizedType(someInterface, resolveGenerics(someInterface, someClass))), annotation))
            .orElse(Key.get((TypeLiteral<T>) TypeLiteral.get(
                    Types.newParameterizedType(someInterface, resolveGenerics(someInterface, someClass)))));
}
 
Example 19
Source Project: business   Source File: DefaultFactoryCollector.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private boolean isCandidate(Type type) {
    boolean result = false;
    if (type instanceof Class<?>) {
        result = BusinessSpecifications.PRODUCIBLE.isSatisfiedBy((Class<?>) type);
    } else if (type instanceof ParameterizedType) {
        result = BusinessSpecifications.PRODUCIBLE.isSatisfiedBy(
                (Class<?>) ((ParameterizedType) type).getRawType());
    }
    return result && !bindings.containsKey(Key.get(Types.newParameterizedType(Factory.class, type)));
}
 
Example 20
Source Project: business   Source File: DomainRegistryImpl.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private void checkType(Type type, Specification<Class<?>> spec, ErrorCode errorCode) {
    Class<?> rawClass = org.seedstack.shed.reflect.Types.rawClassOf(type);
    if (!spec.isSatisfiedBy(rawClass)) {
        throw BusinessException.createNew(errorCode)
                .put("class", rawClass);
    }
}
 
Example 21
@Override
public void resolve(Binder binder) {
    for (Class<? extends T> impl : implementations) {
        if (Arrays.stream(impl.getMethods()).anyMatch(m -> isAbstract(m.getModifiers()))) {
            LOGGER.warn("Skipping default repository implementation {}: abstract methods are still present",
                    impl.getName());
        } else {
            Key<T> key = BusinessUtils.getQualifier(impl)
                    .map(qualifier -> Key.get(repositoryInterface, qualifier))
                    .orElseThrow(() -> new IllegalStateException("Missing qualifier on implementation" + impl));

            if (defaultKey != null) {
                binder.bind(repositoryInterface).to(defaultKey);
            }

            Provider<T> provider = new GenericGuiceProvider<>(impl, generics);
            binder.requestInjection(provider);
            binder.bind(key).toProvider(provider);

            FactoryModuleBuilder guiceFactoryBuilder = new FactoryModuleBuilder();
            guiceFactoryBuilder.implement(key, impl);
            binder.install(guiceFactoryBuilder.build(
                    TypeLiteral.get(Types.newParameterizedType(FACTORY_CLASS, impl))
            ));
        }
    }
}
 
Example 22
Source Project: seed   Source File: BindingUtils.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Resolve the key for injectee class, including qualifier from implClass and resolved type variables.
 * <p>
 * Useful when we can not resolve type variable from one implementation.
 *
 * @param injecteeClass       the injectee class
 * @param genericImplClass    the generic implementation
 * @param typeVariableClasses the type variable classes
 * @return {@link com.google.inject.Key}
 */
@SuppressWarnings("unchecked")
public static <T> Key<T> resolveKey(Class<T> injecteeClass, Class<? extends T> genericImplClass,
        Type... typeVariableClasses) {
    Optional<Annotation> qualifier = Annotations.on(genericImplClass)
            .findAll()
            .filter(AnnotationPredicates.annotationAnnotatedWith(Qualifier.class, false))
            .findFirst();
    TypeLiteral<T> genericInterface = (TypeLiteral<T>) TypeLiteral.get(
            Types.newParameterizedType(injecteeClass, typeVariableClasses));
    return qualifier.map(annotation -> Key.get(genericInterface, annotation)).orElseGet(
            () -> Key.get(genericInterface));
}
 
Example 23
Source Project: seed   Source File: GenericGuiceProvider.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T get() {
    Key<GenericGuiceFactory<T>> factoryKey = (Key<GenericGuiceFactory<T>>) Key.get(
            TypeLiteral.get(
                    Types.newParameterizedType(GenericGuiceFactory.class, defaultImplClass)
            ));
    GenericGuiceFactory<T> genericGuiceFactory = injector.getInstance(factoryKey);
    return genericGuiceFactory.createResolvedInstance(genericClasses);
}
 
Example 24
Source Project: seed   Source File: ApplicationImpl.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> ClassConfiguration<T> getConfiguration(Class<T> someClass) {
    ClassConfiguration<T> classConfiguration = ClassConfiguration.empty(someClass);
    StringBuilder sb = new StringBuilder(CLASSES_CONFIGURATION_PREFIX);
    for (String part : someClass.getName().split("\\.")) {
        sb.append(".").append(part);
        coffig.getOptional(Types.newParameterizedType(ClassConfiguration.class, someClass), sb.toString())
                .ifPresent(o -> classConfiguration.merge((ClassConfiguration<T>) o));
    }
    return classConfiguration;
}
 
Example 25
Source Project: wisdom   Source File: HttpParameterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingHeader() {
    Request request = mock(Request.class);
    Context ctx = mock(Context.class);
    when(ctx.request()).thenReturn(request);
    when(request.data()).thenReturn(Collections.<String, Object>emptyMap());
    when(ctx.headers("header")).thenReturn(ImmutableList.of("value1", "value2"));
    when(ctx.header("header")).thenReturn("value1");
    when(ctx.headers("count")).thenReturn(ImmutableList.of("1"));
    when(ctx.header("count")).thenReturn("1");
    ActionParameter argument = new ActionParameter("missing", Source.HTTP, List.class, Types.listOf(String.class));
    assertThat((List) Bindings.create(argument, ctx, engine)).isEmpty();
    argument = new ActionParameter("missing", Source.HTTP, String.class, null);
    assertThat((List) Bindings.create(argument, ctx, engine)).isNull();
}
 
Example 26
Source Project: wisdom   Source File: HttpParameterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testHeaderWithoutName() {
    Context ctx = mock(Context.class);
    when(ctx.headers("header")).thenReturn(ImmutableList.of("value1", "value2"));
    when(ctx.header("header")).thenReturn("value1");
    when(ctx.headers("count")).thenReturn(ImmutableList.of("1"));
    when(ctx.header("count")).thenReturn("1");
    ActionParameter argument = new ActionParameter(null, Source.HTTP, List.class, Types.listOf(String.class));
    Bindings.create(argument, ctx, engine);
    fail("Should have failed");
}
 
Example 27
Source Project: wisdom   Source File: HttpParameterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testHeaderWithEmptyName() {
    Context ctx = mock(Context.class);
    when(ctx.headers("header")).thenReturn(ImmutableList.of("value1", "value2"));
    when(ctx.header("header")).thenReturn("value1");
    when(ctx.headers("count")).thenReturn(ImmutableList.of("1"));
    when(ctx.header("count")).thenReturn("1");
    ActionParameter argument = new ActionParameter("", Source.HTTP, List.class, Types.listOf(String.class));
    Bindings.create(argument, ctx, engine);
    fail("Should have failed");
}
 
Example 28
Source Project: wisdom   Source File: HttpParameterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestScopeInjectionWithMultipleValues() {
    Request request = mock(Request.class);
    Context ctx = mock(Context.class);
    when(ctx.request()).thenReturn(request);
    when(request.data()).thenReturn(ImmutableMap.<String, Object>of(
            "data", ImmutableList.of("value1", "value2"),
            "key", "value",
            "count", 1
    ));
    ActionParameter argument = new ActionParameter("data", Source.HTTP, List.class, Types.listOf(String.class));
    assertThat((List) Bindings.create(argument, ctx, engine)).contains("value1", "value2");
}
 
Example 29
Source Project: wisdom   Source File: HttpParameterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingRequestScopeValue() {
    Request request = mock(Request.class);
    Context ctx = mock(Context.class);
    when(ctx.request()).thenReturn(request);
    when(request.data()).thenReturn(ImmutableMap.<String, Object>of(
            "data", ImmutableList.of("value1", "value2"),
            "key", "value",
            "count", 1
    ));
    ActionParameter argument = new ActionParameter("missing", Source.HTTP, List.class, Types.listOf(String.class));
    assertThat((List) Bindings.create(argument, ctx, engine)).isEmpty();
    argument = new ActionParameter("missing", Source.HTTP, String.class, null);
    assertThat((List) Bindings.create(argument, ctx, engine)).isNull();
}
 
Example 30
Source Project: wisdom   Source File: HttpParameterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testRequestScopeInjectionWithoutName() {
    Request request = mock(Request.class);
    Context ctx = mock(Context.class);
    when(ctx.request()).thenReturn(request);
    when(request.data()).thenReturn(ImmutableMap.<String, Object>of(
            "data", ImmutableList.of("value1", "value2"),
            "key", "value",
            "count", 1
    ));
    ActionParameter argument = new ActionParameter(null, Source.HTTP, List.class, Types.listOf(String.class));
    Bindings.create(argument, ctx, engine);
    fail("Should have failed");
}