Java Code Examples for com.google.inject.Key

The following are top voted examples for showing how to use com.google.inject.Key. 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: Equella   File: GuicePlugin.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T getBean(String beanId)
{
	Injector injector = ensureInjector();
	Key<Object> nameKey = Key.get(Object.class, Names.named(beanId));
	Binding<Object> binding = injector.getExistingBinding(nameKey);
	if( binding != null )
	{
		return (T) binding.getProvider().get();
	}
	ClassLoader classLoader = privatePluginService.getClassLoader(pluginId);
	try
	{
		Class<?> clazz = classLoader.loadClass(beanId);
		return (T) injector.getInstance(clazz);
	}
	catch( ClassNotFoundException e )
	{
		throw new RuntimeException(e);
	}
}
 
Example 2
Project: empiria.player   File: FactoryBinding.java   Source Code and License 6 votes vote down vote up
/**
 * Matches constructor parameters to method parameters for injection and records remaining parameters as required keys.
 */
private String[] extractConstructorParameters(Key<?> factoryKey, TypeLiteral<?> implementation, Constructor constructor, List<Key<?>> methodParams,
                                              Errors errors, Set<Dependency> dependencyCollector) throws ErrorsException {

    // Get parameters with annotations.
    List<TypeLiteral<?>> ctorParams = implementation.getParameterTypes(constructor);
    Annotation[][] ctorParamAnnotations = constructor.getParameterAnnotations();

    int p = 0;
    String[] parameterNames = new String[ctorParams.size()];
    for (TypeLiteral<?> ctorParam : ctorParams) {
        Key<?> ctorParamKey = getKey(ctorParam, constructor, ctorParamAnnotations[p], errors);

        if (ctorParamKey.getAnnotationType() == Assisted.class) {
            int location = methodParams.indexOf(ctorParamKey);

            // This should never happen since the constructor was already checked
            // in #[inject]constructorHasMatchingParams(..).
            Preconditions.checkState(location != -1);

            parameterNames[p] = ReflectUtil.formatParameterName(location);
        } else {
            dependencyCollector.add(new Dependency(factoryKey, ctorParamKey, false, true, constructor.toString()));
        }

        p++;
    }

    return parameterNames;
}
 
Example 3
Project: abhot   File: GuiceQueryPluginFactory.java   Source Code and License 6 votes vote down vote up
@Inject
@SuppressWarnings("unchecked")
public GuiceQueryPluginFactory(Injector injector)
{
	m_injector = injector;
	Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

	for (Key<?> key : bindings.keySet())
	{
		Class<?> bindingClass = key.getTypeLiteral().getRawType();
		if (QueryPlugin.class.isAssignableFrom(bindingClass))
		{
			PluginName ann = (PluginName) bindingClass.getAnnotation(PluginName.class);
			if (ann == null)
				throw new IllegalStateException("Aggregator class " + bindingClass.getName() +
						" does not have required annotation " + PluginName.class.getName());

			m_plugins.put(ann.name(), (Class<QueryPlugin>)bindingClass);
		}
	}
}
 
Example 4
Project: parabuild-ci   File: BindUtil.java   Source Code and License 6 votes vote down vote up
ConstructorBindingProvider(Binder binder, Class<T> type, Key... keys) 
{
    super(binder, type, keys);
    
    Constructor<T> constructor = null;
    try 
    {
        constructor = type.getConstructor(getTypes());
    } 
    catch (NoSuchMethodException e) 
    {
        if (binder == null)
        {
            throw new IllegalArgumentException("no such constructor", e);
        }
        else
        {
            binder.addError(e);
        }
    }
    
    this.constructor = constructor;
}
 
Example 5
Project: bromium   File: DefaultModuleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void ifCommmandIsInvalidExceptionIsThrown() throws IOException, URISyntaxException {
    String command = "invalid";
    Map<String, Object> opts = new HashMap<>();
    opts.put(BROWSER, CHROME);
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, localhostUrl);
    opts.put(CASE, caseFile.getAbsolutePath());
    opts.put(SCREEN, screenString);
    opts.put(TIMEOUT, timeoutString);
    opts.put(PRECISION, precisionString);
    Module module = new DefaultModule(command, opts);
    Injector injector = Guice.createInjector(module);

    try {
        RequestFilter instance = injector.getInstance(
                Key.get(new TypeLiteral<IOProvider<RequestFilter>>() {})).get();
    } catch (ProvisionException e) {
        assertTrue(e.getCause() instanceof NoSuchCommandException);
    }
}
 
Example 6
Project: pl   File: JCommandExecutor.java   Source Code and License 6 votes vote down vote up
private static boolean checkOnlyAcceptsPlayer(Class<? extends JCmd> executor) {
    for (InjectionPoint point : InjectionPoint.forInstanceMethodsAndFields(executor)) {
        if (!(point.getMember() instanceof Field))
            continue;

        Key<?> key = point.getDependencies().get(0).getKey();
        if (key.getTypeLiteral().getRawType().equals(Player.class)) {
            return true;
        }
    }

    return false;
}
 
Example 7
Project: drift   File: TestDriftNettyClientModule.java   Source Code and License 6 votes vote down vote up
@Test
public void test()
        throws Exception
{
    Annotation clientAnnotation = named("test");
    Bootstrap bootstrap = new Bootstrap(
            new DriftNettyClientModule(),
            binder -> configBinder(binder).bindConfig(DriftClientConfig.class, clientAnnotation, "prefix"));

    Injector injector = bootstrap
            .doNotInitializeLogging()
            .strictConfig()
            .initialize();

    assertNotNull(injector.getInstance(Key.get(new TypeLiteral<MethodInvokerFactory<Annotation>>() {})));
    assertNotNull(injector.getInstance(Key.get(DriftClientConfig.class, clientAnnotation)));
    assertNotNull(injector.getInstance(Key.get(DriftNettyClientConfig.class, clientAnnotation)));
}
 
Example 8
Project: parabuild-ci   File: InternalCreatorManager.java   Source Code and License 6 votes vote down vote up
private void addCreators()
{
    Injector injector = getInjector();
    for (Key<?> key : injector.getBindings().keySet())
    {
        Class<?> atype = key.getAnnotationType();
        if (atype != null && Remoted.class.isAssignableFrom(atype))
        {
            String scriptName = Remoted.class.cast(key.getAnnotation()).value();
            if (scriptName.equals(""))
            {
                Class cls = (Class) key.getTypeLiteral().getType();
                scriptName = cls.getSimpleName();
            }
            addCreator(scriptName, new InternalCreator(injector, key, scriptName));
        }
    }
}
 
Example 9
Project: bromium   File: DefaultModuleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void canCreateReplayBrowserProvider() throws IOException, URISyntaxException {
    String command = REPLAY;
    Map<String, Object> opts = new HashMap<>();
    opts.put(BROWSER, CHROME);
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, localhostUrl);
    opts.put(CASE, caseFile.getAbsolutePath());
    opts.put(SCREEN, screenString);
    opts.put(TIMEOUT, timeoutString);
    opts.put(PRECISION, precisionString);

    Module module = new DefaultModule(command, opts);
    Injector injector = Guice.createInjector(module);
    IOURIProvider<ReplayBrowser> instance = injector.getInstance(new Key<IOURIProvider<ReplayBrowser>>() {});

    ReplayBrowser replayBrowser = instance.get();
    replayBrowser.forceCleanUp();
}
 
Example 10
Project: ProjectAres   File: ModuleManifest.java   Source Code and License 6 votes vote down vote up
public ModuleManifest(@Nullable TypeLiteral<Module> type) {
    // Figure out the module type. If the given type is null,
    // then try to resolve it from this object's superclass.
    this.type = type != null ? Types.assertFullySpecified(type)
                             : new ResolvableType<Module>(){}.in(getClass());
    this.rawType = (Class<Module>) this.type.getRawType();
    this.simpleName = rawType.getSimpleName();

    // Resolve the scope type automatically
    this.scope = (Class<Scope>) new ResolvableType<Scope>(){}.in(getClass()).getRawType();

    // Construct various keys related to the module/scope
    this.key = Key.get(this.type);
    this.optionalKey = Keys.optional(this.key);
    this.wrapperKey = ProvisionWrapper.keyOf(this.type);
    this.contextKey = Key.get(new ResolvableType<Context>(){}.in(getClass()));
    this.setElementKey = Key.get(new ResolvableType<ProvisionWrapper<? extends Base>>(){}.in(getClass()));
}
 
Example 11
Project: empiria.player   File: FactoryBinding.java   Source Code and License 5 votes vote down vote up
FactoryBinding(Map<Key<?>, TypeLiteral<?>> collector, Key<?> factoryKey, Context context, GuiceUtil guiceUtil, MethodCallUtil methodCallUtil) {
    super(context, factoryKey);

    this.collector = Preconditions.checkNotNull(collector);
    this.factoryKey = factoryKey;
    this.factoryType = factoryKey.getTypeLiteral();
    this.guiceUtil = guiceUtil;
    this.methodCallUtil = methodCallUtil;

    try {
        matchMethods(Preconditions.checkNotNull(factoryKey));
    } catch (ErrorsException e) {
        e.getErrors().throwConfigurationExceptionIfErrorsExist();
    }
}
 
Example 12
Project: empiria.player   File: FactoryBinding.java   Source Code and License 5 votes vote down vote up
/**
 * Matching logic for {@literal @}{@link Inject} constructor and method parameters.
 * <p/>
 * This returns true if all assisted parameters required by the constructor are provided by the factory method.
 */
private boolean injectConstructorHasMatchingParams(TypeLiteral<?> type, Constructor<?> constructor, List<Key<?>> paramList, Errors errors)
        throws ErrorsException {
    List<TypeLiteral<?>> params = type.getParameterTypes(constructor);
    Annotation[][] paramAnnotations = constructor.getParameterAnnotations();
    int p = 0;
    for (TypeLiteral<?> param : params) {
        Key<?> paramKey = getKey(param, constructor, paramAnnotations[p++], errors);
        if (paramKey.getAnnotationType() == Assisted.class && !paramList.contains(paramKey)) {
            return false;
        }
    }

    return true;
}
 
Example 13
Project: ProjectAres   File: InnerFactoryManifest.java   Source Code and License 5 votes vote down vote up
public static <I> InnerFactoryManifest<?, I> forInnerClass(Key<I> key) {
    final Class<?> outer = key.getTypeLiteral().getRawType().getEnclosingClass();
    if(outer == null) {
        throw new IllegalArgumentException(key + " is not an inner class");
    }
    return new InnerFactoryManifest(key, TypeLiteral.get(outer));
}
 
Example 14
Project: beadledom   File: LifecycleProvisionListener.java   Source Code and License 5 votes vote down vote up
@Override
public <T> void onProvision(ProvisionInvocation<T> provision) {
  final Key<?> key = provision.getBinding().getKey();
  final Class<?> clazz = key.getTypeLiteral().getRawType();

  final T injectee = provision.provision();

  // Skip the shutdown manager since it's circular and doesn't have any lifecycle methods
  if (injectee instanceof LifecycleShutdownManager
      || injectee instanceof LifecycleProvisionListener) {
    return;
  }

  List<InvokableLifecycleMethod> postConstructMethods = findPostConstructMethods(injectee, clazz);
  List<InvokableLifecycleMethod> preDestroyMethods = findPreDestroyMethods(injectee, clazz);

  for (InvokableLifecycleMethod postConstructMethod : postConstructMethods) {
    try {
      postConstructMethod.invoke();
    } catch (Exception e) {
      throw new ProvisionException("Fail to provision object of type " + key, e);
    }
  }

  if (!preDestroyMethods.isEmpty()) {
    shutdownManager.addPreDestroyMethods(preDestroyMethods);
  }
}
 
Example 15
Project: beadledom   File: BeadledomClientModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configure() {
  OptionalBinder
      .newOptionalBinder(
          binder(),
          Key.get(String.class, CorrelationIdClientHeader.class))
      .setDefault().toInstance(CorrelationIdContext.DEFAULT_HEADER_NAME);

  OptionalBinder
      .newOptionalBinder(
          binder(),
          Key.get(BeadledomClientConfiguration.class, clientBindingAnnotation));

  install(new BeadledomClientPrivateModule(clientBindingAnnotation));
}
 
Example 16
Project: beadledom   File: BeadledomClientBuilderProvider.java   Source Code and License 5 votes vote down vote up
private void processInjector(Injector injector, BeadledomClientBuilder builder) {
  for (Map.Entry<Key<?>, Binding<?>> bindingEntry : injector.getBindings().entrySet()) {
    if (isExcludedBinding(bindingEntry.getKey())) {
      continue;
    }

    Binding<?> binding = bindingEntry.getValue();
    if (isJaxrsClientProviderBinding(binding)) {
      Object object = binding.getProvider().get();
      if (isJaxrsFeatureOrProvider(object)) {
        builder.register(object);
      }
    }
  }
}
 
Example 17
Project: parabuild-ci   File: AbstractMapContextScope.java   Source Code and License 5 votes vote down vote up
public <T> boolean remove(ConcurrentMap registry, Key<T> key, String keyString, 
                          InstanceProvider<T> creator)
{
    @SuppressWarnings("unchecked")
    ConcurrentMap<Key<T>, InstanceProvider<T>> instanceMap =
        (ConcurrentMap<Key<T>, InstanceProvider<T>>) registry;
    
    return instanceMap.remove(key, creator);
}
 
Example 18
Project: beadledom   File: DynamicBindingProviderImpl.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized T get(Class<? extends Annotation> bindingAnnotation) {
  BindingAnnotations.checkIsBindingAnnotation(bindingAnnotation);

  Key<T> key = Key.get(type, bindingAnnotation);
  return injector.getInstance(key);
}
 
Example 19
Project: verify-hub   File: AttributeQueryRequestRunnableFactory.java   Source Code and License 5 votes vote down vote up
public Runnable create(final SessionId sessionId, final AttributeQueryContainerDto attributeQueryContainerDto) {
    return new AttributeQueryRequestRunnable(
            sessionId,
            attributeQueryContainerDto,
            injector.getInstance(ExecuteAttributeQueryRequest.class),
            injector.getInstance(Key.get(Counter.class, MatchingServiceRequestExecutorBacklog.class)),
            injector.getInstance(TimeoutEvaluator.class),
            injector.getInstance(HubMatchingServiceResponseReceiverProxy.class),
            injector.getInstance(ServiceInfoConfiguration.class),
            injector.getInstance(EventSinkProxy.class)
    );
}
 
Example 20
Project: drift   File: ThriftCodecBinder.java   Source Code and License 5 votes vote down vote up
public void bindCustomThriftCodec(Key<? extends ThriftCodec<?>> thriftCodecKey)
{
    requireNonNull(thriftCodecKey, "thriftCodecKey is null");

    // bind the custom codec type to the internal thrift codec set
    newSetBinder(binder, new TypeLiteral<ThriftCodec<?>>() {}, InternalThriftCodec.class).addBinding().to(thriftCodecKey);

    // make the custom codec available to user code for binding
    binder.bind(thriftCodecKey).in(Scopes.SINGLETON);
}
 
Example 21
Project: wall-t   File: ApiModuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void can_inject_functions_to_build_ProjectData_in_singleton( ) throws Exception {
    // Setup
    // Exercise
    final Map<ApiVersion, Function<Project, ProjectData>> instance = _injector.getInstance( Key.get( new TypeLiteral<Map<ApiVersion, Function<Project, ProjectData>>>( ) {
    } ) );
    final Map<ApiVersion, Function<Project, ProjectData>> instance2 = _injector.getInstance( Key.get( new TypeLiteral<Map<ApiVersion, Function<Project, ProjectData>>>( ) {
    } ) );
    // Verify
    assertThat( instance, is( notNullValue( ) ) );
    assertThat( instance, is( sameInstance( instance2 ) ) );
}
 
Example 22
Project: parabuild-ci   File: OutOfScopeException.java   Source Code and License 5 votes vote down vote up
public OutOfScopeException(Scope scope, Key<?> key, Throwable cause) 
{
    super(String.format(
        "Not in scope %s for key %s: caused by %s",
        scope, key, cause
    ), cause);
}
 
Example 23
Project: parabuild-ci   File: AbstractContextScope.java   Source Code and License 5 votes vote down vote up
public List<Key<?>> getKeysInScope()
{
    synchronized (scopedKeys)
    {
        return new ArrayList<Key<?>>(scopedKeys);
    }
}
 
Example 24
Project: drift   File: TestSimpleAddressSelectorBinder.java   Source Code and License 5 votes vote down vote up
private static void testAddressSelector(
        AddressSelectorBinder addressSelectorBinder,
        Map<String, String> configurationProperties,
        List<HostAndPort> expected)
        throws Exception
{
    Bootstrap app = new Bootstrap(
            new ThriftCodecModule(),
            binder -> addressSelectorBinder.bind(binder, THRIFT_SERVICE_ANNOTATION, "testService"));

    LifeCycleManager lifeCycleManager = null;
    try {
        Injector injector = app
                .setRequiredConfigurationProperties(configurationProperties)
                .strictConfig()
                .doNotInitializeLogging()
                .initialize();
        lifeCycleManager = injector.getInstance(LifeCycleManager.class);

        AddressSelector<?> addressSelector = injector.getInstance(Key.get(AddressSelector.class, THRIFT_SERVICE_ANNOTATION));
        assertInstanceOf(addressSelector, SimpleAddressSelector.class);
        SimpleAddressSelector simpleAddressSelector = (SimpleAddressSelector) addressSelector;
        assertEquals(simpleAddressSelector.getAddresses(), expected);
    }
    finally {
        if (lifeCycleManager != null) {
            try {
                lifeCycleManager.stop();
            }
            catch (Exception ignored) {
            }
        }
    }
}
 
Example 25
Project: ProjectAres   File: InjectableMethodTest.java   Source Code and License 5 votes vote down vote up
@Test
public void qualifiedReturnType() throws Exception {
    class Woot {
        @Named("q") String foo() {
            return "hi";
        }
    }

    InjectableMethod<?> method = InjectableMethod.forDeclaredMethod(new Woot(), "foo");
    String hi = Guice.createInjector(method.bindingModule()).getInstance(Key.get(String.class, Names.named("q")));

    assertEquals("hi", hi);
}
 
Example 26
Project: ProjectAres   File: Injection.java   Source Code and License 5 votes vote down vote up
public static <T> Map<Key<? extends T>, Binding<? extends T>> bindingsAssignableTo(Injector injector, TypeToken<T> type) {
    final ImmutableMap.Builder<Key<? extends T>, Binding<? extends T>> builder = ImmutableMap.builder();
    forEachBinding(injector, binding -> {
        if(type.isAssignableFrom(binding.getKey().getTypeLiteral().getType())) {
            builder.put((Key<? extends T>) binding.getKey(), (Binding<? extends T>) binding);
        }
    });
    return builder.build();
}
 
Example 27
Project: abhot   File: DataPointListenerProvider.java   Source Code and License 5 votes vote down vote up
@Inject
public DataPointListenerProvider(Injector injector)
{
	Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

	for (Key<?> key : bindings.keySet())
	{
		Class<?> bindingClass = key.getTypeLiteral().getRawType();
		if (DataPointListener.class.isAssignableFrom(bindingClass))
		{
			DataPointListener listener = (DataPointListener)injector.getInstance(bindingClass);
			m_listeners.add(listener);
		}
	}
}
 
Example 28
Project: abhot   File: GuiceCommandProvider.java   Source Code and License 5 votes vote down vote up
@Inject
public GuiceCommandProvider(Injector injector)
{
	Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

	for (Key<?> key : bindings.keySet())
	{
		Class<?> bindingClass = key.getTypeLiteral().getRawType();
		if (TelnetCommand.class.isAssignableFrom(bindingClass))
		{
			TelnetCommand command = (TelnetCommand)injector.getInstance(bindingClass);
			m_commandMap.put(command.getCommand(), command);
		}
	}
}
 
Example 29
Project: ProjectAres   File: MatchBinders.java   Source Code and License 5 votes vote down vote up
default <T extends Listener> void matchOptionalListener(Key<T> key, @Nullable MatchScope scope) {
    inSet(MatchListenerMeta.class).addBinding().toInstance(
        new MatchListenerMeta((Class<T>) key.getTypeLiteral().getRawType(), scope)
    );

    final Key<Optional<T>> optionalKey = Keys.optional(key);
    inSet(Key.get(new TypeLiteral<Optional<? extends Listener>>(){}, ForMatch.class))
        .addBinding().to(optionalKey);
}
 
Example 30
Project: Equella   File: GuicePlugin.java   Source Code and License 5 votes vote down vote up
@Override
public <T> Collection<T> getBeansOfType(Class<T> clazz)
{
	Injector injector = ensureInjector();
	List<T> beans = new ArrayList<T>();
	Map<Key<?>, Binding<?>> bindings = injector.getBindings();
	for( Binding<?> binding : bindings.values() )
	{
		Key<?> actualKey = null;
		if( binding instanceof UntargettedBinding || binding instanceof ConstructorBinding )
		{
			actualKey = binding.getKey();
		}
		else if( binding instanceof LinkedKeyBinding )
		{
			actualKey = ((LinkedKeyBinding<?>) binding).getLinkedKey();
		}
		else if( binding instanceof ProviderBinding )
		{
			actualKey = ((ProviderBinding<?>) binding).getProvidedKey();
		}
		if( actualKey != null && clazz.isAssignableFrom(actualKey.getTypeLiteral().getRawType()) )
		{
			beans.add(clazz.cast(binding.getProvider().get()));
		}
	}
	return beans;
}
 
Example 31
Project: Equella   File: SectionsModule.java   Source Code and License 5 votes vote down vote up
private Key<SectionNode> bindProvider()
{
	if( key == null )
	{
		key = Key.get(SectionNode.class, this);
		bind(key).toProvider(this);
	}
	return key;
}
 
Example 32
Project: abhot   File: KairosDBSchedulerImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void start() throws KairosDBException
{
	try
	{
		scheduler.start();

		for (Key<?> key : guice.getAllBindings().keySet())
		{
			Class bindingClass = key.getTypeLiteral().getRawType();
			if (KairosDBJob.class.isAssignableFrom(bindingClass))
			{
				KairosDBJob job = (KairosDBJob) guice.getInstance(bindingClass);
				JobDetail jobDetail = newJob(job.getClass())
						.withIdentity(job.getClass().getName()).build();

				scheduler.scheduleJob(jobDetail, job.getTrigger());
			}
		}

		for (String groupName : scheduler.getJobGroupNames())
		{
			for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName)))
			{
				String jobName = jobKey.getName();
				List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
				Date nextFireTime = triggers.get(0).getNextFireTime();
				log.info("*** Scheduled job " + jobName + " to execute next on " + nextFireTime);
			}
		}
	}
	catch (SchedulerException e)
	{
		throw new KairosDBException("Failed to start " + getClass().getName(), e);
	}
}
 
Example 33
Project: ProjectAres   File: FeatureBinder.java   Source Code and License 5 votes vote down vote up
public FeatureBinder(Binder binder, @Nullable TypeLiteral<T> type) {
    this.binder = binder;
    this.type = type != null ? type : new ResolvableType<T>(){}.in(getClass());
    this.typeArg = new TypeArgument<T>(this.type){};
    this.key = Key.get(this.type);

    binder.install(new FeatureManifest<>(this.type));
}
 
Example 34
Project: Equella   File: SectionsModule.java   Source Code and License 5 votes vote down vote up
private void addToList(List<Key<?>> list, Object... children)
{
	for( Object child : children )
	{
		if( child instanceof Class )
		{
			addSectionToList(list, ((Class<?>) child).asSubclass(Section.class));
		}
		else if( child instanceof NodeProvider )
		{
			list.add(((NodeProvider) child).bindProvider());
		}
	}
}
 
Example 35
Project: crnk-framework   File: GuiceServiceDiscovery.java   Source Code and License 5 votes vote down vote up
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
	List<Object> instances = new ArrayList<>();
	for (Key<?> key : injector.getAllBindings().keySet()) {
		Class<?> beanClass = key.getTypeLiteral().getRawType();
		Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass);
		if (annotation.isPresent()) {
			Object instance = injector.getInstance(key);
			instances.add(instance);
		}
	}
	return instances;
}
 
Example 36
Project: ProjectAres   File: DependencyCollector.java   Source Code and License 5 votes vote down vote up
private void processImplicitBindings() {
    for(;;) {
        ImmutableSet<Key<?>> keys = ImmutableSet.copyOf(Sets.difference(requiredKeys, Sets.union(explicitBindings.keySet(), implicitBindings)));
        if(keys.isEmpty()) break;
        for(Key<?> key : keys) {
            if(implicitBindings.add(key)) {
                processInjections(key.getTypeLiteral());
            }
        }
    }
}
 
Example 37
Project: mynlp   File: GuiceTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Injector inject = Guice.createInjector(binder -> {
        binder.bind(A.class).toInstance(new A().set("p"));
    });
    Injector c1 = inject.createChildInjector(binder -> {
        binder.bind(A.class).annotatedWith(Names.named("a")).toInstance(new A());
    });
    Injector c2 = inject.createChildInjector();
    System.out.println(c1.getInstance(Key.get(A.class, Names.named("a"))));
    System.out.println(c2.getInstance(A.class));
}
 
Example 38
Project: crnk-framework   File: GuiceServiceDiscovery.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> List<T> getInstancesByType(Class<T> clazz) {
	List<T> instances = new ArrayList<>();
	for (Key<?> key : injector.getAllBindings().keySet()) {
		if (clazz.isAssignableFrom(key.getTypeLiteral().getRawType())) {
			T instance = (T) injector.getInstance(key);
			instances.add(instance);
		}
	}
	return instances;
}
 
Example 39
Project: junit5-extensions   File: GuiceExtension.java   Source Code and License 5 votes vote down vote up
private static Key<?> getKey(Optional<Class<?>> containingElement, Parameter parameter) {
  Class<?> clazz =
      containingElement.orElseGet(() -> parameter.getDeclaringExecutable().getDeclaringClass());
  TypeToken<?> classType = TypeToken.of(clazz);
  Type resolvedType = classType.resolveType(parameter.getParameterizedType()).getType();

  Optional<Key<?>> key =
      getOnlyBindingAnnotation(parameter).map(annotation -> Key.get(resolvedType, annotation));
  return key.orElse(Key.get(resolvedType));
}
 
Example 40
Project: ProjectAres   File: ComponentRendererRegistry.java   Source Code and License 5 votes vote down vote up
@Override
public ComponentRenderer load(final Class<? extends BaseComponent> type) throws Exception {
    ConfigurationException originalException = null;
    for(Class c = type; BaseComponent.class.isAssignableFrom(c); c = c.getSuperclass()) {
        try {
            return (ComponentRenderer) injector.getInstance(Key.get(ComponentRenderers.rendererType(c)));
        } catch(ConfigurationException e) {
            if(originalException == null) originalException = e;
        }
    }
    throw new IllegalStateException("Can't find a renderer for component type " + type, originalException);
}