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

The following are top voted examples for showing how to use com.google.inject.util.Types. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ice   File: ConfigDynamicMBean.java   Source Code and License 6 votes vote down vote up
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
    ConfigDescriptor desc = descLookupByAttributeName.get(attribute.getName());
    if (desc == null) {
        log.warn("Attribute Set name={} value={} requested on MXBean {}, but no matching configDescriptor found.",
            attribute.getName(), attribute.getValue(), mbeanName);
        throw new AttributeNotFoundException();
    }

    // get appropriate config value converter and test the conversion for immediate error feedback
    ConfigValueConverter<?> converter = (ConfigValueConverter<?>) this.injectorRef.get().getInstance(Key.get(Types.newParameterizedType(ConfigValueConverter.class, desc.getConfigType())));
    String strValue = attribute.getValue() == null ? null : attribute.getValue().toString();
    try {
        converter.apply(strValue);
    }
    catch (Exception ex) {
        log.warn("Attribute Set name={} value={} requested on MXBean {}, but value failed to convert to type {}",
            attribute.getName(), attribute.getValue(), mbeanName, desc.getConfigType().getTypeName());
        throw new InvalidAttributeValueException("Failed to parse value: " + ex.getMessage());
    }

    // emit event
    this.eventSink.fireEvent(desc.getConfigName(), Optional.ofNullable(strValue));
}
 
Example 2
Project: ice   File: PropertyAccessor.java   Source Code and License 6 votes vote down vote up
public static <C> PrivateModule module(final PropertyIdentifier propertyIdentifier, final ConfigDescriptor desc)
{
    return new PrivateModule()
    {
        @Override
        protected void configure()
        {
            // Alias the private module scoped bindings for the un-annotated ConstantValuePropertyAccessor and PropertyIdentifier to globally scoped and annotated ones.
            // Intent here is to make the implementation of this nice and guicified but support a number of different instances.
            bind(ConstantValuePropertyAccessor.class).to(Key.get(ConstantValuePropertyAccessor.class, propertyIdentifier));
            bind(PropertyIdentifier.class).to(Key.get(PropertyIdentifier.class, propertyIdentifier));

            TypeLiteral<PropertyAccessor<C>> accessorType = (TypeLiteral<PropertyAccessor<C>>) TypeLiteral.get(Types.newParameterizedType(PropertyAccessor.class, desc.getConfigType()));
            bind(Key.get(accessorType, propertyIdentifier)).to(accessorType).in(Scopes.SINGLETON);
            expose(Key.get(accessorType, propertyIdentifier));
        }
    };
}
 
Example 3
Project: ice   File: ConfigDescriptorFactory.java   Source Code and License 6 votes vote down vote up
private ConfigDescriptor internalBuildDescriptor(Method method, Optional<String> scopeOpt, Optional<String> defaultValue)
{
    String configName = namingStrategy.methodToFlatName(method, scopeOpt);

    DefaultValue dv = method.getAnnotation(DefaultValue.class);
    NoDefaultValue ndv = method.getAnnotation(NoDefaultValue.class);
    Class<?> innerClass = null;
    if (dv != null && dv.innerType() != None.class) {
        innerClass = dv.innerType();
    }
    else if (ndv != null && ndv.innerType() != None.class) {
        innerClass = ndv.innerType();
    }

    // Only using the base return type to determine isObservable. Validation is ensuring the other requirements.
    boolean isObservable = Observable.class.isAssignableFrom(method.getReturnType());

    Type configType = innerClass == null
        ? ensureBoxedType(method.getReturnType())
        : Types.newParameterizedType(ensureBoxedType(method.getReturnType()), innerClass);

    return new ConfigDescriptor(method, configName, configType, isObservable, scopeOpt, defaultValue);
}
 
Example 4
Project: Orchid   File: OrchidContextImpl.java   Source Code and License 6 votes vote down vote up
public <T> Set<T> resolveSet(Class<T> clazz) {
    Injector injector = getInjector();
    try {
        TypeLiteral<Set<T>> lit = (TypeLiteral<Set<T>>) TypeLiteral.get(Types.setOf(clazz));
        Key<Set<T>> key = Key.get(lit);
        Set<T> bindings = injector.getInstance(key);

        if (bindings != null) {
            return bindings;
        }
    }
    catch (Exception e) {

    }

    return new TreeSet<>();
}
 
Example 5
Project: salta   File: TypeLiteralTypeResolutionTest.java   Source Code and License 6 votes vote down vote up
public void testResolve() {
    TypeLiteral<?> typeResolver = TypeLiteral.get(StringIntegerMap.class);
    assertEquals(String.class, typeResolver.resolveType(mapK));

    typeResolver = new TypeLiteral<Map<String, Integer>>() {
    };
    assertEquals(String.class, typeResolver.resolveType(mapK));
    assertEquals(Types.mapOf(String.class, Integer.class),
            typeResolver.getSupertype(Map.class).getType());

    typeResolver = new TypeLiteral<BetterMap<String, Integer>>() {
    };
    assertEquals(String.class, typeResolver.resolveType(mapK));

    typeResolver = new TypeLiteral<BestMap<String, Integer>>() {
    };
    assertEquals(String.class, typeResolver.resolveType(mapK));

    typeResolver = TypeLiteral.get(StringIntegerHashMap.class);
    assertEquals(String.class, typeResolver.resolveType(mapK));
    assertEquals(String.class, typeResolver.resolveType(hashMapK));
    assertEquals(entryStringInteger, typeResolver.resolveType(setEntryKV));
    assertEquals(Object.class,
            typeResolver.getSupertype(Object.class).getType());
}
 
Example 6
Project: salta   File: ProviderMethodsTest.java   Source Code and License 6 votes vote down vote up
public void testGenericProviderMethods() {
    Injector injector = Guice
            .createInjector(new ProvideTs<String>("A", "B") {
            }, new ProvideTs<Integer>(1, 2) {
            });

    assertEquals("A", injector
            .getInstance(Key.get(String.class, Names.named("First"))));
    assertEquals("B", injector
            .getInstance(Key.get(String.class, Names.named("Second"))));
    assertEquals(ImmutableSet.of("A", "B"),
            injector.getInstance(Key.get(Types.setOf(String.class))));

    assertEquals(1,
            injector.getInstance(
                    Key.get(Integer.class, Names.named("First")))
            .intValue());
    assertEquals(2,
            injector.getInstance(
                    Key.get(Integer.class, Names.named("Second")))
            .intValue());
    assertEquals(ImmutableSet.of(1, 2),
            injector.getInstance(Key.get(Types.setOf(Integer.class))));
}
 
Example 7
Project: salta   File: TypeLiteralTest.java   Source Code and License 6 votes vote down vote up
public void testWithWildcardType()
        throws NoSuchFieldException, IOException {
    TypeLiteral<?> a = TypeLiteral
            .get(getClass().getField("wildcardExtends").getGenericType());
    TypeLiteral<?> b = TypeLiteral
            .get(Types.listOf(Types.subtypeOf(CharSequence.class)));
    TypeLiteral<?> c = new TypeLiteral<List<? extends CharSequence>>() {
    };
    assertEqualsBothWays(a, b);
    assertEqualsBothWays(b, c);
    assertEquals("java.util.List<? extends java.lang.CharSequence>",
            a.toString());
    assertEquals("java.util.List<? extends java.lang.CharSequence>",
            b.toString());
    assertEquals("java.util.List<? extends java.lang.CharSequence>",
            c.toString());
    assertNotSerializable(a);
    assertNotSerializable(b);
    assertNotSerializable(c);
}
 
Example 8
Project: bootique   File: JsonNodeConfigurationFactoryProviderIT.java   Source Code and License 6 votes vote down vote up
@Test
public void testLoadConfiguration_JsonYaml() {

	BQRuntime runtime = testFactory.app("--config=http://127.0.0.1:12025/test1.json",
			"--config=http://127.0.0.1:12025/test1.yml").createRuntime();

	JsonNodeConfigurationFactoryProvider provider = new JsonNodeConfigurationFactoryProvider(
			runtime.getInstance(ConfigurationSource.class), runtime.getInstance(Environment.class),
			runtime.getInstance(JacksonService.class), runtime.getBootLogger(),
               runtime.getInstance(Key.get((TypeLiteral<Set<OptionMetadata>>) TypeLiteral.get(Types.setOf(OptionMetadata.class)))),
			Collections.emptySet(),
               runtime.getInstance(Cli.class));

	JsonNode config = provider.loadConfiguration(Collections.emptyMap(), Collections.emptyMap());
	assertEquals("{\"x\":1,\"a\":\"b\"}", config.toString());
}
 
Example 9
Project: xades4j   File: XadesProfileCore.java   Source Code and License 6 votes vote down vote up
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 10
Project: xades4j   File: XadesProfileCore.java   Source Code and License 6 votes vote down vote up
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 11
Project: xades4j   File: AlgorithmsParametersMarshallingProviderImpl.java   Source Code and License 6 votes vote down vote up
@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 12
Project: guice-old   File: MoreTypes.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an type that's appropriate for use in a key.
 *
 * <p>If the raw type of {@code typeLiteral} is a {@code javax.inject.Provider}, this returns a
 * {@code com.google.inject.Provider} with the same type parameters.
 *
 * <p>If the type is a primitive, the corresponding wrapper type will be returned.
 *
 * @throws ConfigurationException if {@code type} contains a type variable
 */
public static <T> TypeLiteral<T> canonicalizeForKey(TypeLiteral<T> typeLiteral) {
  Type type = typeLiteral.getType();
  if (!isFullySpecified(type)) {
    Errors errors = new Errors().keyNotFullySpecified(typeLiteral);
    throw new ConfigurationException(errors.getMessages());
  }

  if (typeLiteral.getRawType() == javax.inject.Provider.class) {
    ParameterizedType parameterizedType = (ParameterizedType) type;

    // the following casts are generally unsafe, but com.google.inject.Provider extends
    // javax.inject.Provider and is covariant
    @SuppressWarnings("unchecked")
    TypeLiteral<T> guiceProviderType = (TypeLiteral<T>) TypeLiteral.get(
        Types.providerOf(parameterizedType.getActualTypeArguments()[0]));
    return guiceProviderType;
  }

  @SuppressWarnings("unchecked")
  TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER.get(typeLiteral);
  return wrappedPrimitives != null
      ? wrappedPrimitives
      : typeLiteral;
}
 
Example 13
Project: cultivar_old   File: ServiceProviderModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() {
    when(providerBuilder.build()).thenReturn(provider);

    dependencies = new AbstractModule() {
        @Override
        protected void configure() {
            bind(
                    (Key<ServiceProviderBuilder<Void>>) Key.get(
                            Types.newParameterizedType(ServiceProviderBuilder.class, Void.class), Curator.class))
                    .toInstance(providerBuilder);

        }
    };

    inj = Guice.createInjector(
            dependencies,
            ServiceProviderModuleBuilder.create(Void.class).discovery(Curator.class)
                    .additionalFilter(instanceFilter1).additionalFilter(instanceFilter2)
                    .providerStrategy(providerStrategy).threadFactory(threadFactory)
                    .downInstancePolicy(downInstancePolicy).annotation(Curator.class).name("test").build());
}
 
Example 14
Project: fabricator   File: EmbeddedComponentManagerBinding.java   Source Code and License 6 votes vote down vote up
@Override
public boolean execute(String name, Object obj, ConfigurationNode node, Class<?> argType, Injector injector, Method method) throws Exception {
    TypeLiteral<ComponentManager<?>> managerLiteral = (TypeLiteral<ComponentManager<?>>) TypeLiteral.get(Types.newParameterizedType(ComponentManager.class, argType));
    Binding<ComponentManager<?>> managerBinding = injector.getExistingBinding(Key.get(managerLiteral));
    if (managerBinding != null) {
        ComponentManager<?> manager = managerBinding.getProvider().get();
        try {
            method.invoke(obj, manager.create(node));
            return true;
        }
        catch (Exception e) {
            throw new Exception(String.format(
                    "Unable to get component '%s' (%s) for property '%s' must be one of %s",
                    name, argType.getSimpleName(), propertyName, manager.getIds()), e);
        }
    }
    return false;    
}
 
Example 15
Project: jooby   File: RouteParamCollectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void paramToSet() throws ParseException {
  params(new RouteParamCollector().accept(expr("req -> {",
      "req.param(\"p1\").toSet();",
      "req.param(\"p2\").toSet(String.class);",
      "req.param(\"p3\").toSet(apps.model.Pet.class);",
      "}"), ctx()))
  .next(p -> {
    assertEquals("p1", p.name());
    assertEquals(Types.newParameterizedType(Set.class, String.class), p.type());
    assertEquals(null, p.value());
  })
  .next(p -> {
    assertEquals("p2", p.name());
    assertEquals(Types.newParameterizedType(Set.class, String.class), p.type());
    assertEquals(null, p.value());
  })
  .next(p -> {
    assertEquals("p3", p.name());
    assertEquals(Types.newParameterizedType(Set.class, Pet.class), p.type());
    assertEquals(null, p.value());
  });
}
 
Example 16
Project: guice-old   File: ThrowingProviderBinder.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
private Key<P> createKey() {
  TypeLiteral<P> typeLiteral;
  if (interfaceType.getTypeParameters().length == 1) {
    ParameterizedType type = Types.newParameterizedTypeWithOwner(
        interfaceType.getEnclosingClass(), interfaceType, valueType);
    typeLiteral = (TypeLiteral<P>) TypeLiteral.get(type);
  } else {
    typeLiteral = TypeLiteral.get(interfaceType);
  }

  if (annotation != null) {
    return Key.get(typeLiteral, annotation);
    
  } else if (annotationType != null) {
    return Key.get(typeLiteral, annotationType);
    
  } else {
    return Key.get(typeLiteral);
  }
}
 
Example 17
Project: jooby   File: MvcWebSocketTest.java   Source Code and License 6 votes vote down vote up
@Test
public void onListPojoMessage() throws Exception {
  Pojo pojo = new Pojo();
  new MockUnit(WebSocket.class, Injector.class, PojoListSocket.class, Binder.class, Mutant.class)
      .expect(childInjector(PojoListSocket.class))
      .expect(mutant(TypeLiteral.get(Types.listOf(Pojo.class)), ImmutableList.of(pojo)))
      .expect(unit -> {
        PojoListSocket socket = unit.get(PojoListSocket.class);
        socket.onMessage(ImmutableList.of(pojo));
      })
      .run(unit -> {
        new MvcWebSocket(unit.get(WebSocket.class), PojoListSocket.class)
            .onMessage(unit.get(Mutant.class));
      }, unit -> {
        unit.captured(Module.class).iterator().next().configure(unit.get(Binder.class));
      });
}
 
Example 18
Project: jooby   File: CaffeineCache.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static List<TypeLiteral> cacheType(final String name, final Object cache,
    final Type superclass) {
  Class[] ctypes;
  if (cache instanceof AsyncLoadingCache) {
    ctypes = new Class[]{AsyncLoadingCache.class };
  } else if (cache instanceof LoadingCache) {
    ctypes = new Class[]{LoadingCache.class, Cache.class };
  } else {
    ctypes = new Class[]{Cache.class };
  }
  List<TypeLiteral> result = new ArrayList<>(ctypes.length);
  for (Class ctype : ctypes) {
    if (name.equals("session")) {
      result.add(TypeLiteral.get(Types.newParameterizedType(ctype, String.class, Session.class)));
    } else {
      result.add(TypeLiteral.get(Types.newParameterizedType(ctype, types(superclass))));
    }
  }
  return result;
}
 
Example 19
Project: cultivar   File: NodeContainerModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getInstance_NodeContainerWithAnnotation_PropertyOverrideSetBefore_ReturnsPropertyOverrideNodeContainer() {

    PropertyReader.setProperties(ImmutableMap.of("foo", "foo"));

    Module module = NodeContainerModuleBuilder.create(String.class).annotation(Curator.class)
            .mapper(StringUTF8ByteArrayMapper.class).overrideProperty("foo").path("/dev/test").build();
    injector = Guice.createInjector(Stage.PRODUCTION, new AbstractModule() {
        @Override
        protected void configure() {
            bind(CuratorFramework.class).annotatedWith(Curator.class).toInstance(framework);
        }
    }, module);

    assertTrue(injector.getInstance(Key.get(Types.newParameterizedType(NodeContainer.class, String.class),
            Curator.class)) instanceof PropertyOverrideNodeContainer);
}
 
Example 20
Project: cultivar   File: ServiceProviderModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void createInjector_ServiceProviderBuilderBound_Succeeds() {

    Guice.createInjector(
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(
                            (Key<ServiceProviderBuilder<Void>>) Key.get(
                                    Types.newParameterizedType(ServiceProviderBuilder.class, Void.class),
                                    Curator.class)).toInstance(providerBuilder);

                }
            },
            ServiceProviderModuleBuilder.create(Void.class).discovery(Curator.class).annotation(Curator.class)
                    .name("test").build());
}
 
Example 21
Project: cultivar   File: RegistrationServiceModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void createInjector_DiscoveryDefinedAndScheduleDefinedSansExecutor_ReturnsNotNull() {

    assertNotNull(Guice.createInjector(
            RegistrationServiceModuleBuilder.create().targetAnnotation(Cultivar.class)
                    .discoveryAnnotation(Cultivar.class).provider(new ServiceInstanceProvider())
                    .updating(10, TimeUnit.SECONDS).build(), new AbstractModule() {
                @Override
                protected void configure() {
                    bind(
                            (Key<ServiceDiscovery<Void>>) Key.get(
                                    Types.newParameterizedType(ServiceDiscovery.class, Void.class),
                                    Cultivar.class)).toInstance(discovery);
                }
            }));
}
 
Example 22
Project: guice   File: TypeLiteralTypeResolutionTest.java   Source Code and License 6 votes vote down vote up
public void testResolve() {
  TypeLiteral<?> typeResolver = TypeLiteral.get(StringIntegerMap.class);
  assertEquals(String.class, typeResolver.resolveType(mapK));

  typeResolver = new TypeLiteral<Map<String, Integer>>() {};
  assertEquals(String.class, typeResolver.resolveType(mapK));
  assertEquals(
      Types.mapOf(String.class, Integer.class), typeResolver.getSupertype(Map.class).getType());

  typeResolver = new TypeLiteral<BetterMap<String, Integer>>() {};
  assertEquals(String.class, typeResolver.resolveType(mapK));

  typeResolver = new TypeLiteral<BestMap<String, Integer>>() {};
  assertEquals(String.class, typeResolver.resolveType(mapK));

  typeResolver = TypeLiteral.get(StringIntegerHashMap.class);
  assertEquals(String.class, typeResolver.resolveType(mapK));
  assertEquals(String.class, typeResolver.resolveType(hashMapK));
  assertEquals(entryStringInteger, typeResolver.resolveType(setEntryKV));
  assertEquals(Object.class, typeResolver.getSupertype(Object.class).getType());
}
 
Example 23
Project: guice   File: PrivateModuleTest.java   Source Code and License 6 votes vote down vote up
public void testParentBindingToPrivateLinkedJitBinding() {
  Injector injector = Guice.createInjector(new ManyPrivateModules());
  try {
    injector.getBinding(Key.get(Types.providerOf(List.class)));
    fail();
  } catch (ConfigurationException expected) {
    assertEquals(1, expected.getErrorMessages().size());
    assertContains(
        expected.toString(),
        "Unable to create binding for com.google.inject.Provider<java.util.List>.",
        "It was already configured on one or more child injectors or private modules",
        "bound at " + FailingPrivateModule.class.getName() + ".configure(",
        asModuleChain(ManyPrivateModules.class, FailingPrivateModule.class),
        "bound at " + SecondFailingPrivateModule.class.getName() + ".configure(",
        asModuleChain(ManyPrivateModules.class, SecondFailingPrivateModule.class),
        "If it was in a PrivateModule, did you forget to expose the binding?",
        "while locating com.google.inject.Provider<java.util.List>");
  }
}
 
Example 24
Project: guice-old   File: PrivateModuleTest.java   Source Code and License 6 votes vote down vote up
public void testParentBindingToPrivateLinkedJitBinding() {
  Injector injector = Guice.createInjector(new ManyPrivateModules());
  try {
    injector.getBinding(Key.get(Types.providerOf(List.class)));
    fail();
  } catch(ConfigurationException expected) {
    assertEquals(1, expected.getErrorMessages().size());
    assertContains(expected.toString(),
        "Unable to create binding for com.google.inject.Provider<java.util.List>.",
        "It was already configured on one or more child injectors or private modules",
        "bound at " + FailingPrivateModule.class.getName() + ".configure(",
        asModuleChain(ManyPrivateModules.class, FailingPrivateModule.class),
        "bound at " + SecondFailingPrivateModule.class.getName() + ".configure(",
        asModuleChain(ManyPrivateModules.class, SecondFailingPrivateModule.class),
        "If it was in a PrivateModule, did you forget to expose the binding?",
        "while locating com.google.inject.Provider<java.util.List>");
  }
}
 
Example 25
Project: jooby   File: RouteParamCollectorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void paramToList() throws ParseException {
  params(new RouteParamCollector().accept(expr("req -> {",
      "req.param(\"p1\").toList();",
      "req.param(\"p2\").toList(Integer.class);",
      "req.param(\"p3\").toList(apps.model.Pet.class);",
      "}"), ctx()))
  .next(p -> {
    assertEquals("p1", p.name());
    assertEquals(Types.newParameterizedType(List.class, String.class), p.type());
    assertEquals(null, p.value());
  })
  .next(p -> {
    assertEquals("p2", p.name());
    assertEquals(Types.newParameterizedType(List.class, Integer.class), p.type());
    assertEquals(null, p.value());
  })
  .next(p -> {
    assertEquals("p3", p.name());
    assertEquals(Types.newParameterizedType(List.class, Pet.class), p.type());
    assertEquals(null, p.value());
  });
}
 
Example 26
Project: cultivar   File: ServiceProviderModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() {
    when(providerBuilder.build()).thenReturn(provider);

    dependencies = new AbstractModule() {
        @Override
        protected void configure() {
            bind(
                    (Key<ServiceProviderBuilder<Void>>) Key.get(
                            Types.newParameterizedType(ServiceProviderBuilder.class, Void.class), Curator.class))
                    .toInstance(providerBuilder);

        }
    };

    inj = Guice.createInjector(
            dependencies,
            ServiceProviderModuleBuilder.create(Void.class).discovery(Curator.class)
                    .additionalFilter(instanceFilter1).additionalFilter(instanceFilter2)
                    .providerStrategy(providerStrategy).threadFactory(threadFactory)
                    .downInstancePolicy(downInstancePolicy).annotation(Curator.class).name("test").build());
}
 
Example 27
Project: jooby   File: TypeFromDoc.java   Source Code and License 6 votes vote down vote up
public static Optional<Type> parse(final Node node, final Context ctx, final String text) {
  Matcher matcher = TYPE.matcher(text);
  Type type = null;
  while (matcher.find()) {
    String link = matcher.group(1).trim();
    String stype = link.split("\\s+")[0];
    Optional<Type> resolvedType = ctx.resolveType(node, stype);
    if (resolvedType.isPresent()) {
      Type ittype = resolvedType.get();
      if (type != null) {
        type = Types.newParameterizedType(type, ittype);
      } else {
        type = ittype;
      }
    }
  }
  return Optional.ofNullable(type);
}
 
Example 28
Project: cultivar   File: ServiceProviderOverrideModuleBuilder.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Module build() {
    checkState(provider != null, "Provider must be provided.");
    checkState(targetAnnotation != null, "Target annotation must be set.");

    return new AbstractModule() {
        @Override
        protected void configure() {
            Key<ServiceProvider<T>> target = (Key<ServiceProvider<T>>) targetAnnotation.generateKey(Types
                    .newParameterizedType(ServiceProvider.class, payloadClass));

            Key<ServiceProviderManager<T>> manager = (Key<ServiceProviderManager<T>>) targetAnnotation
                    .generateKey(Types.newParameterizedType(ServiceProviderManager.class, payloadClass));

            bind(target).toInstance(provider);
            bind(manager).to(
                    (Key<ServiceProviderManager<T>>) Key.get(Types.newParameterizedType(
                            ControllableServiceProviderManager.class, payloadClass))).in(Singleton.class);
        }
    };
}
 
Example 29
Project: cultivar   File: RegistrationServiceModuleBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void createInjector_DiscoveryDefinedAndScheduleDefinedWithExecutor_ReturnsNotNull() {

    assertNotNull(Guice.createInjector(
            RegistrationServiceModuleBuilder.create().targetAnnotation(Cultivar.class)
                    .discoveryAnnotation(Cultivar.class).provider(new ServiceInstanceProvider())
                    .updating(10, TimeUnit.SECONDS, new ScheduledThreadPoolExecutor(1)).build(),
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(
                            (Key<ServiceDiscovery<Void>>) Key.get(
                                    Types.newParameterizedType(ServiceDiscovery.class, Void.class),
                                    Cultivar.class)).toInstance(discovery);
                }
            }));
}
 
Example 30
Project: Equella   File: ViewUrlModule.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("nls")
@Override
protected void configure()
{
	bindTracker(Types.newParameterizedType(AttachmentResourceExtension.class, IAttachment.class),
		"attachmentResource", "class").orderByParameter("order");
	bindTracker(AttachmentTreeExtension.class, "attachmentTree", "bean");
	bindTracker(ViewableItemResolverExtension.class, "viewableItemResolver", "bean").setIdParam("id");
}
 
Example 31
Project: Equella   File: ObjectExpressionDeserialiserTest.java   Source Code and License 5 votes vote down vote up
private static void setupBullshit()
{
	Injector injector = Guice.createInjector(new Module()
	{
		@SuppressWarnings({"unchecked", "nls"})
		@Override
		public void configure(Binder arg0)
		{
			arg0.bind(PluginService.class).toInstance(new FakePluginService());
			ParameterizedType type = Types.newParameterizedType(PluginTracker.class, SectionsConverter.class);
			TrackerProvider<SectionsConverter> trackerProvider = new TrackerProvider<SectionsConverter>(
				"", "", "")
			{
				@Override
				public PluginTracker<SectionsConverter> get()
				{
					return new FakePluginTracker();
				}
			};

			TypeLiteral<PluginTracker<SectionsConverter>> typeLiteral = (TypeLiteral<PluginTracker<SectionsConverter>>) TypeLiteral
				.get(type);
			LinkedBindingBuilder<PluginTracker<SectionsConverter>> bindingBuilder = arg0.bind(typeLiteral);
			bindingBuilder.toProvider(trackerProvider).in(Scopes.SINGLETON);
		}
	});
	injector.getInstance(Conversion.class);
}
 
Example 32
Project: Equella   File: PluginTrackerModule.java   Source Code and License 5 votes vote down vote up
protected <T> TrackerProvider<T> bindTracker(java.lang.reflect.Type typeParam, Annotation annotatedWith,
	String extensionPoint, String beanParameter)
{
	ParameterizedType type = Types.newParameterizedType(PluginTracker.class, typeParam);
	TrackerProvider<T> trackerProvider = new TrackerProvider<T>(getPluginId(), extensionPoint, beanParameter);
	@SuppressWarnings("unchecked")
	TypeLiteral<PluginTracker<T>> typeLiteral = (TypeLiteral<PluginTracker<T>>) TypeLiteral.get(type);
	LinkedBindingBuilder<PluginTracker<T>> bindingBuilder = bind(typeLiteral);
	if( annotatedWith != null )
	{
		bindingBuilder = ((AnnotatedBindingBuilder<PluginTracker<T>>) bindingBuilder).annotatedWith(annotatedWith);
	}
	bindingBuilder.toProvider(trackerProvider).in(Scopes.SINGLETON);
	return trackerProvider;
}
 
Example 33
Project: ice   File: ConfigDynamicMBean.java   Source Code and License 5 votes vote down vote up
public ConfigDynamicMBean(ConfigEventSink<String> eventSink, Injector injector, List<ConfigDescriptor> configDescriptors)
{
    checkNotNull(eventSink);
    checkNotNull(injector);
    checkNotNull(configDescriptors);
    checkArgument(!configDescriptors.isEmpty());

    this.mbeanName = descToBeanName(configDescriptors.get(0));
    this.eventSink = eventSink;
    this.injectorRef = new WeakReference<>(injector);
    this.providerLookupByAttributeName = Maps.newHashMap();
    this.descLookupByAttributeName = Maps.newHashMap();
    for (ConfigDescriptor desc : configDescriptors) {
        String attrName = desc.getMethod().getName();
        log.trace("MBean {} Found Attribute {}", mbeanName, attrName);

        // Add entry to descriptor lookup map
        this.descLookupByAttributeName.put(attrName, desc);

        // Add entry to provider lookup map
        TypeLiteral<PropertyAccessor<?>> accessorKey = (TypeLiteral<PropertyAccessor<?>>) TypeLiteral.get(Types.newParameterizedType(PropertyAccessor.class, desc.getConfigType()));
        this.providerLookupByAttributeName.put(attrName, injectorRef.get().getProvider(Key.get(accessorKey, ConfigSystem.getIdentifier(desc))));
    }

    MBeanAttributeInfo[] attributeInfos = configDescriptors.stream()
        .sorted(comparing(d -> d.getConfigName()))
        .map(ConfigDynamicMBean::descToAttributeInfo)
        .toArray(MBeanAttributeInfo[]::new);

    String className = configDescriptors.get(0).getMethod().getDeclaringClass().getDeclaringClass().getName();
    this.mbeanInfo = new MBeanInfo(className, "", attributeInfos, null, null, null);
}
 
Example 34
Project: ice   File: ConfigSystem.java   Source Code and License 5 votes vote down vote up
/**
 * Validates all static configurations (i.e. strings in your @DefaultValue annotations) which are found in the
 * injector in which ConfigSystem was retrieved from.
 * Intended to be used both in unit tests as well as in the initialization logic of your application immediately
 * after the Guice Injector has been created. It is essentially a sanity check of all static configurations.
 *
 * @throws ConfigException if Guice had issues provisioning property accessors
 */
public void validateStaticConfiguration()
{
    int failedConfigCount = 0;

    if (allConfigDescriptors == null) {
        log.warn("No config descriptors found. If you don't have any configurations installed, this warning can be ignored");
        return;
    }

    for (ConfigDescriptor desc : allConfigDescriptors) {
        try {
            log.trace("Checking static config for property {}, with default value of {}",
                desc.getConfigName(), desc.getDefaultValue());
            PropertyIdentifier propertyId = getIdentifier(desc);
            TypeLiteral<PropertyAccessor<?>> accessorKey =
                (TypeLiteral<PropertyAccessor<?>>) TypeLiteral.get(
                    Types.newParameterizedType(PropertyAccessor.class, desc.getConfigType()));
            Provider<PropertyAccessor<?>> propertyAccessor = injector.getProvider(Key.get(accessorKey, propertyId));

            propertyAccessor.get();
        }
        catch (ProvisionException ex) {
            ++failedConfigCount;
            log.warn("Failed static config check for property {}", desc.getConfigName(), ex);
        }
    }

    if (failedConfigCount > 0) {
        throw new ConfigException("{} of {} configuration values failed static config checks",
            failedConfigCount,
            allConfigDescriptors.size());
    }
}
 
Example 35
Project: ice   File: ConfigValueConvertersTest.java   Source Code and License 5 votes vote down vote up
@Test(timeout = 5000)
public void testStringListConverter_viaMap()
{
    ConfigValueConverter<List<String>> listConverter = (ConfigValueConverter<List<String>>) converterMap.get(TypeLiteral.get(Types.newParameterizedType(List.class, String.class)));
    List<String> result = listConverter.apply("abc,def,123");
    assertNotNull(result);
    assertEquals(3, result.size());
    assertEquals("abc", result.get(0));
    assertEquals("def", result.get(1));
    assertEquals("123", result.get(2));
}
 
Example 36
Project: favorite-things   File: BraqueConverterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                        Retrofit retrofit) {
    if (type.toString().equals(Types.newParameterizedType(List.class, BrowseGithubsShowGithubThing.class).toString())) {
        return new BraqueResponseBodyConverter(BrowseGithubsShowGithubThing.class,
                StringProvisioner.pathBrowseGithubs(),
                new BraqueResponseBodyConverter.BraqueProperty[]{
                        new BraqueProperty("id", StringProvisioner.propId()),
                        new BraqueProperty("stargazers_count", StringProvisioner.propStars()),
                        new BraqueProperty("name", StringProvisioner.propName()),
                        new BraqueProperty("forks_count", StringProvisioner.propForks()),
                        new BraqueProperty("watchers_count", StringProvisioner.propWatchers()),
                        new BraqueProperty("description", StringProvisioner.propDescription())

                }, "items");
    } else if (type.toString().equals(Types.newParameterizedType(List.class, BrowseTVMazesShowTVMazeThing.class).toString())) {
        return new BraqueResponseBodyConverter(BrowseTVMazesShowTVMazeThing.class,
                StringProvisioner.pathBrowseTVMazes(),
                new BraqueResponseBodyConverter.BraqueProperty[]{
                        new BraqueProperty("show.id", StringProvisioner.propId()),
                        new BraqueProperty("show.type", StringProvisioner.propShowType()),
                        new BraqueProperty("show.name", StringProvisioner.propName()),
                        new BraqueProperty("show.summary", StringProvisioner.propDescription())
                });
    } else if (type.toString().equals(Types.newParameterizedType(List.class, BrowseOMDBsShowOMDBThing.class).toString())) {
        return new BraqueResponseBodyConverter(BrowseOMDBsShowOMDBThing.class,
                StringProvisioner.pathBrowseOMDBs(),
                new BraqueResponseBodyConverter.BraqueProperty[]{
                        new BraqueProperty("imdbID", StringProvisioner.propId()),
                        new BraqueProperty("Title", StringProvisioner.propName()),
                        new BraqueProperty("Year", StringProvisioner.propYear()),
                }, "Search");
    }
    return null;
}
 
Example 37
Project: emodb   File: JobStatusUtil.java   Source Code and License 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 38
Project: xtext-core   File: GenericModuleTest.java   Source Code and License 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 39
Project: salta   File: TypeLiteral.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the type of this type's provider.
 */
@SuppressWarnings("unchecked")
final TypeLiteral<Provider<T>> providerType() {
    // This cast is safe and wouldn't generate a warning if Type had a type
    // parameter.
    return (TypeLiteral<Provider<T>>) get(Types.providerOf(getType()));
}
 
Example 40
Project: salta   File: MoreTypes.java   Source Code and License 5 votes vote down vote up
/**
 * Returns an type that's appropriate for use in a key.
 *
 * <p>
 * If the raw type of {@code typeLiteral} is a {@code javax.inject.Provider}
 * , this returns a {@code com.google.inject.Provider} with the same type
 * parameters.
 *
 * <p>
 * If the type is a primitive, the corresponding wrapper type will be
 * returned.
 *
 * @throws ConfigurationException
 *             if {@code type} contains a type variable
 */
public static <T> TypeLiteral<T> canonicalizeForKey(
        TypeLiteral<T> typeLiteral) {
    Type type = typeLiteral.getType();
    if (!isFullySpecified(type)) {
        Errors errors = new Errors().keyNotFullySpecified(typeLiteral);
        throw new ConfigurationException(errors.getMessages());
    }

    if (typeLiteral.getRawType() == javax.inject.Provider.class) {
        ParameterizedType parameterizedType = (ParameterizedType) type;

        // the following casts are generally unsafe, but
        // com.google.inject.Provider extends
        // javax.inject.Provider and is covariant
        @SuppressWarnings("unchecked")
        TypeLiteral<T> guiceProviderType = (TypeLiteral<T>) TypeLiteral
                .get(Types.providerOf(
                        parameterizedType.getActualTypeArguments()[0]));
        return guiceProviderType;
    }

    @SuppressWarnings("unchecked")
    TypeLiteral<T> wrappedPrimitives = (TypeLiteral<T>) PRIMITIVE_TO_WRAPPER
            .get(typeLiteral);
    return wrappedPrimitives != null ? wrappedPrimitives : typeLiteral;
}