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 Project: vespa   Author: vespa-engine   File: ComponentGraph.java    License: Apache License 2.0 6 votes vote down vote up
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 #2
Source Project: seed   Author: seedstack   File: CliLauncher.java    License: Mozilla Public License 2.0 6 votes vote down vote up
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 #3
Source Project: presto   Author: prestosql   File: TestResourceSecurity.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: business   Author: seedstack   File: DomainRegistryImplTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@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 #5
Source Project: presto   Author: prestosql   File: TestResourceSecurity.java    License: Apache License 2.0 6 votes vote down vote up
@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 #6
Source Project: presto   Author: prestosql   File: TestWebUi.java    License: Apache License 2.0 6 votes vote down vote up
@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 #7
Source Project: business   Author: seedstack   File: DomainRegistryImplTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@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 #8
Source Project: attic-aurora   Author: apache   File: AsyncModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #9
Source Project: biomedicus   Author: nlpie   File: BiomedicusScopes.java    License: Apache License 2.0 6 votes vote down vote up
@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 #10
Source Project: arcusplatform   Author: arcus-smart-home   File: GroovyDriverTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@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 #11
Source Project: nano-framework   Author: nano-projects   File: AbstractConsulTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #12
Source Project: seed   Author: seedstack   File: CryptoPluginTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@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 #13
Source Project: emodb   Author: bazaarvoice   File: MegabusModule.java    License: Apache License 2.0 6 votes vote down vote up
@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 #14
Source Project: nano-framework   Author: nano-projects   File: AbstractConsulTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #15
Source Project: ProjectAres   Author: OvercastNetwork   File: TypeMapBinder.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 #16
Source Project: xtext-eclipse   Author: eclipse   File: PlainInjectorTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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 #17
Source Project: digdag   Author: treasure-data   File: GuiceRsModule.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public ApplicationBindingBuilder addProviderInstance(Object object)
{
    Key<Object> key = Key.get((Class<Object>) object.getClass(), UniqueAnnotations.create());
    binder.bind(key).toInstance(object);
    initializer.addProvider(key);
    return this;
}
 
Example #18
Source Project: xtext-eclipse   Author: eclipse   File: PlainInjectorTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test(expected = ConfigurationException.class)
public void testEmptyChildInjectorNoJIT() {
	Injector injector = Guice.createInjector().createChildInjector(new Module() {
		@Override
		public void configure(Binder binder) {
			binder.requireExplicitBindings();
		}
	});
	Assert.assertNull(injector.getExistingBinding(Key.get(String.class)));
	injector.getInstance(String.class);
}
 
Example #19
Source Project: business   Author: seedstack   File: DataOverridingModule.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    for (Map.Entry<Key<?>, Class<?>> binding : bindings.entrySet()) {
        LOGGER.trace("Overriding {} with {}", binding.getKey(), binding.getValue()
                .getSimpleName());
        bind(binding.getKey()).to(Classes.cast(binding.getValue()));
    }
}
 
Example #20
Source Project: digdag   Author: treasure-data   File: GuiceRsModule.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> ApplicationBindingBuilder addResources(Class<T> annotatedClass, Provider<? extends T> resourceProvider)
{
    Key<T> key = Key.get(annotatedClass, UniqueAnnotations.create());
    binder.bind(key).toProvider(resourceProvider);
    initializer.addResource((Key<Object>) key, annotatedClass);
    return this;
}
 
Example #21
Source Project: presto   Author: prestosql   File: TestResourceSecurity.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCertAuthenticator()
        throws Exception
{
    try (TestingPrestoServer server = TestingPrestoServer.builder()
            .setProperties(ImmutableMap.<String, String>builder()
                    .putAll(SECURE_PROPERTIES)
                    .put("http-server.authentication.type", "certificate")
                    .put("http-server.https.truststore.path", LOCALHOST_KEYSTORE)
                    .put("http-server.https.truststore.key", "")
                    .build())
            .build()) {
        server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(new TestSystemAccessControl());
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));

        assertAuthenticationDisabled(httpServerInfo.getHttpUri());

        OkHttpClient.Builder clientBuilder = client.newBuilder();
        setupSsl(
                clientBuilder,
                Optional.of(LOCALHOST_KEYSTORE),
                Optional.empty(),
                Optional.of(LOCALHOST_KEYSTORE),
                Optional.empty());
        OkHttpClient clientWithCert = clientBuilder.build();
        assertAuthenticationAutomatic(httpServerInfo.getHttpsUri(), clientWithCert);
    }
}
 
Example #22
Source Project: usergrid   Author: apache   File: MapModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind( MapManagerFactory.class ).to( MapManagerFactoryImpl.class );
    bind( MapSerialization.class ).to( MapSerializationImpl.class );

    Multibinder<Migration> migrationBinding = Multibinder.newSetBinder( binder(), Migration.class );
    migrationBinding.addBinding().to(  Key.get( MapSerialization.class ) );

}
 
Example #23
Source Project: emodb   Author: bazaarvoice   File: EmoModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind(DatabusConfiguration.class).toInstance(_configuration.getDatabusConfiguration());
    // Used by the databus resource to support long polling
    bind(DatabusResourcePoller.class).asEagerSingleton();
    bind(OwnerDatabusAuthorizer.class).asEagerSingleton();

    // Bind the suppressed event condition setting as the supplier
    bind(new TypeLiteral<Supplier<Condition>>(){}).annotatedWith(DefaultJoinFilter.class)
            .to(Key.get(new TypeLiteral<Setting<Condition>>(){}, DefaultJoinFilter.class));
    bind(DatabusDefaultJoinFilterConditionAdminTask.class).asEagerSingleton();

    install(new DatabusModule(_serviceMode, _environment.metrics()));
}
 
Example #24
Source Project: sarl   Author: sarl   File: SARLProjectConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
/** Constructor.
 */
public SARLProjectConfigurator() {
	final Injector injector = SARLEclipseExecutableExtensionFactory.getSARLInjector();
	final String fileExtension = injector.getInstance(
			Key.get(String.class, Names.named(Constants.FILE_EXTENSIONS)));
	if (Strings.isNullOrEmpty(fileExtension)) {
		this.fileExtension = null;
	} else {
		this.fileExtension = "." + fileExtension; //$NON-NLS-1$
	}
	injector.injectMembers(this);
	this.candidates = new ArrayList<>();
	this.candidates.addAll(Arrays.asList(BundleUtil.SRC_FOLDERS));
	this.candidates.add(SARLConfig.FOLDER_TEST_SOURCE_SARL);
}
 
Example #25
Source Project: api-compiler   Author: googleapis   File: Element.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds an attribute value.
 */
@SuppressWarnings("unchecked")
public <T> void addAttribute(Key<List<T>> key, T value) {
  List<T> list = getAttribute(key);
  if (list == null) {
    list = Lists.newArrayList();
    putAttribute(key, list);
  }
  list.add(value);
}
 
Example #26
Source Project: presto   Author: prestosql   File: TestWebUi.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJwtAuthenticator()
        throws Exception
{
    try (TestingPrestoServer server = TestingPrestoServer.builder()
            .setProperties(ImmutableMap.<String, String>builder()
                    .putAll(SECURE_PROPERTIES)
                    .put("http-server.authentication.type", "jwt")
                    .put("http-server.authentication.jwt.key-file", HMAC_KEY)
                    .build())
            .build()) {
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();

        testLogIn(httpServerInfo.getHttpUri(), false);

        testNeverAuthorized(httpServerInfo.getHttpsUri(), client);

        String hmac = Files.readString(Paths.get(HMAC_KEY));
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, hmac)
                .setSubject("test-user")
                .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()))
                .compact();

        OkHttpClient clientWithJwt = client.newBuilder()
                .authenticator((route, response) -> response.request().newBuilder()
                        .header(AUTHORIZATION, "Bearer " + token)
                        .build())
                .build();
        testAlwaysAuthorized(httpServerInfo.getHttpsUri(), clientWithJwt, nodeId);
    }
}
 
Example #27
Source Project: business   Author: seedstack   File: DomainRegistryImplTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testGetFactoryClassOfT(final @Mocked Factory<?> factory) {
    DomainRegistry domainRegistry = createDomainRegistry();

    new Expectations() {
        {
            injector.getInstance((Key<Factory<AggregateRoot<Long>>>) any);
            result = factory;
        }
    };

    assertThat(domainRegistry.getFactory(AggregateRoot.class)).isEqualTo(factory);
}
 
Example #28
Source Project: business   Author: seedstack   File: DomainRegistryImplTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testGetServiceClassOfTClassOfQextendsAnnotation(final @Mocked MockedService service) {
    DomainRegistry domainRegistry = createDomainRegistry();

    new Expectations() {
        {
            injector.getInstance((Key<MockedService>) any);
            result = service;
        }
    };

    assertThat(domainRegistry.getService(MockedService.class, MockedAnnotation.class)).isEqualTo(service);
}
 
Example #29
Source Project: pinpoint   Author: naver   File: DefaultApplicationContextTest.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isPinpointBinding(Key<?> key) {
    TypeLiteral<?> typeLiteral = key.getTypeLiteral();
    if (typeLiteral != null && typeLiteral.toString().startsWith(PINPOINT_PACKAGE_PREFIX)) {
        return true;
    }
    Class<? extends Annotation> annotationType = key.getAnnotationType();
    if (annotationType != null) {
        return annotationType.getName().startsWith(PINPOINT_PACKAGE_PREFIX);
    }
    return false;
}
 
Example #30
Source Project: karyon   Author: Netflix   File: KaryonAbstractInjectorGrapher.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}