com.google.inject.Guice Java Examples

The following examples show how to use com.google.inject.Guice. 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: opt4j   Author: felixreimann   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   Author: VelocityPowered   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
Source Project: kafka-pubsub-emulator   Author: GoogleCloudPlatform   File: PubsubEmulatorServer.java    License: 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 #4
Source Project: kafka-pubsub-emulator   Author: GoogleCloudPlatform   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   Author: h-mdm   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
Source Project: hivemq-community-edition   Author: hivemq   File: PersistenceMigrationModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@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
Source Project: hivemq-community-edition   Author: hivemq   File: ConfigurationModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@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
Source Project: hivemq-community-edition   Author: hivemq   File: HiveMQMainModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@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
Source Project: cassandra-sidecar   Author: apache   File: AbstractHealthServiceTest.java    License: 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 #11
Source Project: opt4j   Author: felixreimann   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
Source Project: graphical-lsp   Author: eclipsesource   File: DefaultGLSPServerLauncher.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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
Source Project: plugins   Author: open-osrs   File: SpecialCounterPluginTest.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);

	// 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   Author: sofastack   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   Author: felixreimann   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   Author: softvis-research   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   Author: felixreimann   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   Author: open-osrs   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
Source Project: nexus-repository-helm   Author: sonatype-nexus-community   File: CreateIndexServiceImplTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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   Author: felixreimann   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   Author: open-osrs   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   Author: felixreimann   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   Author: felixreimann   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   Author: felixreimann   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   Author: apache   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   Author: felixreimann   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   Author: apache   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
Source Project: spark-bigquery-connector   Author: GoogleCloudDataproc   File: BigQueryDataSourceV2.java    License: Apache License 2.0 5 votes vote down vote up
@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   Author: jveverka   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   Author: tcrct   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();
}