Java Code Examples for com.google.inject.Guice

The following examples show how to use com.google.inject.Guice. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: opt4j   Source File: AbstractArchiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public void update() {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);

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

	TestArchive archive = new TestArchive();

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

	Assert.assertTrue(archive.update(i0));
	Assert.assertTrue(archive.contains(i0));
}
 
Example 2
Source Project: Velocity   Source File: JavaPluginLoader.java    License: MIT License 6 votes vote down vote up
@Override
public PluginContainer createPlugin(PluginDescription description) throws Exception {
  if (!(description instanceof JavaVelocityPluginDescription)) {
    throw new IllegalArgumentException("Description provided isn't of the Java plugin loader");
  }

  JavaVelocityPluginDescription javaDescription = (JavaVelocityPluginDescription) description;
  Optional<Path> source = javaDescription.getSource();

  if (!source.isPresent()) {
    throw new IllegalArgumentException("No path in plugin description");
  }

  Injector injector = Guice
      .createInjector(new VelocityPluginModule(server, javaDescription, baseDirectory));
  Object instance = injector.getInstance(javaDescription.getMainClass());

  if (instance == null) {
    throw new IllegalStateException(
        "Got nothing from injector for plugin " + javaDescription.getId());
  }

  return new VelocityPluginContainer(description, instance);
}
 
Example 3
/**
 * 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 4
Source Project: kafka-pubsub-emulator   Source File: BaseIT.java    License: 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 5
private Injector createInjector()
{
    try
    {
        return Guice.createInjector(new ExternalDependenciesModule(this));

    }
    catch (Exception e)
    {
        String msg = MessageFormat.format(Messages.BslValidator_Failed_to_create_injector_for_0,
            getBundle().getSymbolicName());
        log(createErrorStatus(msg, e));
        return null;

    }
}
 
Example 6
Source Project: hmdm-server   Source File: Initializer.java    License: Apache License 2.0 6 votes vote down vote up
protected Injector getInjector() {
    boolean success = false;

    final StringWriter errorOut = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errorOut);
    try {
        this.injector = Guice.createInjector(Stage.PRODUCTION, this.getModules());
        success = true;
    } catch (Exception e){
        System.err.println("[HMDM-INITIALIZER]: Unexpected error during injector initialization: " + e);
        e.printStackTrace();
        e.printStackTrace(errorWriter);
    }
    if (success) {
        System.out.println("[HMDM-INITIALIZER]: Application initialization was successful");
        onInitializationCompletion(null);
    } else {
        System.out.println("[HMDM-INITIALIZER]: Application initialization has failed");
        onInitializationCompletion(errorOut);
    }
    return injector;
}
 
Example 7
@Test
public void test_memory_persistence() {
    when(persistenceConfigurationService.getMode()).thenReturn(PersistenceConfigurationService.PersistenceMode.IN_MEMORY);

    final Injector injector = Guice.createInjector(
            new PersistenceMigrationModule(new MetricRegistry(), persistenceConfigurationService),
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(SystemInformation.class).toInstance(systemInformation);
                    bindScope(LazySingleton.class, LazySingletonScope.get());
                    bind(MqttConfigurationService.class).toInstance(mqttConfigurationService);
                }
            });

    assertTrue(injector.getInstance(RetainedMessageLocalPersistence.class) instanceof RetainedMessageMemoryLocalPersistence);
    assertTrue(injector.getInstance(PublishPayloadLocalPersistence.class) instanceof PublishPayloadMemoryLocalPersistence);
}
 
Example 8
@Before
public void setUp() throws Exception {

    MockitoAnnotations.initMocks(this);

    testConfigurationBootstrap = new TestConfigurationBootstrap();
    final FullConfigurationService fullConfigurationService = testConfigurationBootstrap.getFullConfigurationService();

    injector = Guice.createInjector(new SystemInformationModule(new SystemInformationImpl()), new ConfigurationModule(fullConfigurationService, new HivemqId()),
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(SharedSubscriptionService.class).toInstance(sharedSubscriptionService);
                }
            });
}
 
Example 9
@Test
public void test_topic_matcher_not_same() {

    final Injector injector = Guice.createInjector(Stage.PRODUCTION,
            new HiveMQMainModule(),
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(EventExecutorGroup.class).toInstance(Mockito.mock(EventExecutorGroup.class));
                }
            });

    final TopicMatcher instance1 = injector.getInstance(TopicMatcher.class);
    final TopicMatcher instance2 = injector.getInstance(TopicMatcher.class);

    assertNotSame(instance1, instance2);

}
 
Example 10
@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 11
Source Project: opt4j   Source File: CrowdingArchiveTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {

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

	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);

	for (int i = 0; i < SIZE; i++) {
		Individual individual = factory.create();
		Objectives objectives = new Objectives();
		objectives.add(o0, i);
		objectives.add(o1, SIZE - i);
		individual.setObjectives(objectives);
		set.add(individual);
	}
}
 
Example 12
private void createClientConnection(AsynchronousSocketChannel socketChannel) {
	Injector injector = Guice.createInjector(getGLSPModule());
	GsonConfigurator gsonConf = injector.getInstance(GsonConfigurator.class);

	InputStream in = Channels.newInputStream(socketChannel);
	OutputStream out = Channels.newOutputStream(socketChannel);

	Consumer<GsonBuilder> configureGson = (GsonBuilder builder) -> gsonConf.configureGsonBuilder(builder);
	Function<MessageConsumer, MessageConsumer> wrapper = Function.identity();
	GLSPServer languageServer = injector.getInstance(GLSPServer.class);

	Launcher<GLSPClient> launcher = Launcher.createIoLauncher(languageServer, GLSPClient.class, in, out, threadPool,
			wrapper, configureGson);
	languageServer.connect(launcher.getRemoteProxy());
	launcher.startListening();

	try {
		SocketAddress remoteAddress = socketChannel.getRemoteAddress();
		log.info("Started language server for client " + remoteAddress);
	} catch (IOException ex) {
		log.error("Failed to get the remoteAddress for the new client connection: " + ex.getMessage(), ex);
	}
}
 
Example 13
@Before
public void before()
{
	Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);

	// Set up spec weapon
	ItemContainer equipment = mock(ItemContainer.class);
	when(equipment.getItem(EquipmentInventorySlot.WEAPON.getSlotIdx())).thenReturn(new Item(ItemID.BANDOS_GODSWORD, 1));
	when(client.getItemContainer(InventoryID.EQUIPMENT)).thenReturn(equipment);

	// Set up special attack energy
	when(client.getVar(VarPlayer.SPECIAL_ATTACK_PERCENT)).thenReturn(100);
	specialCounterPlugin.onVarbitChanged(new VarbitChanged());

}
 
Example 14
Source Project: sofa-ark   Source File: ArkServiceContainer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Start Ark Service Container
 * @throws ArkRuntimeException
 * @since 0.1.0
 */
public void start() throws ArkRuntimeException {
    if (started.compareAndSet(false, true)) {
        ClassLoader oldClassLoader = ClassLoaderUtils.pushContextClassLoader(getClass()
            .getClassLoader());
        try {
            LOGGER.info("Begin to start ArkServiceContainer");

            injector = Guice.createInjector(findServiceModules());
            for (Binding<ArkService> binding : injector
                .findBindingsByType(new TypeLiteral<ArkService>() {
                })) {
                arkServiceList.add(binding.getProvider().get());
            }
            Collections.sort(arkServiceList, new OrderComparator());

            for (ArkService arkService : arkServiceList) {
                LOGGER.info(String.format("Init Service: %s", arkService.getClass().getName()));
                arkService.init();
            }

            ArkServiceContainerHolder.setContainer(this);
            ArkClient.setBizFactoryService(getService(BizFactoryService.class));
            ArkClient.setBizManagerService(getService(BizManagerService.class));
            ArkClient.setInjectionService(getService(InjectionService.class));
            ArkClient.setEventAdminService(getService(EventAdminService.class));
            ArkClient.setArguments(arguments);
            LOGGER.info("Finish to start ArkServiceContainer");
        } finally {
            ClassLoaderUtils.popContextClassLoader(oldClassLoader);
        }

    }

}
 
Example 15
Source Project: opt4j   Source File: AbstractArchiveTest.java    License: 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 16
Source Project: Getaviz   Source File: RDOutputStandaloneSetup.java    License: Apache License 2.0 5 votes vote down vote up
public Injector createInjector() {
	return Guice.createInjector(new RDRuntimeModule() {
		@Override
		public Class<? extends IGenerator2> bindIGenerator2() {
			return RDOutput.class;
		}
	});
}
 
Example 17
Source Project: opt4j   Source File: AbstractArchiveOptimalityTester.java    License: 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 18
Source Project: plugins   Source File: ScreenshotPluginTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Before
public void before()
{
	Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);
	when(screenshotConfig.screenshotLevels()).thenReturn(true);
	when(screenshotConfig.screenshotValuableDrop()).thenReturn(true);
	when(screenshotConfig.screenshotUntradeableDrop()).thenReturn(true);
}
 
Example 19
private void initializeSystemUnderTest() {
  underTest = Guice.createInjector(new TransactionModule(), new AbstractModule() {
    @Override
    protected void configure() {
      bind(IndexYamlBuilder.class).toInstance(indexYamlBuilder);
    }
  }).getInstance(CreateIndexServiceImpl.class);
}
 
Example 20
Source Project: opt4j   Source File: SequentialIndividualCompleterTest.java    License: MIT License 5 votes vote down vote up
@Test
public void evaluate() throws TerminationException {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);
	Individual i1 = factory.create();

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

	i1.setPhenotype("my phenotype");
	Assert.assertTrue(i1.getState().equals(State.PHENOTYPED));
	completer.evaluate(i1);
	Assert.assertTrue(i1.getState().equals(State.EVALUATED));
	// Assert.assertTrue(i1.getObjectives() == objectives);
}
 
Example 21
Source Project: plugins   Source File: XpTrackerPluginTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Before
public void before()
{
	Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);

	when(client.getLocalPlayer()).thenReturn(mock(Player.class));

	xpTrackerPlugin.setXpPanel(mock(XpPanel.class));
}
 
Example 22
Source Project: opt4j   Source File: AbstractArchiveTest.java    License: MIT License 5 votes vote down vote up
/**
 * Tests {@link AbstractArchive#removeDominatedCandidates(List)} with two
 * nondominated individuals.
 */
@Test
public void removeDominatedCandidatesTest() {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);

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

	TestArchive archive = new TestArchive();

	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.removeDominatedCandidates(list);

	Assert.assertEquals(2, list.size());
	Assert.assertTrue(list.contains(i0));
	Assert.assertTrue(list.contains(i1));
}
 
Example 23
Source Project: opt4j   Source File: AbstractArchiveTest.java    License: MIT License 5 votes vote down vote up
/**
 * Tests {@link AbstractArchive#removeDominatedCandidates(List)} with two
 * individuals which dominate themselves.
 */
@Test
public void removeDominatedCandidatesTest2() {
	Injector injector = Guice.createInjector(new MockProblemModule());
	IndividualFactory factory = injector.getInstance(IndividualFactory.class);

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

	TestArchive archive = new TestArchive();

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

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

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

	Assert.assertEquals(1, list.size());
	Assert.assertTrue(list.contains(i0));

	list.clear();
	list.add(i1);
	list.add(i0);
	archive.removeDominatedCandidates(list);

	Assert.assertEquals(1, list.size());
	Assert.assertTrue(list.contains(i0));
}
 
Example 24
Source Project: opt4j   Source File: Opt4JTask.java    License: MIT License 5 votes vote down vote up
/**
 * Initialize a task manually before executing it. This enables to get
 * instances of classes before the optimization starts.
 */
public synchronized void open() {
	if (injector == null && !isClosed) {
		if (!isInit) {
			throw new IllegalStateException("Task is not initialized. Call method init(modules) first.");
		}
		if (parentInjector == null) {
			injector = Guice.createInjector(modules);
		} else {
			injector = parentInjector.createChildInjector(modules);
		}
	}
}
 
Example 25
Source Project: hadoop-ozone   Source File: AbstractReconSqlDBTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void createReconSchemaForTest() throws IOException {
  injector = Guice.createInjector(getReconSqlDBModules());
  dslContext = DSL.using(new DefaultConfiguration().set(
      injector.getInstance(DataSource.class)));
  createSchema(injector);
}
 
Example 26
Source Project: opt4j   Source File: SequentialIndividualCompleterTest.java    License: 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 27
Source Project: hadoop-ozone   Source File: TestReconContainerDBProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  tempFolder.create();
  injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      File dbDir = tempFolder.getRoot();
      OzoneConfiguration configuration = new OzoneConfiguration();
      configuration.set(OZONE_RECON_DB_DIR, dbDir.getAbsolutePath());
      bind(OzoneConfiguration.class).toInstance(configuration);
      bind(DBStore.class).toProvider(ReconContainerDBProvider.class).in(
          Singleton.class);
    }
  });
}
 
Example 28
@Override
public DataSourceReader createReader(StructType schema, DataSourceOptions options) {
    SparkSession spark = getDefaultSparkSessionOrCreate();

    Injector injector = Guice.createInjector(
            new BigQueryClientModule(),
            new SparkBigQueryConnectorModule(spark, options, Optional.ofNullable(schema)));

    BigQueryDataSourceReader reader = injector.getInstance(BigQueryDataSourceReader.class);
    return reader;
}
 
Example 29
Source Project: java-11-examples   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    ExampleModule exampleModule = new ExampleModule(executor);
    Injector injector = Guice.createInjector(exampleModule, new AppModule());

    messageClientService = injector.getInstance(MessageClientServiceImpl.class);
}
 
Example 30
Source Project: openAGV   Source File: RunPlantOverview.java    License: 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();
}