Java Code Examples for com.google.inject.Injector#getInstance()

The following examples show how to use com.google.inject.Injector#getInstance() . 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: ResourceServiceProviderServiceLoader.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private Registry loadRegistry() {
	ResourceServiceProviderRegistryImpl registry = new ResourceServiceProviderRegistryImpl();
	for (ISetup cp : setupLoader) {
		Injector injector = cp.createInjectorAndDoEMFRegistration();
		IResourceServiceProvider resourceServiceProvider = injector.getInstance(IResourceServiceProvider.class);
		FileExtensionProvider extensionProvider = injector.getInstance(FileExtensionProvider.class);
		String primaryFileExtension = extensionProvider.getPrimaryFileExtension();
		for (String ext : extensionProvider.getFileExtensions()) {
			if (registry.getExtensionToFactoryMap().containsKey(ext)) {
				if (primaryFileExtension.equals(ext))
					registry.getExtensionToFactoryMap().put(ext, resourceServiceProvider);
			} else {
				registry.getExtensionToFactoryMap().put(ext, resourceServiceProvider);
			}
		}
	}
	return registry;
}
 
Example 2
Source File: SagaModuleBuilderTest.java    From saga-lib with Apache License 2.0 6 votes vote down vote up
/**
 * <pre>
 * Given => Module is configured.
 * When  => String message is added to stream
 * Then  => Monitor reports saga has been started.
 * </pre>
 */
@Test
public void handleString_sagaHandledAsynchronous_isExecutedInBackground() throws InterruptedException {
    // given
    Module sagaModule = SagaModuleBuilder.configure().callModule(TestSagaModule.class).build();
    Injector injector = Guice.createInjector(sagaModule, new CustomModule());
    MessageStream msgStream = injector.getInstance(MessageStream.class);

    // when
    msgStream.add("anyString");

    // then
    SagaMonitor monitor = injector.getInstance(SagaMonitor.class);
    boolean waitSucceeded = monitor.waitForSagaStarted(2, TimeUnit.SECONDS);

    assertThat("Expected saga to be executed.", waitSucceeded, equalTo(true));
}
 
Example 3
Source File: ProcessorServiceTest.java    From nifi-config with Apache License 2.0 6 votes vote down vote up
@Test
public void setStateTest() {
    Injector injector = Guice.createInjector(new AbstractModule() {
        protected void configure() {
            bind(ProcessorsApi.class).toInstance(processorsApiMock);
            bind(Integer.class).annotatedWith(Names.named("timeout")).toInstance(1);
            bind(Integer.class).annotatedWith(Names.named("interval")).toInstance(1);
            bind(Boolean.class).annotatedWith(Names.named("forceMode")).toInstance(false);
        }
    });
    ProcessorService processorService = injector.getInstance(ProcessorService.class);
    ProcessorEntity processor = TestUtils.createProcessorEntity("id", "name");
    processor.getComponent().setState(ProcessorDTO.StateEnum.STOPPED);

    ProcessorEntity processorResponse = TestUtils.createProcessorEntity("id", "name");
    processorResponse.getComponent().setState(ProcessorDTO.StateEnum.RUNNING);
    when(processorsApiMock.updateProcessor(eq("id"), any() )).thenReturn(processorResponse);
    when(processorsApiMock.getProcessor(eq("id"))).thenReturn(processorResponse);

    processorService.setState(processor, ProcessorDTO.StateEnum.RUNNING);
    ArgumentCaptor<ProcessorEntity> processorEntity = ArgumentCaptor.forClass(ProcessorEntity.class);
    verify(processorsApiMock).updateProcessor(eq("id"), processorEntity.capture());
    assertEquals("id", processorEntity.getValue().getComponent().getId());
    assertEquals( ProcessorDTO.StateEnum.RUNNING, processorEntity.getValue().getComponent().getState());
}
 
Example 4
Source File: IndexTestLanguageStandaloneSetupGenerated.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void register(Injector injector) {
	IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class);
	IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class);
	
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("indextestlanguage", resourceFactory);
	IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("indextestlanguage", serviceProvider);
	if (!EPackage.Registry.INSTANCE.containsKey("http://www.eclipse.org/xtext/indexTestLanguage")) {
		EPackage.Registry.INSTANCE.put("http://www.eclipse.org/xtext/indexTestLanguage", IndexTestLanguagePackage.eINSTANCE);
	}
}
 
Example 5
Source File: CommentAssociationTestLanguageStandaloneSetupGenerated.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void register(Injector injector) {
	IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class);
	IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class);
	
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("commentassociationtestlanguage", resourceFactory);
	IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("commentassociationtestlanguage", serviceProvider);
	if (!EPackage.Registry.INSTANCE.containsKey("http://www.eclipse.org/xtext/tests/CommentAssociation")) {
		EPackage.Registry.INSTANCE.put("http://www.eclipse.org/xtext/tests/CommentAssociation", CommentAssociationPackage.eINSTANCE);
	}
}
 
Example 6
Source File: SequentialIndividualCompleterTest.java    From opt4j with MIT License 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void evaluateDifferentObjectivesSize() throws TerminationException {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);
	Individual i1 = factory.create();
	Individual i2 = factory.create();

	SequentialIndividualCompleter completer = injector.getInstance(SequentialIndividualCompleter.class);

	i1.setPhenotype("my phenotype");
	i2.setPhenotype("my other phenotype");
	completer.evaluate(i1);
	objectives.add(new Objective("y"), 4);
	completer.evaluate(i2);
}
 
Example 7
Source File: EmbeddedHiveMQImplTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000L)
public void embeddedHiveMQ_readsConfig() {
    final EmbeddedHiveMQImpl embeddedHiveMQ = new EmbeddedHiveMQImpl(conf, data, extensions);
    embeddedHiveMQ.start().join();

    final Injector injector = embeddedHiveMQ.getInjector();
    final ListenerConfigurationService listenerConfigurationService =
            injector.getInstance(ListenerConfigurationService.class);
    final List<Listener> listeners = listenerConfigurationService.getListeners();

    assertEquals(1, listeners.size());
    assertEquals(randomPort, listeners.get(0).getPort());

    embeddedHiveMQ.stop().join();
}
 
Example 8
Source File: InjectorAsserts.java    From greenbeans with Apache License 2.0 5 votes vote down vote up
public static <T> T assertSingletonBinding(Injector injector, Class<T> clazz) {
	Key<T> key = Key.get(clazz);
	Binding<T> binding = injector.getExistingBinding(key);
	assertNotNull(binding);
	T instance = injector.getInstance(key);
	assertSame(instance, injector.getInstance(key));
	return instance;
}
 
Example 9
Source File: XtextGrammarTestLanguageStandaloneSetupGenerated.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void register(Injector injector) {
	if (!EPackage.Registry.INSTANCE.containsKey("http://www.eclipse.org/2008/testlanguages/xtextgrammar")) {
		EPackage.Registry.INSTANCE.put("http://www.eclipse.org/2008/testlanguages/xtextgrammar", XtextGrammarTestPackage.eINSTANCE);
	}
	IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class);
	IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class);
	
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("xtextgrammar", resourceFactory);
	IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("xtextgrammar", serviceProvider);
}
 
Example 10
Source File: ConditionModelStandaloneSetupGenerated.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public void register(Injector injector) {
    if (!EPackage.Registry.INSTANCE.containsKey("http://www.bonitasoft.org/studio/condition/ConditionModel")) {
        EPackage.Registry.INSTANCE.put("http://www.bonitasoft.org/studio/condition/ConditionModel",
                org.bonitasoft.studio.condition.conditionModel.ConditionModelPackage.eINSTANCE);
    }
    org.eclipse.xtext.resource.IResourceFactory resourceFactory = injector
            .getInstance(org.eclipse.xtext.resource.IResourceFactory.class);
    org.eclipse.xtext.resource.IResourceServiceProvider serviceProvider = injector
            .getInstance(org.eclipse.xtext.resource.IResourceServiceProvider.class);
    Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("cmodel", resourceFactory);
    org.eclipse.xtext.resource.IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("cmodel",
            serviceProvider);
}
 
Example 11
Source File: BaseRecordIntegrationTest.java    From bromium with MIT License 5 votes vote down vote up
@Override
public void runTest() throws IOException {
    /**
     * record
     * -d ./bromium-chrome/bromium-chrome-base/src/test/resources/chromedriver
     * -a /home/hvrigazov/bromium-data/demo-app/configurations/demo.json
     * -u http://localhost:3000
     * -o bromium-core/src/test/resources/dynamic-testCase.json
     */
    File outputFile = createTempFile(pathToTestCase);
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, demoApp.getBaseUrl());
    opts.put(OUTPUT, outputFile.getAbsolutePath());
    opts.put(BROWSER, CHROME);
    opts.put(TIMEOUT, String.valueOf(10));
    opts.put(SCREEN, screen);
    Module defaultModule = new DefaultModule(RECORD, opts);
    Injector originalInjector = Guice.createInjector(defaultModule);
    RecordingSimulatorModule recordingSimulatorModule = new RecordingSimulatorModule(originalInjector);
    recordingSimulatorModule.whenPromptedForRecordingRunnable(this);
    Injector injector = Guice.createInjector(Modules.override(defaultModule).with(recordingSimulatorModule));
    stepsReader = injector.getInstance(Key.get(new TypeLiteral<IOProvider<StepsReader>>() {})).get();
    RecordCommand recordCommand = injector.getInstance(RecordCommand.class);
    recordCommand.run();
    verifyAssertions();
}
 
Example 12
Source File: UnorderedGroupsTestLanguageStandaloneSetupGenerated.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void register(Injector injector) {
	IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class);
	IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class);
	
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("unorderedgroupstestlanguage", resourceFactory);
	IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("unorderedgroupstestlanguage", serviceProvider);
	if (!EPackage.Registry.INSTANCE.containsKey("http://www.eclipse.org/2010/tmf/xtext/UnorderedGroupsTestLanguage")) {
		EPackage.Registry.INSTANCE.put("http://www.eclipse.org/2010/tmf/xtext/UnorderedGroupsTestLanguage", UnorderedGroupsTestLanguagePackage.eINSTANCE);
	}
}
 
Example 13
Source File: TestAHSWebApp.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppPage() throws Exception {
  Injector injector =
      WebAppTests.createMockInjector(ApplicationBaseProtocol.class,
        mockApplicationHistoryClientService(1, 5, 1));
  AppPage appPageInstance = injector.getInstance(AppPage.class);

  appPageInstance.render();
  WebAppTests.flushOutput(injector);

  appPageInstance.set(YarnWebParams.APPLICATION_ID, ApplicationId
    .newInstance(0, 1).toString());
  appPageInstance.render();
  WebAppTests.flushOutput(injector);
}
 
Example 14
Source File: IndividualCompleterModuleTest.java    From opt4j with MIT License 5 votes vote down vote up
@Test
public void configParallel() {
	IndividualCompleterModule module = new IndividualCompleterModule();
	module.setType(Type.PARALLEL);

	Injector injector = Guice.createInjector(new MockProblemModule(), module);
	IndividualCompleter completer = injector.getInstance(IndividualCompleter.class);

	Assert.assertEquals(ParallelIndividualCompleter.class, completer.getClass());
}
 
Example 15
Source File: EcoreFragmentTestLanguageStandaloneSetupGenerated.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void register(Injector injector) {
	IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class);
	IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class);
	
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("ecorefragmenttestlanguage", resourceFactory);
	IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("ecorefragmenttestlanguage", serviceProvider);
	if (!EPackage.Registry.INSTANCE.containsKey("http://www.eclipse.org/2009/tmf/xtext/EcoreFragmentTestLanguage")) {
		EPackage.Registry.INSTANCE.put("http://www.eclipse.org/2009/tmf/xtext/EcoreFragmentTestLanguage", SecondPackage.eINSTANCE);
	}
}
 
Example 16
Source File: CustomExplicitAnnotationTest.java    From guice-validator with MIT License 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    Injector injector = Guice.createInjector(new ValidationModule()
            .validateAnnotatedOnly(ToValidate.class));

    service = injector.getInstance(ExplicitMethod.class);
}
 
Example 17
Source File: ApplicationContextHandler.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private AnnotationKeyRegistryService findAnnotationKeyRegistryService(Injector injector) {
    return injector.getInstance(AnnotationKeyRegistryService.class);
}
 
Example 18
Source File: JoinTest.java    From yql-plus with Apache License 2.0 4 votes vote down vote up
/**
 * Ticket 7143393
 *
 * @throws Exception
 */
@Test
public void testProjectJoinRecordAlias() throws Exception {
    Injector injector = Guice.createInjector(new JavaTestModule());
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile("SELECT p.*, m " +
            "FROM people p LEFT JOIN moreMinions m ON p.id = m.master_id " +
            "OUTPUT AS foo;");
    ProgramResult myResult = program.run(ImmutableMap.<String, Object>of(), true);
    YQLResultSet rez = myResult.getResult("foo").get();
    List<Record> foo = rez.getResult();
    Assert.assertEquals(foo.size(), 4);

    /*
     * Assert record size is 7 fields: all the fields (6) from table "people" plus nested "m" record
     */

    Record record = foo.get(0);
    Assert.assertEquals(Records.getRecordSize(record), 7);
    Assert.assertEquals(record.get("value"), "bob");
    Assert.assertEquals(record.get("id"), "1");
    Assert.assertEquals(record.get("iid"), 1);
    Assert.assertEquals(record.get("iidPrimitive"), 1);
    Assert.assertEquals(record.get("otherId"), "1");
    Assert.assertEquals(record.get("score"), 0);
    Minion minion = (Minion) record.get("m");
    Assert.assertEquals(minion.master_id, "1");
    Assert.assertEquals(minion.minion_id, "2");

    record = foo.get(1);
    Assert.assertEquals(Records.getRecordSize(record), 7);
    Assert.assertEquals(record.get("value"), "bob");
    Assert.assertEquals(record.get("id"), "1");
    Assert.assertEquals(record.get("iid"), 1);
    Assert.assertEquals(record.get("iidPrimitive"), 1);
    Assert.assertEquals(record.get("otherId"), "1");
    Assert.assertEquals(record.get("score"), 0);
    minion = (Minion) record.get("m");
    Assert.assertEquals(minion.master_id, "1");
    Assert.assertEquals(minion.minion_id, "3");
}
 
Example 19
Source File: PublicApi.java    From pay-publicapi with MIT License 4 votes vote down vote up
@Override
public void run(PublicApiConfig configuration, Environment environment) {
    initialiseSSLSocketFactory();

    final Injector injector = Guice.createInjector(new PublicApiModule(configuration, environment));

    environment.healthChecks().register("ping", new Ping());

    environment.jersey().register(injector.getInstance(HealthCheckResource.class));
    environment.jersey().register(injector.getInstance(PaymentsResource.class));
    environment.jersey().register(injector.getInstance(DirectDebitEventsResource.class));
    environment.jersey().register(injector.getInstance(PaymentRefundsResource.class));
    environment.jersey().register(injector.getInstance(RequestDeniedResource.class));
    environment.jersey().register(injector.getInstance(MandatesResource.class));
    environment.jersey().register(injector.getInstance(SearchRefundsResource.class));
    environment.jersey().register(injector.getInstance(DirectDebitPaymentsResource.class));
    environment.jersey().register(injector.getInstance(TransactionsResource.class));
    environment.jersey().register(injector.getInstance(TelephonePaymentNotificationResource.class));
    environment.jersey().register(new InjectingValidationFeature(injector));
    environment.jersey().register(injector.getInstance(ReturnUrlValidator.class));

    environment.jersey().register(injector.getInstance(RateLimiterFilter.class));
    environment.jersey().register(injector.getInstance(LoggingMDCRequestFilter.class));

    environment.servlets().addFilter("ClearMdcValuesFilter", injector.getInstance(ClearMdcValuesFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    environment.servlets().addFilter("AuthorizationValidationFilter", injector.getInstance(AuthorizationValidationFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    environment.servlets().addFilter("LoggingFilter", injector.getInstance(LoggingFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    /*
       Turn off 'FilteringJacksonJaxbJsonProvider' which overrides dropwizard JacksonMessageBodyProvider.
       Fails on Integration tests if not disabled. 
           - https://github.com/dropwizard/dropwizard/issues/1341
    */
    environment.jersey().property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, Boolean.TRUE);

    CachingAuthenticator<String, Account> cachingAuthenticator = new CachingAuthenticator<>(
            environment.metrics(),
            injector.getInstance(AccountAuthenticator.class),
            configuration.getAuthenticationCachePolicy());

    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<Account>()
                    .setAuthenticator(cachingAuthenticator)
                    .setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Account.class));

    attachExceptionMappersTo(environment.jersey());

    initialiseMetrics(configuration, environment);

    //health check removed as redis is not a mandatory dependency
    environment.healthChecks().unregister("redis");
}
 
Example 20
Source File: ESSuiteTest.java    From usergrid with Apache License 2.0 3 votes vote down vote up
private static void setupRunResults( Injector injector ) throws Exception {

        runResultDao = injector.getInstance( RunResultDao.class );

        BasicRunResult runResult = new BasicRunResult( RUN_ID_1, 5, 1000, 0, 1 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_1, 5, 1103, 0, 0 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_2, 5, 1200, 1, 0 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_3, 17, 15789, 2, 2 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_4, 17, 15789, 2, 2 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_4, 17, 15789, 2, 2 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_4, 17, 15789, 2, 2 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_5, RESULT_RUN_COUNT, 15729, 2, 2 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_5, RESULT_RUN_COUNT, 13429, 0, 0 );
        runResultDao.save( runResult );

        runResult = new BasicRunResult( RUN_ID_5, RESULT_RUN_COUNT, 16421, 1, 0 );
        runResultDao.save( runResult );
    }