@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); } }
/** * 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; }
@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); } } }
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; }
@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); } }
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; }
@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))); }
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)); } } }
@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(); }
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())); }
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(); } }
/** * 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; }
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)); }
@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); } }
@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)); }
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); } } } }
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); }
@Override public synchronized T get(Class<? extends Annotation> bindingAnnotation) { BindingAnnotations.checkIsBindingAnnotation(bindingAnnotation); Key<T> key = Key.get(type, bindingAnnotation); return injector.getInstance(key); }
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) ); }
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); }
@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 ) ) ); }
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); }
public List<Key<?>> getKeysInScope() { synchronized (scopedKeys) { return new ArrayList<Key<?>>(scopedKeys); } }
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) { } } } }
@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); }
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(); }
@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); } } }
@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); } } }
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); }
@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; }
private Key<SectionNode> bindProvider() { if( key == null ) { key = Key.get(SectionNode.class, this); bind(key).toProvider(this); } return key; }
@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); } }
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)); }
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()); } } }
@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; }
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()); } } } }
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)); }
@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; }
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)); }
@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); }