com.google.inject.util.Types Java Examples
The following examples show how to use
com.google.inject.util.Types.
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: GenericBindingStrategy.java From seed with Mozilla Public License 2.0 | 6 votes |
@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 #2
Source File: ApiImplicitParamProcessor.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@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 #3
Source File: AlgorithmsParametersMarshallingProviderImpl.java From xades4j with GNU Lesser General Public License v3.0 | 6 votes |
@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 #4
Source File: XadesProfileCore.java From xades4j with GNU Lesser General Public License v3.0 | 6 votes |
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
Source File: JsonConfigProvider.java From druid-api with Apache License 2.0 | 6 votes |
@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 #6
Source File: JsonConfigProvider.java From druid-api with Apache License 2.0 | 6 votes |
@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 #7
Source File: XadesProfileCore.java From xades4j with GNU Lesser General Public License v3.0 | 6 votes |
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 #8
Source File: BespokeFormatStoreModule.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
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 #9
Source File: HttpParameterTest.java From wisdom with Apache License 2.0 | 6 votes |
@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 #10
Source File: ApplicationImpl.java From seed with Mozilla Public License 2.0 | 5 votes |
@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 #11
Source File: HttpParameterTest.java From wisdom with Apache License 2.0 | 5 votes |
@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 #12
Source File: HttpParameterTest.java From wisdom with Apache License 2.0 | 5 votes |
@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 #13
Source File: HttpParameterTest.java From wisdom with Apache License 2.0 | 5 votes |
@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 #14
Source File: BaseSpecificationTranslator.java From business with Mozilla Public License 2.0 | 5 votes |
@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 #15
Source File: HttpParameterTest.java From wisdom with Apache License 2.0 | 5 votes |
@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 #16
Source File: HttpParameterTest.java From wisdom with Apache License 2.0 | 5 votes |
@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 #17
Source File: Spoofax.java From spoofax with Apache License 2.0 | 5 votes |
/** * Instantiate the MetaBorg API with a Spoofax implementation. * * @param loader * Module plugin loader to use. * @param module * Spoofax module to use. * @param additionalModules * Additional modules to use. * * @throws MetaborgException * When loading plugins or dependency injection fails. */ public Spoofax(IModulePluginLoader loader, SpoofaxModule module, Module... additionalModules) throws MetaborgException { super(ISpoofaxInputUnit.class, ISpoofaxParseUnit.class, ISpoofaxAnalyzeUnit.class, ISpoofaxAnalyzeUnitUpdate.class, Types.newParameterizedType(ISpoofaxTransformUnit.class, Types.subtypeOf(Object.class)), Types.newParameterizedType(ISpoofaxTransformUnit.class, ISpoofaxParseUnit.class), Types.newParameterizedType(ISpoofaxTransformUnit.class, ISpoofaxAnalyzeUnit.class), IStrategoTerm.class, loader, module, additionalModules); this.unitService = injector.getInstance(ISpoofaxUnitService.class); this.syntaxService = injector.getInstance(ISpoofaxSyntaxService.class); this.analysisService = injector.getInstance(ISpoofaxAnalysisService.class); this.transformService = injector.getInstance(ISpoofaxTransformService.class); this.builder = injector.getInstance(ISpoofaxBuilder.class); this.processorRunner = injector.getInstance(ISpoofaxProcessorRunner.class); this.parseResultProcessor = injector.getInstance(ISpoofaxParseResultProcessor.class); this.analysisResultProcessor = injector.getInstance(ISpoofaxAnalysisResultProcessor.class); this.tracingService = injector.getInstance(ISpoofaxTracingService.class); this.categorizerService = injector.getInstance(ISpoofaxCategorizerService.class); this.stylerService = injector.getInstance(ISpoofaxStylerService.class); this.hoverService = injector.getInstance(ISpoofaxHoverService.class); this.resolverService = injector.getInstance(ISpoofaxResolverService.class); this.outlineService = injector.getInstance(ISpoofaxOutlineService.class); this.completionService = injector.getInstance(ISpoofaxCompletionService.class); this.termFactory = injector.getInstance(ITermFactory.class); this.strategoRuntimeService = injector.getInstance(IStrategoRuntimeService.class); this.strategoCommon = injector.getInstance(IStrategoCommon.class); }
Example #18
Source File: GenericGuiceProvider.java From seed with Mozilla Public License 2.0 | 5 votes |
@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 #19
Source File: BindingUtils.java From seed with Mozilla Public License 2.0 | 5 votes |
/** * 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 #20
Source File: SpecificationModule.java From business with Mozilla Public License 2.0 | 5 votes |
@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 #21
Source File: DefaultFactoryCollector.java From business with Mozilla Public License 2.0 | 5 votes |
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 #22
Source File: DomainRegistryImpl.java From business with Mozilla Public License 2.0 | 5 votes |
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 #23
Source File: DefaultRepositoryStrategy.java From business with Mozilla Public License 2.0 | 5 votes |
@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 #24
Source File: LifeCycleStageModule.java From james-project with Apache License 2.0 | 5 votes |
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 #25
Source File: DefaultVerificationBindingsModule.java From xades4j with GNU Lesser General Public License v3.0 | 5 votes |
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 #26
Source File: PropertyDataGeneratorsMapperImpl.java From xades4j with GNU Lesser General Public License v3.0 | 5 votes |
@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 #27
Source File: GenericModuleTest.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@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 #28
Source File: HttpParameterTest.java From wisdom with Apache License 2.0 | 5 votes |
@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"); }
Example #29
Source File: JobStatusUtil.java From emodb with Apache License 2.0 | 5 votes |
@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 #30
Source File: FormProcessorCreator.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
private void initRepeatedConverter(Type genericParamType) { if (genericParamType instanceof JavaType) { genericParamType = Types.newParameterizedType(((JavaType) genericParamType).getRawClass(), ((JavaType) genericParamType).getContentType()); } converter = partsToTargetConverters.get(genericParamType); }