com.google.inject.Key Java Examples
The following examples show how to use
com.google.inject.Key.
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: BiomedicusScopes.java From biomedicus with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected <T> T get(Key<T> key, Provider<T> unscoped) { T t = (T) objectsMap.get(key); if (t == null) { synchronized (lock) { t = (T) objectsMap.get(key); if (t == null) { t = unscoped.get(); if (!Scopes.isCircularProxy(t)) { objectsMap.put(key, t); } } } } return t; }
Example #2
Source File: DomainRegistryImplTest.java From business with Mozilla Public License 2.0 | 6 votes |
@SuppressWarnings({"unchecked"}) @Test public void testGetRepositoryTypeOfOfTString(final @Mocked Repository<AggregateRoot<Long>, Long> repository1) { DomainRegistry domainRegistry = createDomainRegistry(); new Expectations() { { injector.getInstance((Key<Repository<AggregateRoot<Long>, Long>>) any); result = repository1; } }; Repository<AggregateRoot<Long>, Long> repository2 = domainRegistry.getRepository( new TypeLiteral<Repository<AggregateRoot<Long>, Long>>() {}.getType(), "dummyAnnotation"); assertThat(repository2).isEqualTo(repository1); }
Example #3
Source File: TestResourceSecurity.java From presto with Apache License 2.0 | 6 votes |
@Test public void testInsecureAuthenticatorHttpsOnly() throws Exception { try (TestingPrestoServer server = TestingPrestoServer.builder() .setProperties(ImmutableMap.<String, String>builder() .putAll(SECURE_PROPERTIES) .put("http-server.authentication.allow-insecure-over-http", "false") .build()) .build()) { server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(new TestSystemAccessControl()); HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class)); assertAuthenticationDisabled(httpServerInfo.getHttpUri()); assertInsecureAuthentication(httpServerInfo.getHttpsUri()); } }
Example #4
Source File: PlainInjectorTest.java From xtext-eclipse with Eclipse Public License 2.0 | 6 votes |
@Test public void testChildInjector() { Injector parentInjector = Guice.createInjector(); Injector injector = parentInjector.createChildInjector(new Module() { @Override public void configure(Binder binder) { binder.bind(CharSequence.class).to(String.class); } }); Assert.assertNotNull(injector.getExistingBinding(Key.get(CharSequence.class))); // Parent allows JIT bindings and those are always created in the ancestor Assert.assertNotNull(injector.getExistingBinding(Key.get(String.class))); CharSequence emptyString = injector.getInstance(CharSequence.class); Assert.assertEquals("", emptyString); Assert.assertNotNull(injector.getExistingBinding(Key.get(String.class))); Assert.assertNotNull(parentInjector.getExistingBinding(Key.get(String.class))); }
Example #5
Source File: CliLauncher.java From seed with Mozilla Public License 2.0 | 6 votes |
int execute(String cliCommand, CliContext cliContext, Map<String, String> kernelParameters) throws Exception { if (launched.compareAndSet(false, true)) { KernelConfiguration kernelConfiguration = NuunCore.newKernelConfiguration(); for (Map.Entry<String, String> kernelParameter : kernelParameters.entrySet()) { kernelConfiguration.param(kernelParameter.getKey(), kernelParameter.getValue()); } kernel = Seed.createKernel(cliContext, kernelConfiguration, true); CommandLineHandler cliHandler; try { cliHandler = kernel.objectGraph() .as(Injector.class) .getInstance(Key.get(CommandLineHandler.class, Names.named(cliCommand))); LOGGER.info("Executing CLI command {}, handled by {}", cliCommand, cliHandler.getClass().getCanonicalName()); } catch (ConfigurationException e) { throw SeedException.wrap(e, CliErrorCode.COMMAND_LINE_HANDLER_NOT_FOUND) .put("commandLineHandler", cliCommand); } return cliHandler.call(); } else { throw SeedException.createNew(CliErrorCode.COMMAND_LINE_HANDLER_ALREADY_RUN); } }
Example #6
Source File: ComponentGraph.java From vespa with Apache License 2.0 | 6 votes |
private Node lookupOrCreateGlobalComponent(Node node, Injector fallbackInjector, Class<?> clazz, Key<?> key) { Optional<Node> component = lookupGlobalComponent(key); if (component.isEmpty()) { Object instance; try { log.log(Level.FINE, "Trying the fallback injector to create" + messageForNoGlobalComponent(clazz, node)); instance = fallbackInjector.getInstance(key); } catch (ConfigurationException e) { throw removeStackTrace(new IllegalStateException( (messageForMultipleClassLoaders(clazz).isEmpty()) ? "No global" + messageForNoGlobalComponent(clazz, node) : messageForMultipleClassLoaders(clazz))); } component = Optional.of(matchingGuiceNode(key, instance).orElseGet(() -> { GuiceNode guiceNode = new GuiceNode(instance, key.getAnnotation()); add(guiceNode); return guiceNode; })); } return component.get(); }
Example #7
Source File: TestResourceSecurity.java From presto with Apache License 2.0 | 6 votes |
@Test public void testFixedManagerAuthenticatorHttpInsecureEnabledOnly() throws Exception { try (TestingPrestoServer server = TestingPrestoServer.builder() .setProperties(ImmutableMap.<String, String>builder() .putAll(SECURE_PROPERTIES) .put("http-server.authentication.type", "password") .put("http-server.authentication.allow-insecure-over-http", "true") .put("management.user", MANAGEMENT_USER) .build()) .build()) { server.getInstance(Key.get(PasswordAuthenticatorManager.class)).setAuthenticator(TestResourceSecurity::authenticate); server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(new TestSystemAccessControl()); HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class)); assertFixedManagementUser(httpServerInfo.getHttpUri(), true); assertPasswordAuthentication(httpServerInfo.getHttpsUri()); } }
Example #8
Source File: AbstractConsulTests.java From nano-framework with Apache License 2.0 | 6 votes |
@BeforeClass public static void setup() throws Throwable { PropertiesLoader.load("/cluster-scheduler-context.properties", true); final Injector injector = Guice.createInjector().createChildInjector(new SPIModule()); Globals.set(Injector.class, injector); final Set<String> moduleNames = SPILoader.spiNames(Module.class); if (!CollectionUtils.isEmpty(moduleNames)) { final List<Module> loadedModules = Lists.newArrayList(); for (final String moduleName : moduleNames) { final Module module = injector.getInstance(Key.get(Module.class, Names.named(moduleName))); module.config(config); loadedModules.addAll(module.load()); } Globals.set(Injector.class, injector.createChildInjector(loadedModules)); } }
Example #9
Source File: CryptoPluginTest.java From seed with Mozilla Public License 2.0 | 6 votes |
@Test public void testNativeUnitModule(@Mocked final CryptoModule module, @Mocked final SSLContext sslContext, @Mocked final KeyStore trustStore, @Mocked final KeyManagerAdapter keyManagerAdapter) { final Map<Key<EncryptionService>, EncryptionService> encryptionServices = new HashMap<>(); final Map<String, KeyStore> keyStores = new HashMap<>(); final CryptoPlugin underTest = new CryptoPlugin(); Deencapsulation.setField(underTest, "encryptionServices", encryptionServices); Deencapsulation.setField(underTest, "keyStores", keyStores); Deencapsulation.setField(underTest, "sslContext", sslContext); Deencapsulation.setField(underTest, "trustStore", trustStore); List<KeyManagerAdapter> keyManagerAdapters = Lists.newArrayList(keyManagerAdapter); Deencapsulation.setField(underTest, "keyManagerAdapters", keyManagerAdapters); underTest.nativeUnitModule(); new Verifications() {{ new CryptoModule(encryptionServices, keyStores, trustStore, sslContext, keyManagerAdapters, null); times = 1; }}; }
Example #10
Source File: TypeMapBinder.java From ProjectAres with GNU Affero General Public License v3.0 | 6 votes |
public TypeMapBinder(Binder binder, @Nullable TypeLiteral<K> keyType, @Nullable TypeLiteral<V> valueType) { this.keyType = keyType != null ? keyType : new ResolvableType<K>(){}.in(getClass()); this.valueType = valueType != null ? valueType : new ResolvableType<V>(){}.in(getClass()); final TypeArgument<K> keyTypeArg = new TypeArgument<K>(this.keyType){}; final TypeArgument<V> valueTypeArg = new TypeArgument<V>(this.valueType){}; this.collectionKey = Key.get(new ResolvableType<TypeMap<K, V>>(){}.with(keyTypeArg, valueTypeArg)); this.backingCollectionKey = Key.get(new ResolvableType<Map<TypeToken<? extends K>, Set<V>>>(){}.with(keyTypeArg, valueTypeArg)); this.backingCollectionBinder = MapBinder.newMapBinder( binder, new ResolvableType<TypeToken<? extends K>>(){}.with(keyTypeArg), this.valueType ).permitDuplicates(); binder.install(new KeyedManifest.Impl(collectionKey) { @Override public void configure() { final Provider<Map<TypeToken<? extends K>, Set<V>>> backingCollectionProvider = getProvider(backingCollectionKey); bind(collectionType()).toProvider(() -> ImmutableTypeMap.copyOf(backingCollectionProvider.get())); } }); }
Example #11
Source File: AsyncModuleTest.java From attic-aurora with Apache License 2.0 | 6 votes |
@Test public void testBindings() throws Exception { Injector injector = createInjector(new AsyncModule(new AsyncModule.Options())); control.replay(); Set<Service> services = injector.getInstance( Key.get(new TypeLiteral<Set<Service>>() { }, AppStartup.class)); for (Service service : services) { service.startAsync().awaitRunning(); } injector.getBindings(); assertEquals( ImmutableMap.of( RegisterGauges.TIMEOUT_QUEUE_GAUGE, 0, RegisterGauges.ASYNC_TASKS_GAUGE, 0L), statsProvider.getAllValues() ); }
Example #12
Source File: GroovyDriverTestCase.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override protected void configure(Binder binder) { binder .bind(new Key<Set<GroovyDriverPlugin>>() {}) .toInstance(getPlugins()); binder.bind(InMemoryPlatformMessageBus.class).in(Singleton.class); binder.bind(InMemoryProtocolMessageBus.class).in(Singleton.class); binder.bind(PlatformMessageBus.class).to(InMemoryPlatformMessageBus.class); binder.bind(ProtocolMessageBus.class).to(InMemoryProtocolMessageBus.class); Multibinder.newSetBinder(binder, CompilationCustomizer.class) .addBinding() .to(DriverCompilationCustomizer.class); binder .bind(Scheduler.class) .toInstance(new ExecutorScheduler(Executors.newScheduledThreadPool(1))) ; }
Example #13
Source File: AbstractConsulTests.java From nano-framework with Apache License 2.0 | 6 votes |
@BeforeClass public static void setup() throws Throwable { final Injector injector = Guice.createInjector().createChildInjector(new SPIModule()); Globals.set(Injector.class, injector); final Set<String> moduleNames = SPILoader.spiNames(Module.class); if (!CollectionUtils.isEmpty(moduleNames)) { final List<Module> loadedModules = Lists.newArrayList(); for (final String moduleName : moduleNames) { final Module module = injector.getInstance(Key.get(Module.class, Names.named(moduleName))); module.config(config); loadedModules.addAll(module.load()); } Globals.set(Injector.class, injector.createChildInjector(loadedModules)); } }
Example #14
Source File: DomainRegistryImplTest.java From business with Mozilla Public License 2.0 | 6 votes |
@SuppressWarnings({"unchecked"}) @Test public void testGetServiceTypeOfOfTString(final @Mocked MockedServiceParameterized<Long> service1) { DomainRegistry domainRegistry = createDomainRegistry(); new Expectations() { { injector.getInstance((Key<MockedServiceParameterized<Long>>) any); result = service1; } }; MockedServiceParameterized<Long> service2 = domainRegistry.getService( new TypeLiteral<MockedServiceParameterized<Long>>() {}.getType(), "dummyAnnotation"); assertThat(service2).isEqualTo(service1); }
Example #15
Source File: TestWebUi.java From presto with Apache License 2.0 | 6 votes |
@Test public void testFixedAuthenticator() throws Exception { try (TestingPrestoServer server = TestingPrestoServer.builder() .setProperties(ImmutableMap.<String, String>builder() .putAll(SECURE_PROPERTIES) .put("web-ui.authentication.type", "fixed") .put("web-ui.user", "test-user") .build()) .build()) { HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class)); String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId(); testAlwaysAuthorized(httpServerInfo.getHttpUri(), client, nodeId); testAlwaysAuthorized(httpServerInfo.getHttpsUri(), client, nodeId); testFixedAuthenticator(httpServerInfo.getHttpUri()); testFixedAuthenticator(httpServerInfo.getHttpsUri()); } }
Example #16
Source File: MegabusModule.java From emodb with Apache License 2.0 | 6 votes |
@Override protected void configure() { bind(Integer.class).annotatedWith(NumRefPartitions.class).toInstance(REF_PARTITIONS); bind(RateLimitedLogFactory.class).to(DefaultRateLimitedLogFactory.class).asEagerSingleton(); bind(String.class).annotatedWith(TableEventRegistrationId.class).to(Key.get(String.class, MegabusApplicationId.class)); bind(Service.class).annotatedWith(MegabusRefResolverService.class).to(ResilientMegabusRefResolver.class).asEagerSingleton(); bind(Service.class).annotatedWith(MissingRefDelayService.class).to(ResilientMissingRefDelayProcessor.class).asEagerSingleton(); bind(Service.class).annotatedWith(TableEventRegistrationService.class).to(TableEventRegistrar.class).asEagerSingleton(); bind(Service.class).annotatedWith(TableEventProcessorService.class).to(TableEventProcessorManager.class).asEagerSingleton(); bind(MegabusRefProducerManager.class).asEagerSingleton(); bind(MegabusBootWorkflowManager.class).asEagerSingleton(); bind(MegabusRefSubscriptionMonitorManager.class).asEagerSingleton(); bind(MegabusSource.class).to(DefaultMegabusSource.class).asEagerSingleton(); expose(MegabusSource.class); bind(MegabusRefSubscriptionMonitorManager.class).asEagerSingleton(); }
Example #17
Source File: SecurityInternalModuleIntegrationTest.java From seed with Mozilla Public License 2.0 | 5 votes |
@Test public void configure_should_bind_wanted_components() { SecurityConfig conf = new SecurityConfig(); conf.addUser("Obiwan", new SecurityConfig.UserConfig().setPassword("mdp").addRole("jedi")); when(securityConfigurer.getSecurityConfiguration()).thenReturn(conf); RealmConfiguration confRealm = new RealmConfiguration("ConfigurationRealm", ConfigurationRealm.class); confRealm.setRoleMappingClass(ConfigurationRoleMapping.class); confRealm.setRolePermissionResolverClass(ConfigurationRolePermissionResolver.class); Collection<RealmConfiguration> confRealms = new ArrayList<>(); confRealms.add(confRealm); when(securityConfigurer.getConfigurationRealms()).thenReturn(confRealms); Injector injector = Guice.createInjector(underTest, new DefaultSecurityModule(securityGuiceConfigurer)); //Verify realm Set<Realm> exposedRealms = injector.getInstance(Key.get(new TypeLiteral<Set<Realm>>() { })); assertTrue(exposedRealms.size() > 0); Realm exposedRealm = exposedRealms.iterator().next(); assertEquals(ShiroRealmAdapter.class, exposedRealm.getClass()); ConfigurationRealm innerRealm = (ConfigurationRealm) ((ShiroRealmAdapter) exposedRealm).getRealm(); Set<?> users = Whitebox.getInternalState(innerRealm, "users"); assertTrue(users.size() > 0); assertNotNull(innerRealm.getRoleMapping()); assertEquals(ConfigurationRoleMapping.class, innerRealm.getRoleMapping().getClass()); assertNotNull(innerRealm.getRolePermissionResolver()); assertEquals(ConfigurationRolePermissionResolver.class, innerRealm.getRolePermissionResolver().getClass()); }
Example #18
Source File: ManagedObjectRegistrar.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Inject public ManagedObjectRegistrar(final BeanLocator beanLocator, final MBeanServer server) { checkNotNull(beanLocator); checkNotNull(server); beanLocator.watch(Key.get(Object.class), new ManageObjectMediator(), server); }
Example #19
Source File: SchedulerModule.java From flux with Apache License 2.0 | 5 votes |
@Override protected void configure() { Provider<SessionFactoryContext> provider = getProvider(Key.get(SessionFactoryContext.class, Names.named("schedulerSessionFactoriesContext"))); final TransactionInterceptor transactionInterceptor = new TransactionInterceptor(provider); bindInterceptor(Matchers.inPackage(MessageDao.class.getPackage()), Matchers.annotatedWith(Transactional.class), transactionInterceptor); bindInterceptor(Matchers.inPackage(EventSchedulerDao.class.getPackage()), Matchers.annotatedWith(Transactional.class), transactionInterceptor); bindInterceptor(Matchers.inPackage(ClientElbDAOImpl.class.getPackage()), Matchers.annotatedWith(Transactional.class), transactionInterceptor); }
Example #20
Source File: Application.java From greenbeans with Apache License 2.0 | 5 votes |
@Override public Set<Object> getSingletons() { ImmutableSet.Builder<Object> builder = ImmutableSet.<Object> builder(); Map<Key<?>, Binding<?>> bindings = injector.getBindings(); for (Key<?> key : bindings.keySet()) { if (hasAnnotation(key, ImmutableList.of(Path.class, Provides.class, Consumes.class)) && isEligible(key)) { builder.add(injector.getInstance(key)); } } return builder.build(); }
Example #21
Source File: DeviceManagerImpl.java From linstor-server with GNU General Public License v3.0 | 5 votes |
@Override public void notifyDrbdVolumeResized(Volume vlm) { // Remember the resize to clear the flag after DeviceHandler instances have finished synchronized (sched) { drbdResizedVlmSet.add(new VolumeDefinition.Key(vlm)); } }
Example #22
Source File: DeviceManagerImpl.java From linstor-server with GNU General Public License v3.0 | 5 votes |
@Override public void notifySnapshotDeleted(Snapshot snapshot) { // Remember the snapshot for removal after the DeviceHandler instances have finished synchronized (sched) { deletedSnapshotSet.add(new SnapshotDefinition.Key(snapshot.getSnapshotDefinition())); } }
Example #23
Source File: NexusLifecycleManager.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Inject public NexusLifecycleManager(final BeanLocator locator, @Named("system") final Bundle systemBundle) { this.locator = checkNotNull(locator); this.systemBundle = checkNotNull(systemBundle); this.lifecycles = locator.locate(Key.get(Lifecycle.class, Named.class)); locator.watch(Key.get(BundleContext.class), new BundleContextMediator(), this); }
Example #24
Source File: TckListener.java From che with Eclipse Public License 2.0 | 5 votes |
private TckResourcesCleaner getResourcesCleaner(Injector injector, Key<TckResourcesCleaner> key) { try { return injector.getInstance(key); } catch (ConfigurationException ignored) { } return null; }
Example #25
Source File: KaryonAbstractInjectorGrapher.java From karyon with Apache License 2.0 | 5 votes |
@Override public final void graph(Injector injector, Set<Key<?>> root) throws IOException { reset(); Iterable<Binding<?>> bindings = getBindings(injector, root); Map<NodeId, NodeId> aliases = resolveAliases(aliasCreator .createAliases(bindings)); createNodes(nodeCreator.getNodes(bindings), aliases); createEdges(edgeCreator.getEdges(bindings), aliases); postProcess(); }
Example #26
Source File: Injection.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
public static Key<?> dependencyKey(Key<?> key) { if(isImplicitProvider(key.getTypeLiteral())) { return Key.get(providedType((TypeLiteral<? extends Provider<Object>>) key.getTypeLiteral())); } else { return key; } }
Example #27
Source File: V3JobManagerModule.java From titus-control-plane with Apache License 2.0 | 5 votes |
@Override protected void configure() { bind(Key.get(JOB_DIFFERENCE_RESOLVER, Names.named(JobReconciliationFrameworkFactory.BATCH_RESOLVER))).to(BatchDifferenceResolver.class); bind(Key.get(JOB_DIFFERENCE_RESOLVER, Names.named(JobReconciliationFrameworkFactory.SERVICE_RESOLVER))).to(ServiceDifferenceResolver.class); bind(V3JobOperations.class).to(DefaultV3JobOperations.class); bind(ReadOnlyJobOperations.class).to(DefaultV3JobOperations.class); bind(JobSubmitLimiter.class).to(DefaultJobSubmitLimiter.class); bind(TaskInfoRequestFactory.class).to(DefaultV3TaskInfoRequestFactory.class); bind(KubeNotificationProcessorInitializer.class).asEagerSingleton(); bind(JobAndTaskMetrics.class).asEagerSingleton(); }
Example #28
Source File: KinesisConnectorFactory.java From presto-kinesis with Apache License 2.0 | 5 votes |
/** * Convenience method to get the table description supplier. * * @param inj Injector for table description supplier * @return Returns Table Description Supplier for kinesis table */ protected KinesisTableDescriptionSupplier getTableDescSupplier(Injector inj) { requireNonNull(inj, "Injector is missing in getTableDescSupplier"); Supplier<Map<SchemaTableName, KinesisStreamDescription>> supplier = inj.getInstance(Key.get(new TypeLiteral<Supplier<Map<SchemaTableName, KinesisStreamDescription>>>() {})); requireNonNull(inj, "Injector cannot find any table description supplier"); return (KinesisTableDescriptionSupplier) supplier; }
Example #29
Source File: MatchBinders.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
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
Source File: BindingUtils.java From seed with Mozilla Public License 2.0 | 5 votes |
/** * Same as {@link #resolveBindingDefinitions(Class, Class, Class...)}. * * @param injecteeClass the parent class to reach * @param implClasses the sub classes collection * @return a multimap with typeliterals for keys and a list of associated subclasses for values */ @SuppressWarnings("unchecked") public static <T> Map<Key<T>, Class<? extends T>> resolveBindingDefinitions(Class<T> injecteeClass, Collection<Class<? extends T>> implClasses) { if (implClasses != null && !implClasses.isEmpty()) { return resolveBindingDefinitions(injecteeClass, null, implClasses.toArray(new Class[implClasses.size()])); } return new HashMap<>(); }