Java Examples for com.google.inject.Key

The following java examples will help you to understand the usage of com.google.inject.Key. These source code samples are taken from different open source projects.

Example 1
Project: sitebricks-master  File: DefaultPageBook.java View source code
private List<Object> reflect(Method method) {
    final Annotation[][] annotationsGrid = method.getParameterAnnotations();
    if (null == annotationsGrid)
        return Collections.emptyList();
    List<Object> args = new ArrayList<Object>();
    for (int i = 0; i < annotationsGrid.length; i++) {
        Annotation[] annotations = annotationsGrid[i];
        Annotation bindingAnnotation = null;
        boolean preInjectableFound = false;
        for (Annotation annotation : annotations) {
            if (Named.class.isInstance(annotation)) {
                Named named = (Named) annotation;
                args.add(new NamedParameter(named.value(), method.getGenericParameterTypes()[i]));
                preInjectableFound = true;
                break;
            }
            if (javax.inject.Named.class.isInstance(annotation)) {
                javax.inject.Named named = (javax.inject.Named) annotation;
                args.add(new NamedParameter(named.value(), method.getGenericParameterTypes()[i]));
                preInjectableFound = true;
                break;
            } else if (annotation.annotationType().isAnnotationPresent(BindingAnnotation.class)) {
                bindingAnnotation = annotation;
            } else if (As.class.isInstance(annotation)) {
                As as = (As) annotation;
                if (method.isAnnotationPresent(Get.class) || method.isAnnotationPresent(Head.class) || method.isAnnotationPresent(Trace.class)) {
                    if (!as.value().equals(Form.class)) {
                        throw new IllegalArgumentException("Cannot accept a @As(...) request body from" + " method marked @Get, @Head or @Trace: " + method.getDeclaringClass().getName() + "#" + method.getName() + "()");
                    }
                }
                preInjectableFound = true;
                args.add(new AsParameter(as.value(), TypeLiteral.get(method.getGenericParameterTypes()[i])));
                break;
            }
        }
        if (!preInjectableFound) {
            Type genericParameterType = method.getGenericParameterTypes()[i];
            Key<?> key = (null != bindingAnnotation) ? Key.get(genericParameterType, bindingAnnotation) : Key.get(genericParameterType);
            args.add(key);
            if (null == injector.getBindings().get(key)) {
                throw new InvalidEventHandlerException("Encountered an argument not annotated with @Named and not a valid injection key" + " in event handler method: " + method + " " + key);
            }
        }
    }
    return Collections.unmodifiableList(args);
}
Example 2
Project: airlift-master  File: ConfigurationFactory.java View source code
private <T> ConfigDefaults<T> getConfigDefaults(Key<T> key) {
    List<ConfigDefaults<T>> defaults = registeredDefaultConfigs.get(key).stream().map( holder -> (ConfigDefaultsHolder<T>) holder).sorted().map(ConfigDefaultsHolder::getConfigDefaults).collect(toList());
    return ConfigDefaults.configDefaults(defaults);
}
Example 3
Project: sisu-guice-master  File: RealMapBinder.java View source code
// Note: We use valueTypeAndAnnotation effectively as a Pair<TypeLiteral, Annotation|Class>
// since it's an easy way to group a type and an optional annotation type or instance.
static <K, V> RealMapBinder<K, V> newRealMapBinder(Binder binder, TypeLiteral<K> keyType, Key<V> valueTypeAndAnnotation) {
    binder = binder.skipSources(RealMapBinder.class);
    TypeLiteral<V> valueType = valueTypeAndAnnotation.getTypeLiteral();
    return newRealMapBinder(binder, keyType, valueType, valueTypeAndAnnotation.ofType(mapOf(keyType, valueType)), RealMultibinder.newRealSetBinder(binder, valueTypeAndAnnotation.ofType(entryOfProviderOf(keyType, valueType))));
}
Example 4
Project: usergrid-master  File: AbstractService.java View source code
public void setServiceManager(ServiceManager sm) {
    this.sm = sm;
    em = sm.getEntityManager();
    final Injector injector = sm.getApplicationContext().getBean(Injector.class);
    rxScheduler = injector.getInstance(Key.get(RxTaskScheduler.class, ResponseImportTasks.class)).getAsyncIOScheduler();
    rxSchedulerFig = injector.getInstance(ServiceSchedulerFig.class);
    metricsFactory = injector.getInstance(MetricsFactory.class);
    this.entityGetTimer = metricsFactory.getTimer(this.getClass(), "importEntity.get");
    this.entitiesGetTimer = metricsFactory.getTimer(this.getClass(), "importEntities.get");
    this.entitiesParallelGetTimer = metricsFactory.getTimer(this.getClass(), "importEntitiesP.get");
    this.invokeTimer = metricsFactory.getTimer(this.getClass(), "service.invoke");
    this.cacheFactory = injector.getInstance(CacheFactory.class);
    this.localShiroCache = injector.getInstance(LocalShiroCache.class);
}
Example 5
Project: mycila-master  File: BindMethodTest.java View source code
@Test
public void test_bind() {
    MycilaTesting.from(getClass()).createNotifier(this).prepare();
    assertEquals(injector.getInstance(String.class), "helloa");
    assertEquals(injector.getInstance(Key.get(String.class, Named.class)), "hellob");
    b = "changedb";
    a = "changeda";
    assertEquals(injector.getInstance(String.class), "changeda");
    assertEquals(injector.getInstance(Key.get(String.class, Named.class)), "hellob");
    assertEquals(injector.getInstance(ServiceImpl2.class).go(), "impl1");
    assertEquals(injector.getInstance(Key.get(Service.class, Named.class)).go(), "impl2");
}
Example 6
Project: aokp-gerrit-master  File: PluginGuiceEnvironment.java View source code
private void reattachMap(ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> oldHandles, Map<TypeLiteral<?>, DynamicMap<?>> maps, @Nullable Injector src, Plugin newPlugin) {
    if (src == null || maps == null || maps.isEmpty()) {
        return;
    }
    for (Map.Entry<TypeLiteral<?>, DynamicMap<?>> e : maps.entrySet()) {
        @SuppressWarnings("unchecked") TypeLiteral<Object> type = (TypeLiteral<Object>) e.getKey();
        @SuppressWarnings("unchecked") PrivateInternals_DynamicMapImpl<Object> map = (PrivateInternals_DynamicMapImpl<Object>) e.getValue();
        Map<Annotation, ReloadableRegistrationHandle<?>> am = Maps.newHashMap();
        for (ReloadableRegistrationHandle<?> h : oldHandles.get(type)) {
            Annotation a = h.getKey().getAnnotation();
            if (a != null && !UNIQUE_ANNOTATION.isInstance(a)) {
                am.put(a, h);
            }
        }
        for (Binding<?> binding : bindings(src, e.getKey())) {
            @SuppressWarnings("unchecked") Binding<Object> b = (Binding<Object>) binding;
            Key<Object> key = b.getKey();
            if (key.getAnnotation() == null) {
                continue;
            }
            @SuppressWarnings("unchecked") ReloadableRegistrationHandle<Object> h = (ReloadableRegistrationHandle<Object>) am.remove(key.getAnnotation());
            if (h != null) {
                replace(newPlugin, h, b);
                oldHandles.remove(type, h);
            } else {
                newPlugin.add(map.put(newPlugin.getName(), b.getKey(), b.getProvider()));
            }
        }
    }
}
Example 7
Project: palava-ipc-xml-rpc-master  File: XmlRpcNettyModule.java View source code
@Override
public void configure(Binder binder) {
    binder.bind(HttpRequestDecoder.class).in(Scopes.NO_SCOPE);
    binder.bind(HttpResponseEncoder.class).in(Singleton.class);
    binder.bind(HttpHandler.class).in(Singleton.class);
    binder.bind(JaxbDecoder.class).in(Singleton.class);
    binder.bind(JaxbEncoder.class).in(Singleton.class);
    binder.bind(MethodCallDecoder.class).in(Singleton.class);
    binder.bind(MethodResponseEncoder.class).in(Singleton.class);
    binder.bind(XmlRpcHandler.class).in(Singleton.class);
    binder.bind(Key.get(Schema.class, XmlRpc.class)).toProvider(XmlRpcSchemaProvider.class).in(Singleton.class);
    binder.bind(Marshaller.class).annotatedWith(XmlRpc.class).toProvider(XmlRpcMarshallerProvider.class);
    binder.bind(Unmarshaller.class).annotatedWith(XmlRpc.class).toProvider(XmlRpcUnmarshallerProvider.class);
    binder.install(new AdapterModule());
}
Example 8
Project: mind-compiler-master  File: TestADLAnnotationProcessor.java View source code
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
    final Injector injector = Guice.createInjector(new CommonFrontendModule(), new PluginLoaderModule(), new IDLFrontendModule(), new ADLFrontendModule() {

        protected void configureErrorLoader() {
            bind(Loader.class).annotatedWith(Names.named("ErrorLoader")).toChainStartingWith(ErrorLoader.class).endingWith(Loader.class);
        }
    });
    loader = injector.getInstance(Key.get(Loader.class, Names.named("ErrorLoader")));
    // ensure that phases are empty.
    FooProcessor.phases = new ArrayList<ProcessParams>();
}
Example 9
Project: Magnolia-master  File: MagnoliaScopes.java View source code
@Override
public <T> Provider<T> scope(Key<T> key, final Provider<T> creator) {
    final String name = key.toString();
    return new Provider<T>() {

        @Override
        public T get() {
            HttpServletRequest request = getRequest();
            if (request == null) {
                return null;
            }
            synchronized (request) {
                Object obj = request.getAttribute(name);
                if (NullObject.INSTANCE == obj) {
                    return null;
                }
                @SuppressWarnings("unchecked") T t = (T) obj;
                if (t == null) {
                    t = creator.get();
                    request.setAttribute(name, (t != null) ? t : NullObject.INSTANCE);
                }
                return t;
            }
        }

        @Override
        public String toString() {
            return String.format("%s[%s]", creator, LOCAL);
        }
    };
}
Example 10
Project: mini-git-server-master  File: ChangeMergeQueue.java View source code
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
    return new Provider<T>() {

        public T get() {
            return getContext().get(key, creator);
        }

        @Override
        public String toString() {
            return String.format("%s[%s]", creator, REQUEST);
        }
    };
}
Example 11
Project: commons-old-master  File: DefaultProvider.java View source code
/**
   * Creates a DefaultProvider and installs a new module to {@code binder}, which will serve as
   * an indirection layer for swapping the default binding with a custom one.
   *
   * @param customBinding The custom binding key.
   * @param defaultBinding The default binding key.
   * @param exposedBinding The exposed binding key.
   * @param binder The binder to install bindings to.
   * @param <T> The type of binding to make.
   */
public static <T> void bindOrElse(final Key<T> customBinding, final Key<T> defaultBinding, final Key<T> exposedBinding, Binder binder) {
    Preconditions.checkNotNull(customBinding);
    Preconditions.checkNotNull(defaultBinding);
    Preconditions.checkNotNull(exposedBinding);
    Preconditions.checkArgument(!customBinding.equals(defaultBinding) && !customBinding.equals(exposedBinding));
    binder.install(new AbstractModule() {

        @Override
        protected void configure() {
            Provider<T> defaultProvider = new DefaultProvider<T>(defaultBinding, customBinding);
            requestInjection(defaultProvider);
            bind(exposedBinding).toProvider(defaultProvider);
        }
    });
}
Example 12
Project: torodb-master  File: MongoDbReplModule.java View source code
@Override
protected void configure() {
    expose(TopologyService.class);
    expose(ReplCoordinator.class);
    expose(OplogManager.class);
    bind(ReplCoordinator.class).in(Singleton.class);
    bind(OplogManager.class).in(Singleton.class);
    bind(ReplCoordinatorStateMachine.class).in(Singleton.class);
    install(new MongoClientWrapperModule());
    expose(CachedMongoClientFactory.class);
    bind(OplogReaderProvider.class).to(MongoOplogReaderProvider.class).asEagerSingleton();
    install(new FactoryModuleBuilder().implement(//To use the applier service that delegates on a OplogApplier
    OplogApplierService.class, DefaultOplogApplierService.class).build(OplogApplierService.OplogApplierServiceFactory.class));
    install(new FactoryModuleBuilder().implement(RecoveryService.class, RecoveryService.class).build(RecoveryService.RecoveryServiceFactory.class));
    install(new FactoryModuleBuilder().implement(ContinuousOplogFetcher.class, ContinuousOplogFetcher.class).build(ContinuousOplogFetcher.ContinuousOplogFetcherFactory.class));
    bind(DbCloner.class).annotatedWith(MongoDbRepl.class).toProvider(AkkaDbClonerProvider.class).in(Singleton.class);
    expose(Key.get(DbCloner.class, MongoDbRepl.class));
    bind(OplogApplier.class).to(DefaultOplogApplier.class).in(Singleton.class);
    bind(DefaultOplogApplier.BatchLimits.class).toInstance(new BatchLimits(1000, Duration.ofSeconds(2)));
    bind(CommitHeuristic.class).to(DefaultCommitHeuristic.class).in(Singleton.class);
    bind(Integer.class).annotatedWith(DocsPerTransaction.class).toInstance(1000);
    bind(ConcurrentOplogBatchExecutor.class).in(Singleton.class);
    bind(AnalyzedOplogBatchExecutor.class).to(ConcurrentOplogBatchExecutor.class);
    expose(AnalyzedOplogBatchExecutor.class);
    bind(ConcurrentOplogBatchExecutor.ConcurrentOplogBatchExecutorMetrics.class).in(Singleton.class);
    bind(AnalyzedOplogBatchExecutor.AnalyzedOplogBatchExecutorMetrics.class).to(ConcurrentOplogBatchExecutorMetrics.class);
    bind(ConcurrentOplogBatchExecutor.SubBatchHeuristic.class).toInstance((ConcurrentOplogBatchExecutorMetrics metrics) -> 100);
    install(new FactoryModuleBuilder().implement(BatchAnalyzer.class, BatchAnalyzer.class).build(BatchAnalyzer.BatchAnalyzerFactory.class));
    bind(AnalyzedOpReducer.class).toInstance(new AnalyzedOpReducer(false));
    install(new TopologyGuiceModule());
    bind(MongodbReplConfig.class).toInstance(config);
    bind(ReplMetrics.class).in(Singleton.class);
    bind(OplogApplierMetrics.class).in(Singleton.class);
    bind(OplogOperationApplier.class).in(Singleton.class);
    bind(NamespaceJobExecutor.class).in(Singleton.class);
    install(new ReplCommandsGuiceModule());
    install(new MongoLayerModule(new ReplCommandImplementionsModule()));
    expose(MongodServer.class);
}
Example 13
Project: WaveInCloud-master  File: ServerMain.java View source code
public static void run(Module coreSettings) throws PersistenceException, ConfigurationException, WaveServerException {
    Injector settingsInjector = Guice.createInjector(coreSettings);
    boolean enableFederation = settingsInjector.getInstance(Key.get(Boolean.class, Names.named(CoreSettings.ENABLE_FEDERATION)));
    if (enableFederation) {
        Module federationSettings = SettingsBinder.bindSettings(PROPERTIES_FILE_KEY, FederationSettings.class);
        // This MUST happen first, or bindings will fail if federation is enabled.
        settingsInjector = settingsInjector.createChildInjector(federationSettings);
    }
    Module federationModule = buildFederationModule(settingsInjector, enableFederation);
    PersistenceModule persistenceModule = settingsInjector.getInstance(PersistenceModule.class);
    Injector injector = settingsInjector.createChildInjector(new ServerModule(enableFederation), new RobotApiModule(), federationModule, persistenceModule);
    ServerRpcProvider server = injector.getInstance(ServerRpcProvider.class);
    WaveBus waveBus = injector.getInstance(WaveBus.class);
    String domain = injector.getInstance(Key.get(String.class, Names.named(CoreSettings.WAVE_SERVER_DOMAIN)));
    if (!ParticipantIdUtil.isDomainAddress(ParticipantIdUtil.makeDomainAddress(domain))) {
        throw new WaveServerException("Invalid wave domain: " + domain);
    }
    initializeServer(injector, domain);
    initializeServlets(injector, server);
    initializeRobotAgents(injector, server);
    initializeRobots(injector, waveBus);
    initializeFrontend(injector, server, waveBus);
    initializeFederation(injector);
    LOG.info("Starting server");
    server.startWebSocketServer(injector);
}
Example 14
Project: wave-protocol-master  File: ServerMain.java View source code
public static void run(Module coreSettings) throws PersistenceException, ConfigurationException, WaveServerException {
    Injector settingsInjector = Guice.createInjector(coreSettings);
    boolean enableFederation = settingsInjector.getInstance(Key.get(Boolean.class, Names.named(CoreSettings.ENABLE_FEDERATION)));
    if (enableFederation) {
        Module federationSettings = SettingsBinder.bindSettings(PROPERTIES_FILE_KEY, FederationSettings.class);
        // This MUST happen first, or bindings will fail if federation is enabled.
        settingsInjector = settingsInjector.createChildInjector(federationSettings);
    }
    Module federationModule = buildFederationModule(settingsInjector, enableFederation);
    PersistenceModule persistenceModule = settingsInjector.getInstance(PersistenceModule.class);
    Injector injector = settingsInjector.createChildInjector(new ServerModule(enableFederation), new RobotApiModule(), federationModule, persistenceModule);
    ServerRpcProvider server = injector.getInstance(ServerRpcProvider.class);
    WaveBus waveBus = injector.getInstance(WaveBus.class);
    String domain = injector.getInstance(Key.get(String.class, Names.named(CoreSettings.WAVE_SERVER_DOMAIN)));
    if (!ParticipantIdUtil.isDomainAddress(ParticipantIdUtil.makeDomainAddress(domain))) {
        throw new WaveServerException("Invalid wave domain: " + domain);
    }
    initializeServer(injector, domain);
    initializeServlets(injector, server);
    initializeRobotAgents(injector, server);
    initializeRobots(injector, waveBus);
    initializeFrontend(injector, server, waveBus);
    initializeFederation(injector);
    LOG.info("Starting server");
    server.startWebSocketServer(injector);
}
Example 15
Project: acteur-master  File: ResponseImpl.java View source code
@Override
public void setBodyWriter(ResponseWriter writer) {
    Page p = Page.get();
    Application app = p.getApplication();
    Dependencies deps = app.getDependencies();
    HttpEvent evt = deps.getInstance(HttpEvent.class);
    Charset charset = deps.getInstance(Charset.class);
    ByteBufAllocator allocator = deps.getInstance(ByteBufAllocator.class);
    Codec mapper = deps.getInstance(Codec.class);
    Key<ExecutorService> key = Key.get(ExecutorService.class, Names.named(ServerModule.BACKGROUND_THREAD_POOL_NAME));
    ExecutorService svc = deps.getInstance(key);
    setWriter(writer, charset, allocator, mapper, evt, svc);
}