Java Code Examples for com.google.inject.Key#get()

The following examples show how to use com.google.inject.Key#get() . 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: ComponentGraphTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private Pair<Integer, Pair<Executor, Executor>> buildGraphWithChildInjector(Supplier<Executor> executorProvider) {
    Injector childInjector = Guice.createInjector(new AbstractModule() {
        @Override
        public void configure() {
            bind(Executor.class).toProvider(executorProvider::get);
        }
    });

    ComponentGraph componentGraph = new ComponentGraph();

    Key<ComponentTakingExecutor> keyA = Key.get(ComponentTakingExecutor.class, Names.named("A"));
    Key<ComponentTakingExecutor> keyB = Key.get(ComponentTakingExecutor.class, Names.named("B"));

    componentGraph.add(mockComponentNode(keyA));
    componentGraph.add(mockComponentNode(keyB));

    componentGraph.complete(childInjector);

    return new Pair<>(componentGraph.size(),
            new Pair<>(componentGraph.getInstance(keyA).executor, componentGraph.getInstance(keyB).executor));
}
 
Example 2
Source File: JndiModule.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    requestStaticInjection(JndiContext.class);

    // Bind default context
    Key<Context> defaultContextKey = Key.get(Context.class, Names.named("defaultContext"));
    bind(defaultContextKey).toInstance(this.defaultContext);
    bind(Context.class).to(defaultContextKey);

    // Bind additional contexts
    for (Map.Entry<String, Context> jndiContextToBeBound : jndiContextsToBeBound.entrySet()) {
        Key<Context> key = Key.get(Context.class, Names.named(jndiContextToBeBound.getKey()));
        bind(key).toInstance(jndiContextToBeBound.getValue());
    }

    bindListener(Matchers.any(), new ResourceTypeListener(this.defaultContext, this.jndiContextsToBeBound));
}
 
Example 3
Source File: ModuleManifest.java    From ProjectAres with GNU Affero General Public License v3.0 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 4
Source File: ToolOptions.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/** Creates a new option from a type literal. */
@SuppressWarnings("unchecked")
public static <T> Option<T> createOption(
    TypeLiteral<T> type, String name, String description, @Nullable T defaultValue) {
  Option<T> option =
              new Option<T>(
                  Key.get(type, Names.named(name)), name, description, defaultValue, false, true);
  registeredOptions.add(option);
  return option;
}
 
Example 5
Source File: InnerFactoryManifest.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public InnerFactoryManifest(Key<I> innerKey, TypeLiteral<O> outerType) {
    if(innerKey == null) {
        innerKey = Key.get(new ResolvableType<I>(){}.in(getClass()));
    }
    this.innerType = innerKey.getTypeLiteral();
    this.outerType = outerType != null ? outerType : new ResolvableType<O>(){}.in(getClass());

    this.factoryKey = innerKey.ofType(new ResolvableType<InnerFactory<O, I>>(){}
                                          .with(new TypeArgument<O>(this.outerType){},
                                                new TypeArgument<I>(this.innerType){}));
}
 
Example 6
Source File: CodeGeneratorFragmentProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public CharSequence get(String target, ExecutionFlow flow, IGenArtifactConfigurations config) {
	Key<Set<ISourceFragment>> key = Key.get(new TypeLiteral<Set<ISourceFragment>>() {
	}, Names.named(target));
	if (injector.getExistingBinding(key) == null) {
		return "";
	}
	Set<ISourceFragment> fragments = injector.getInstance(key);
	return fragments.stream().map((it) -> it.get(flow, config))
			.collect(Collectors.joining(Strings.newLine() + Strings.newLine()));
}
 
Example 7
Source File: ModelsManifest.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void configure() {
    // @ModelSync ExecutorService must be bound elsewhere
    final Key<Executor> executorKey = Key.get(Executor.class, ModelSync.class);
    final Key<ExecutorService> executorServiceKey = Key.get(ExecutorService.class, ModelSync.class);
    final Key<ListeningExecutorService> listeningExecutorServiceKey = Key.get(ListeningExecutorService.class, ModelSync.class);

    bind(executorKey).to(executorServiceKey);

    expose(executorKey);
    expose(executorServiceKey);
    expose(listeningExecutorServiceKey);

    new ModelListenerBinder(publicBinder());
}
 
Example 8
Source File: GuiceRsModule.java    From digdag with Apache License 2.0 5 votes vote down vote up
protected <T extends HttpServlet> ServletBindingBuilder bindServlet(Class<T> servlet)
{
    Annotation annotation = UniqueAnnotations.create();
    Key<T> servletKey = Key.get(servlet, UniqueAnnotations.create());
    binder().bind(servletKey).to(servlet).in(Scopes.SINGLETON);
    return new ServletBindingBuilder(binder(), servletKey);
}
 
Example 9
Source File: GuiceRsModule.java    From digdag with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public ApplicationBindingBuilder addProvider(Class<?> annotatedClass)
{
    Key<Object> key = Key.get((Class<Object>) annotatedClass, UniqueAnnotations.create());
    binder.bind(key).to(annotatedClass);
    initializer.addProvider(key);
    return this;
}
 
Example 10
Source File: ApplicationContextHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private TestTcpDataSender findTestTcpDataSender(Injector injector) {
    TypeLiteral<EnhancedDataSender<Object>> dataSenderTypeLiteral = new TypeLiteral<EnhancedDataSender<Object>>() {
    };
    Key<EnhancedDataSender<Object>> dataSenderKey = Key.get(dataSenderTypeLiteral);
    EnhancedDataSender dataSender = injector.getInstance(dataSenderKey);
    if (dataSender instanceof TestTcpDataSender) {
        return (TestTcpDataSender) dataSender;
    }
    throw new IllegalStateException("unexpected dataSender" + dataSender);
}
 
Example 11
Source File: SignalFxOutputPlugin.java    From ffwd with Apache License 2.0 4 votes vote down vote up
@Override
public Module module(final Key<PluginSink> key, final String id) {
    return new OutputPluginModule(id) {
        @Provides
        Supplier<AggregateMetricSender> sender() {
            final Collection<OnSendErrorHandler> handlers = ImmutableList.of(metricError -> {
                log.error(metricError.toString());
            });

            return () -> {
                final SignalFxEndpoint endpoint = new SignalFxEndpoint();
                final HttpDataPointProtobufReceiverFactory dataPoints =
                    new HttpDataPointProtobufReceiverFactory(endpoint).setVersion(2);

                BasicHttpClientConnectionManager connectionManager =
                    new BasicHttpClientConnectionManager();
                SocketConfig socketConfigWithSoTimeout = SocketConfig
                    .copy(connectionManager.getSocketConfig())
                    .setSoTimeout(soTimeout)
                    .build();
                connectionManager.setSocketConfig(socketConfigWithSoTimeout);
                dataPoints.setHttpClientConnectionManager(connectionManager);

                final EventReceiverFactory events =
                    new HttpEventProtobufReceiverFactory(endpoint);
                final AuthToken auth = new StaticAuthToken(authToken);

                return new AggregateMetricSender(sourceName, dataPoints, events, auth,
                    handlers);
            };
        }

        @Override
        protected void configure() {
            final Key<SignalFxPluginSink> sinkKey =
                Key.get(SignalFxPluginSink.class, Names.named("signalfxSink"));
            bind(sinkKey).to(SignalFxPluginSink.class).in(Scopes.SINGLETON);
            install(wrapPluginSink(sinkKey, key));
            expose(key);
        }
    };
}
 
Example 12
Source File: ReflectiveFeatureManifest.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public ReflectiveFeatureManifest(@Nullable TypeLiteral<T> type) {
    this.type = type != null ? Types.assertFullySpecified(type)
                             : new ResolvableType<T>(){}.in(getClass());
    this.typeArg = new TypeArgument<T>(this.type){};
    this.definitionParserKey = Key.get(new ResolvableType<FeatureDefinitionParser<T>>(){}.with(typeArg));
}
 
Example 13
Source File: ProvisionWrapper.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
static <T> Key<ProvisionWrapper<T>> keyOf(TypeLiteral<T> type) {
    return Key.get(new ResolvableType<ProvisionWrapper<T>>(){}.where(new TypeParameter<T>(){}, type));
}
 
Example 14
Source File: ProvisionAtParseTime.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public ProvisionAtParseTime(TypeLiteral<T> type) {
    this(Key.get(type));
}
 
Example 15
Source File: Bindings.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override public <T> Key<T> create(TypeLiteral<T> type) {
  return Key.get(type);
}
 
Example 16
Source File: Keys.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static <T> Key<T> get(TypeToken<T> type) {
    return Key.get(Types.toLiteral(type));
}
 
Example 17
Source File: Bindings.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override public <T> Key<T> create(Class<T> type) {
  return Key.get(type);
}
 
Example 18
Source File: TransformableBinder.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public TransformableBinder(Binder binder, @Nullable Class<T> type) {
    this(binder, type == null ? null : Key.get(type));
}
 
Example 19
Source File: AppModule.java    From Scribengin with GNU Affero General Public License v3.0 4 votes vote down vote up
public <T> void bindType(Class<T> type, String impl) throws ClassNotFoundException {
  Key<T> key = Key.get(type, Names.named(type.getSimpleName())) ;
  Class<?> clazz = (Class<?>)Class.forName(impl);
  bind(type).to((Class)clazz);
}
 
Example 20
Source File: ValidatorTesterTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testInjection() {
	Key<ValidatorTester<TestingValidator>> key = Key.get(new TypeLiteral<ValidatorTester<TestingValidator>>() {});
	ValidatorTester<TestingValidator> injectedTester = get(key);
	assertNotNull(injectedTester);
}