Java Code Examples for com.google.inject.Guice#createInjector()

The following examples show how to use com.google.inject.Guice#createInjector() . 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: BaseIT.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
private static Injector getInjector() throws IOException {
  File serverConfig = TEMPORARY_FOLDER.newFile();
  File pubSubRepository = TEMPORARY_FOLDER.newFile();
  Files.write(pubSubRepository.toPath(), Configurations.PUBSUB_CONFIG_JSON.getBytes(UTF_8));

  if (!USE_SSL) {
    Files.write(serverConfig.toPath(), Configurations.SERVER_CONFIG_JSON.getBytes(UTF_8));
  } else {
    // Update certificate paths
    String updated =
        Configurations.SSL_SERVER_CONFIG_JSON
            .replace("/path/to/server.crt", ClassLoader.getSystemResource("server.crt").getPath())
            .replace(
                "/path/to/server.key", ClassLoader.getSystemResource("server.key").getPath());
    Files.write(serverConfig.toPath(), updated.getBytes(UTF_8));
  }
  return Guice.createInjector(
      new DefaultModule(serverConfig.getPath(), pubSubRepository.getPath()));
}
 
Example 2
Source File: PubsubEmulatorServer.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize and start the PubsubEmulatorServer.
 *
 * <p>To set an external configuration file must be considered argument
 * `configuration.location=/to/path/application.yaml` the properties will be merged.
 */
public static void main(String[] args) {
  Args argObject = new Args();
  JCommander jCommander = JCommander.newBuilder().addObject(argObject).build();
  jCommander.parse(args);
  if (argObject.help) {
    jCommander.usage();
    return;
  }
  Injector injector =
      Guice.createInjector(new DefaultModule(argObject.configurationFile, argObject.pubSubFile));
  PubsubEmulatorServer pubsubEmulatorServer = injector.getInstance(PubsubEmulatorServer.class);
  try {
    pubsubEmulatorServer.start();
    pubsubEmulatorServer.blockUntilShutdown();
  } catch (IOException | InterruptedException e) {
    logger.atSevere().withCause(e).log("Unexpected server failure");
  }
}
 
Example 3
Source File: AbstractHealthServiceTest.java    From cassandra-sidecar with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() throws InterruptedException
{
    Injector injector = Guice.createInjector(Modules.override(new MainModule()).with(getTestModule()));
    server = injector.getInstance(HttpServer.class);

    check = injector.getInstance(MockHealthCheck.class);
    service = injector.getInstance(HealthService.class);
    vertx = injector.getInstance(Vertx.class);
    config = injector.getInstance(Configuration.class);

    VertxTestContext context = new VertxTestContext();
    server.listen(config.getPort(), context.completing());

    context.awaitCompletion(5, TimeUnit.SECONDS);
}
 
Example 4
Source File: Configurator.java    From opt4j with MIT License 6 votes vote down vote up
/**
 * Starts the {@link Configurator} with the specified task class and the
 * file to be loaded.
 * 
 * @param taskClass
 *            the task class
 * @param filename
 *            the filename of the configuration file to be loaded
 */
public void main(final Class<? extends Task> taskClass, final String filename) {

	try {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	} catch (Exception e) {
		e.printStackTrace();
	}

	Module module = getModule(taskClass);

	final Injector injector = Guice.createInjector(module);

	SwingUtilities.invokeLater(new Runnable() {
		@Override
		public void run() {
			ApplicationFrame frame = injector.getInstance(ApplicationFrame.class);
			frame.startup();
			if (filename != null) {
				File file = new File(filename);
				FileOperations fo = injector.getInstance(FileOperations.class);
				fo.load(file);
			}
		}
	});
}
 
Example 5
Source File: MetricsModuleTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
    MockitoAnnotations.initMocks(this);

    injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            final Injector persistenceInjector = mock(Injector.class);
            when(persistenceInjector.getInstance(MetricsHolder.class)).thenReturn(mock(MetricsHolder.class));
            final NettyConfiguration nettyConfiguration = mock(NettyConfiguration.class);
            when(nettyConfiguration.getChildEventLoopGroup()).thenReturn(mock(EventLoopGroup.class));

            bind(NettyConfiguration.class).toInstance(nettyConfiguration);
            bind(ChannelGroup.class).toInstance(mock(ChannelGroup.class));
            bind(ClientSessionLocalPersistence.class).toInstance(mock(ClientSessionLocalPersistence.class));
            bind(LocalTopicTree.class).toInstance(mock(TopicTreeImpl.class));
            bind(RetainedMessagePersistence.class).toInstance(mock(RetainedMessagePersistence.class));
            bind(SystemInformation.class).toInstance(mock(SystemInformation.class));
            bindScope(LazySingleton.class, LazySingletonScope.get());

            install(new MetricsModule(new MetricRegistry(), persistenceInjector));
        }
    });
}
 
Example 6
Source File: ResourceDefinitionSatelliteTest.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    errorReporter = new StdErrorReporter("TESTS", Paths.get("build/test-logs"), true, "", null, null, () -> null);
    Injector injector = Guice.createInjector(
        new GuiceConfigModule(),
        new LoggingModule(errorReporter),
        new TestSecurityModule(SYS_CTX),
        new CoreModule(),
        new SatelliteDbModule(),
        new SatelliteTransactionMgrModule(),
        new TestApiModule()
    );
    injector.injectMembers(this);
    TransactionMgr transMgr = new SatelliteTransactionMgr();
    testScope.enter();
    testScope.seed(TransactionMgr.class, transMgr);

    resDfnUuid = UUID.randomUUID();
}
 
Example 7
Source File: Hismo2JSONStandaloneSetup.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
public Injector createInjector() {
	return Guice.createInjector(new HismoRuntimeModule() {

		@Override
		public Class<? extends IGenerator2> bindIGenerator2() {
			return Hismo2JSON.class;
		}
	});
}
 
Example 8
Source File: AbstractArchiveTest.java    From opt4j with MIT License 5 votes vote down vote up
/**
 * Tests {@link AbstractArchive#removeArchiveDominated(List)} with a
 * dominated individual.
 */
@Test
public void removeArchiveDominatedTest2() {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);

	Objective o0 = new Objective("o0");
	Objective o1 = new Objective("o1");

	Individual iArchived0 = factory.create();
	Objectives objectivesA0 = new Objectives();
	objectivesA0.add(o0, 2);
	objectivesA0.add(o1, 3);
	iArchived0.setObjectives(objectivesA0);

	Individual iArchived1 = factory.create();
	Objectives objectivesA1 = new Objectives();
	objectivesA1.add(o0, 3);
	objectivesA1.add(o1, 2);
	iArchived1.setObjectives(objectivesA1);

	TestArchive archive = new TestArchive();
	archive.addAll(iArchived0, iArchived1);

	Individual i0 = factory.create();
	Objectives objectives0 = new Objectives();
	objectives0.add(o0, 4);
	objectives0.add(o1, 4);
	i0.setObjectives(objectives0);

	List<Individual> list = new ArrayList<>();
	list.add(i0);
	archive.removeArchiveDominated(list);

	Assert.assertTrue(list.isEmpty());
	Assert.assertEquals(2, archive.size());
}
 
Example 9
Source File: SequentialIndividualCompleterTest.java    From opt4j with MIT License 5 votes vote down vote up
@Test
public void complete() throws TerminationException {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);
	Individual i1 = factory.create();

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

	completer.complete(i1);

	Assert.assertTrue(i1.isEvaluated());
	Assert.assertTrue(i1.isEvaluated());
}
 
Example 10
Source File: AzureBackupRestoreTest.java    From cassandra-backup with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup() throws Exception {

    final List<Module> modules = new ArrayList<Module>() {{
        add(new KubernetesApiModule());
        add(new AzureModule());
        add(new ExecutorsModule());
    }};

    final Injector injector = Guice.createInjector(modules);
    injector.injectMembers(this);

    init();
}
 
Example 11
Source File: SingletonModuleTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test
public void test_singleton_provider_module_configured_executed_once() throws Exception {
    final SingletonProviderModuleWithConfiguredMethod module1 = new SingletonProviderModuleWithConfiguredMethod();
    final SingletonProviderModuleWithConfiguredMethod module2 = new SingletonProviderModuleWithConfiguredMethod();

    final Injector injector = Guice.createInjector(module1, module2);
    injector.getInstance(String.class);
    injector.getInstance(String.class);

    assertTrue(module1.accessed ^ module2.accessed);
    assertTrue(module1.provided ^ module2.provided);
}
 
Example 12
Source File: AbstractArchiveOptimalityTester.java    From opt4j with MIT License 5 votes vote down vote up
/**
 * Test a given {@link Opt4JModule}.
 * 
 * @param archiveModule
 *            the archive module under test
 */
protected void archiveOptimalityTest(Opt4JModule archiveModule) {
	Injector injector = Guice.createInjector(archiveModule);
	Archive archive = injector.getInstance(Archive.class);

	fillArchive(injector, archive);

	Assert.assertTrue(archive.contains(first));
	Assert.assertTrue(archive.contains(last));
	Assert.assertTrue(archive.contains(randMin));

	testOptimalityOfAllIndividuals(archive);
}
 
Example 13
Source File: RunPlantOverview.java    From openAGV with Apache License 2.0 5 votes vote down vote up
/**
 * The plant overview client's main entry point.
 *
 * @param args the command line arguments
 */
@SuppressWarnings("deprecation")
public static void main(final String[] args) {
  System.setSecurityManager(new SecurityManager());
  Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionLogger(false));
  System.setProperty(org.opentcs.util.configuration.Configuration.PROPKEY_IMPL_CLASS,
                     org.opentcs.util.configuration.XMLConfiguration.class.getName());

  Environment.logSystemInfo();

  Injector injector = Guice.createInjector(customConfigurationModule());
  injector.getInstance(PlantOverviewStarter.class).startPlantOverview();
}
 
Example 14
Source File: TestSystemTableHandle.java    From presto with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void startUp()
{
    Injector injector = Guice.createInjector(new JsonModule(), new HandleJsonModule());

    objectMapper = injector.getInstance(ObjectMapper.class);
}
 
Example 15
Source File: GenerateHismoStandaloneSetup.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
public Injector createInjector() {
	return Guice.createInjector(new HismoRuntimeModule() {
		@Override
		public Class<? extends IGenerator2> bindIGenerator2() {
			return GenerateHismo.class;
		}
	});
}
 
Example 16
Source File: SlackClientModuleTest.java    From slack-client with Apache License 2.0 5 votes vote down vote up
@Test
public void itCanHaveBothModulesInstalled() {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      binder().requireAtInjectOnConstructors();

      install(new SlackClientModule());
      install(new com.hubspot.slack.client.SlackClientModule());
    }
  });

  injector.getInstance(SlackClientFactory.class);
  injector.getInstance(SlackWebClient.Factory.class);
}
 
Example 17
Source File: AbstractArchiveTest.java    From opt4j with MIT License 4 votes vote down vote up
/**
 * Tests {@link AbstractArchive#removeArchiveDominated(List)} with two
 * nondominated individuals.
 */
@Test
public void removeArchiveDominatedTest() {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);

	Objective o0 = new Objective("o0");
	Objective o1 = new Objective("o1");

	Individual iArchived0 = factory.create();
	Objectives objectivesA0 = new Objectives();
	objectivesA0.add(o0, 2);
	objectivesA0.add(o1, 3);
	iArchived0.setObjectives(objectivesA0);

	Individual iArchived1 = factory.create();
	Objectives objectivesA1 = new Objectives();
	objectivesA1.add(o0, 3);
	objectivesA1.add(o1, 2);
	iArchived1.setObjectives(objectivesA1);

	TestArchive archive = new TestArchive();
	archive.addAll(iArchived0, iArchived1);

	Individual i0 = factory.create();
	Objectives objectives0 = new Objectives();
	objectives0.add(o0, 1);
	objectives0.add(o1, 0);
	i0.setObjectives(objectives0);

	Individual i1 = factory.create();
	Objectives objectives1 = new Objectives();
	objectives1.add(o0, 0);
	objectives1.add(o1, 1);
	i1.setObjectives(objectives1);

	List<Individual> list = new ArrayList<>();
	list.add(i0);
	list.add(i1);
	archive.removeArchiveDominated(list);

	Assert.assertEquals(2, list.size());
	Assert.assertTrue(list.contains(i0));
	Assert.assertTrue(list.contains(i1));
	Assert.assertTrue(archive.isEmpty());
}
 
Example 18
Source File: BackupRestoreCLI.java    From cassandra-backup with Apache License 2.0 4 votes vote down vote up
static void init(final Runnable command,
                 final CassandraJMXSpec jmxSpec,
                 final OperationRequest operationRequest,
                 final Logger logger,
                 final List<Module> appSpecificModules) {

    final List<Module> modules = new ArrayList<>();

    if (jmxSpec != null) {
        modules.add(new CassandraModule(new CassandraJMXConnectionInfo(jmxSpec.jmxPassword,
                                                                       jmxSpec.jmxUser,
                                                                       jmxSpec.jmxServiceURL,
                                                                       jmxSpec.trustStore,
                                                                       jmxSpec.trustStorePassword)));
    } else {
        modules.add(new AbstractModule() {
            @Override
            protected void configure() {
                bind(StorageServiceMBean.class).toProvider(() -> null);
                bind(Cassandra4StorageServiceMBean.class).toProvider(() -> null);
            }
        });
    }

    modules.add(new OperationsModule());
    modules.add(new StorageModules());
    modules.add(new ExecutorsModule());
    modules.addAll(appSpecificModules);

    final Injector injector = Guice.createInjector(
        Stage.PRODUCTION, // production binds singletons as eager by default
        modules
    );

    GuiceInjectorHolder.INSTANCE.setInjector(injector);

    injector.injectMembers(command);

    final Validator validator = Validation.byDefaultProvider()
        .configure()
        .constraintValidatorFactory(new GuiceInjectingConstraintValidatorFactory()).buildValidatorFactory()
        .getValidator();

    final Set<ConstraintViolation<OperationRequest>> violations = validator.validate(operationRequest);

    if (!violations.isEmpty()) {
        violations.forEach(violation -> logger.error(violation.getMessage()));
        throw new ValidationException();
    }
}
 
Example 19
Source File: SlackClientModuleTest.java    From slack-client with Apache License 2.0 4 votes vote down vote up
@Test
public void itGuices() {
  Guice.createInjector(Stage.TOOL, new StrictGuiceModule());
}
 
Example 20
Source File: ProxyManagerTest.java    From browserup-proxy with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    Injector injector = Guice.createInjector(new ConfigModule(getArgs()));
    proxyManager = injector.getInstance(MitmProxyManager.class);
}