Java Code Examples for com.google.inject.Injector

The following are top voted examples for showing how to use com.google.inject.Injector. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: grpc-mate   File: ServiceLauncher.java   View source code 6 votes vote down vote up
/**
 * Start the micro service.
 */
public static void main(final String[] args) {
  try {
    final Injector injector =
        Guice.createInjector(new ElasticSearchModule());
    //start http server in daemon mode
    injector
        .getInstance(HttpServer.class)
        .start();
    //start grpc server
    injector
        .getInstance(GrpcServer.class)
        .start()
        // blocks until VM shutdown begins
        .awaitTermination();

  } catch (Exception ex) {
    log.error("failed to start ip-elasticsearch service ", ex);
    throw new IllegalStateException("failed to start elasticsearch service ", ex);
  }
}
 
Example 2
Project: grpc-mate   File: TransportClientProviderTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  String ip = esContainer.getContainerIpAddress();
  Integer transportPort = esContainer.getMappedPort(9300);
  MapConfiguration memoryParams = new MapConfiguration(new HashMap<>());
  memoryParams.setProperty(CONFIG_ES_CLUSTER_HOST, ip);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_PORT, transportPort);
  memoryParams.setProperty(CONFIG_ES_CLUSTER_NAME, "elasticsearch");
  Injector injector = Guice.createInjector(
      Modules.override(new ElasticSearchModule()).with(
          binder -> {
            binder.bind(Configuration.class).toInstance(memoryParams);
          }
      )
  );
  transportClientProvider = injector.getInstance(TransportClientProvider.class);
}
 
Example 3
Project: violet   File: LazyTest.java   View source code 6 votes vote down vote up
@Test
public void testLazy() {
  final Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      this.bind(Thing.class).to(ThingA.class);
      this.bindLazy(Thing.class).annotatedWith(Names.named("b")).to(ThingB.class);
      this.bindLazy(Thing.class).annotatedWith(Names.named("c")).to(ThingC.class);
    }
  });
  final Things things = injector.getInstance(Things.class);
  assertNotSame(things.ap.get(), things.ap.get());
  assertSame(things.al.get(), things.al.get());
  assertSame(things.bl.get(), things.bl.get());
  assertSame(things.cl.get(), things.cl.get());
  assertSame(things.dl.get(), things.dl.get());
}
 
Example 4
Project: paraflow   File: HDFSConnectorFactory.java   View source code 6 votes vote down vote up
@Override
public Connector create(String connectorId, Map<String, String> config, ConnectorContext context)
{
    requireNonNull(config, "config is null");

    try {
        Bootstrap app = new Bootstrap(
                new JsonModule(),
                new HDFSModule(connectorId, context.getTypeManager())
        );

        Injector injector = app
                .strictConfig()
                .doNotInitializeLogging()
                .setRequiredConfigurationProperties(config)
                .initialize();

        return injector.getInstance(HDFSConnector.class);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Project: n4js   File: DuplicateResourceAwareFileSetupContext.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Resource load(final ResourceSet resourceSet, final URI uri, final InputStream input) throws IOException {
	final Injector injector = IXtInjectorProvider.INSTANCE.getInjector(context.get(XpectJavaModel.class), uri);
	final Resource resource = injector.getInstance(IResourceFactory.class).createResource(uri);
	final Resource existingResousce = from(resourceSet.getResources())
			.firstMatch(r -> r.getURI().equals(resource.getURI())).orNull();
	if (null != existingResousce) {
		// remove the existing one
		resourceSet.getResources().remove(existingResousce);
	}
	resourceSet.getResources().add(resource);
	try {
		resource.load(input, null);
	} finally {
		if (input != null)
			input.close();
	}
	return resource;
}
 
Example 6
Project: n4js   File: UnicodeStandaloneSetupGenerated.java   View source code 6 votes vote down vote up
@Override
public Injector createInjectorAndDoEMFRegistration() {
	// register default ePackages
	if (!Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().containsKey("ecore"))
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
			"ecore", new EcoreResourceFactoryImpl());
	if (!Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().containsKey("xmi"))
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
			"xmi", new XMIResourceFactoryImpl());
	if (!Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().containsKey("xtextbin"))
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
			"xtextbin", new BinaryGrammarResourceFactoryImpl());
	if (!EPackage.Registry.INSTANCE.containsKey(XtextPackage.eNS_URI))
		EPackage.Registry.INSTANCE.put(XtextPackage.eNS_URI, XtextPackage.eINSTANCE);

	Injector injector = createInjector();
	register(injector);
	return injector;
}
 
Example 7
Project: hadoop   File: TestWebAppTests.java   View source code 6 votes vote down vote up
@Test public void testInstances() throws Exception {
  Injector injector = WebAppTests.createMockInjector(this);
  HttpServletRequest req = injector.getInstance(HttpServletRequest.class);
  HttpServletResponse res = injector.getInstance(HttpServletResponse.class);
  String val = req.getParameter("foo");
  PrintWriter out = res.getWriter();
  out.println("Hello world!");
  logInstances(req, res, out);

  assertSame(req, injector.getInstance(HttpServletRequest.class));
  assertSame(res, injector.getInstance(HttpServletResponse.class));
  assertSame(this, injector.getInstance(TestWebAppTests.class));

  verify(req).getParameter("foo");
  verify(res).getWriter();
  verify(out).println("Hello world!");
}
 
Example 8
Project: bromium   File: DefaultModuleTest.java   View source code 6 votes vote down vote up
@Test
public void canCreateRecordBrowserProvider() throws IOException, URISyntaxException {
    String command = RECORD;
    Map<String, Object> opts = new HashMap<>();
    opts.put(DRIVER, chromedriverFile.getAbsolutePath());
    opts.put(APPLICATION, configurationFile.getAbsolutePath());
    opts.put(URL, localhostUrl);
    opts.put(OUTPUT, "output.json");
    opts.put(BROWSER, CHROME);
    opts.put(TIMEOUT, timeoutString);
    opts.put(SCREEN, screenString);
    Module module = new DefaultModule(command, opts);
    Injector injector = Guice.createInjector(module);
    IOURIProvider<RecordBrowser> instance = injector.getInstance(new Key<IOURIProvider<RecordBrowser>>() {});
    RecordBrowser recordBrowser = instance.get();

    // cleanup
    recordBrowser.cleanUp();
}
 
Example 9
Project: endpoint-health   File: EndPointHealthServerLifeCycleListener.java   View source code 6 votes vote down vote up
@Override
public void lifeCycleStarted(final LifeCycle event) {
    LOGGER.info("Starting End Point Health server");

    final Injector injector = (Injector) servletContext.getAttribute(Injector.class.getName());

    endPointCheckSchedulerService = Optional.ofNullable(injector.getInstance(EndPointCheckSchedulerService.class));

    if (endPointCheckSchedulerService.isPresent()) {
        endPointCheckSchedulerService.get().start();
    } else {
        throw new EndPointHealthException("Unable to get EndPointCheckService instance");
    }

    LOGGER.info("End Point Health server started");
}
 
Example 10
Project: hadoop   File: TestHSWebApp.java   View source code 6 votes vote down vote up
@Test
public void testLogsView2() throws IOException {
  LOG.info("HsLogsPage with data");
  MockAppContext ctx = new MockAppContext(0, 1, 1, 1);
  Map<String, String> params = new HashMap<String, String>();

  params.put(CONTAINER_ID, MRApp.newContainerId(1, 1, 333, 1)
      .toString());
  params.put(NM_NODENAME, 
      NodeId.newInstance(MockJobs.NM_HOST, MockJobs.NM_PORT).toString());
  params.put(ENTITY_STRING, "container_10_0001_01_000001");
  params.put(APP_OWNER, "owner");

  Injector injector =
      WebAppTests.testPage(AggregatedLogsPage.class, AppContext.class, ctx,
          params);
  PrintWriter spyPw = WebAppTests.getPrintWriter(injector);
  verify(spyPw).write(
      "Aggregation is not enabled. Try the nodemanager at "
          + MockJobs.NM_HOST + ":" + MockJobs.NM_PORT);
}
 
Example 11
Project: nifi-config   File: PortServiceTest.java   View source code 6 votes vote down vote up
/**
 * Creates a token for accessing the REST API via username/password
 * <p>
 * The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header in the format &#39;Authorization: Bearer &lt;token&gt;&#39;.
 *
 * @throws ApiException if the Api call fails
 */
@Test
public void getByIdInputTest() throws ApiException, IOException, URISyntaxException {
    Injector injector = Guice.createInjector(new AbstractModule() {
        protected void configure() {
            bind(InputPortsApi.class).toInstance(inputPortsApiMock);
            bind(OutputPortsApi.class).toInstance(outputPortsApiMock);
            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);
        }
    });
    PortService portService = injector.getInstance(PortService.class);
    PortEntity port = new PortEntity();
    port.setComponent(new PortDTO());
    port.getComponent().setId("id");
    when(inputPortsApiMock.getInputPort("id")).thenReturn(port);
    PortEntity portResult = portService.getById("id", PortDTO.TypeEnum.INPUT_PORT);
    assertEquals("id", portResult.getComponent().getId());
}
 
Example 12
Project: Re-Collector   File: Run.java   View source code 6 votes vote down vote up
private Injector getInjector() {
    Injector injector = null;

    try {
        injector = CollectorInjector.createInjector(new ConfigurationModule(configFile),
                new BufferModule(),
                new InputsModule(),
                new FileModule(),
                new OutputsModule(),
                new ServicesModule(),
                new MetricsModule(),
                new MemoryReporterModule(),
                new ServerApiModule(),
                new HeartbeatModule(),
                new CollectorIdModule(),
                new CollectorHostNameModule());
    } catch (Exception e) {
        LOG.error("ERROR: {}", e.getMessage());
        LOG.debug("Detailed injection creation error", e);
        doExit();
    }

    return injector;
}
 
Example 13
Project: abhot   File: GuiceGroupByFactory.java   View source code 6 votes vote down vote up
@Inject
@SuppressWarnings("unchecked")
public GuiceGroupByFactory(Injector injector)
{
	this.injector = injector;
	Map<Key<?>, Binding<?>> bindings = injector.getAllBindings();

	for (Key<?> key : bindings.keySet())
	{
		Class<?> bindingClass = key.getTypeLiteral().getRawType();
		if (GroupBy.class.isAssignableFrom(bindingClass))
		{
			GroupByName name = (GroupByName)bindingClass.getAnnotation(GroupByName.class);
			if (name == null)
				throw new IllegalStateException("Aggregator class "+bindingClass.getName()+
						" does not have required annotation "+GroupByName.class.getName());

			groupBys.put(name.name(), (Class<GroupBy>)bindingClass);
		}
	}
}
 
Example 14
Project: violet   File: VBinderTest.java   View source code 5 votes vote down vote up
@Test
public void testFactory() {
  final Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      this.installFactory(FooThingFactory.class, builder -> builder.implement(FooThing.class, FooThingImpl.class));
    }
  });
  final FooThings things = injector.getInstance(FooThings.class);
  assertEquals(100, things.factory.create(100).value());
}
 
Example 15
Project: bromium   File: DslActivator.java   View source code 5 votes vote down vote up
public Injector getInjector(String language) {
	synchronized (injectors) {
		Injector injector = injectors.get(language);
		if (injector == null) {
			injectors.put(language, injector = createInjector(language));
		}
		return injector;
	}
}
 
Example 16
Project: hadoop   File: TestHtmlBlock.java   View source code 5 votes vote down vote up
@Test public void testUsual() {
  Injector injector = WebAppTests.testBlock(TestBlock.class);
  PrintWriter out = injector.getInstance(PrintWriter.class);

  verify(out).print(" id=\"testid\"");
  verify(out).print("test note");
}
 
Example 17
Project: OCCI-Studio   File: OCCIStandaloneSetupGenerated.java   View source code 5 votes vote down vote up
@Override
public Injector createInjectorAndDoEMFRegistration() {
	TerminalsStandaloneSetup.doSetup();

	Injector injector = createInjector();
	register(injector);
	return injector;
}
 
Example 18
Project: dragoman   File: AbstractResourceTest.java   View source code 5 votes vote down vote up
@BeforeEach
@SuppressWarnings("unchecked")
public void start() {
  Injector injector =
      Guice.createInjector(
          Modules.override(new DragomanModule()).with(new RestOverridesModule()));
  injector.injectMembers(this);

  startHttpServer();
}
 
Example 19
Project: junit5-extensions   File: GuiceExtension.java   View source code 5 votes vote down vote up
@Override
public boolean supportsParameter(ParameterContext parameterContext,
    ExtensionContext extensionContext)
    throws ParameterResolutionException {
  Parameter parameter = parameterContext.getParameter();
  if (getBindingAnnotations(parameter).size() > 1) {
    return false;
  }

  Key<?> key = getKey(
      extensionContext.getTestClass(),
      parameter);
  Optional<Injector> optInjector = getInjectorForParameterResolution(extensionContext);
  return optInjector.map(injector -> injector.getExistingBinding(key)).isPresent();
}
 
Example 20
Project: hrrs   File: Distiller.java   View source code 5 votes vote down vote up
public static void main(String[] args, DistillerModuleFactory moduleFactory) throws IOException {
    Config config = Config.of(args);
    config.dump();
    DistillerModule module = moduleFactory.create(config);
    Injector injector = Guice.createInjector(module);
    LoggerLevelAccessor loggerLevelAccessor = injector.getInstance(LoggerLevelAccessor.class);
    LoggerLevels.applyLoggerLevelSpecs(config.getLoggerLevelSpecs(), loggerLevelAccessor);
    Distiller distiller = injector.getInstance(Distiller.class);
    try {
        distiller.run();
    } finally {
        distiller.close();
    }
}
 
Example 21
Project: hadoop   File: TestRMWebServicesAppsModification.java   View source code 5 votes vote down vote up
private Injector getNoAuthInjectorFair() {
  return Guice.createInjector(new FairTestServletModule() {
    @Override
    protected void configureServlets() {
      setAuthFilter = false;
      super.configureServlets();
    }
  });
}
 
Example 22
Project: OCCI-Studio   File: OCCIStandaloneSetupGenerated.java   View source code 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("occi", resourceFactory);
	IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("occi", serviceProvider);
}
 
Example 23
Project: n4js   File: N4MFInjectorProvider.java   View source code 5 votes vote down vote up
@Override
public Injector getInjector()
{
	if (injector == null) {
		stateBeforeInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
		this.injector = internalCreateInjector();
		stateAfterInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
	}
	return injector;
}
 
Example 24
Project: ja-micro   File: ServiceRegistryModule.java   View source code 5 votes vote down vote up
@Provides
public ServiceDiscoveryProvider getDiscoveryProvider(Injector injector) {
    if (discoveryProvider == null) {
        Object plugin = getServiceRegistryPlugin(injector);
        if (plugin != null && plugin instanceof ServiceDiscoveryProvider) {
            discoveryProvider = (ServiceDiscoveryProvider) plugin;
        }
    }
    return discoveryProvider;
}
 
Example 25
Project: outland   File: ServerMain.java   View source code 5 votes vote down vote up
@Override
protected void applicationOnRun(ServerConfiguration configuration, Environment environment,
    Injector injector) {

  enableContentEncodingGzip(environment);
  configureAuth(configuration.auth, environment, injector);
}
 
Example 26
Project: n4js   File: TypesStandaloneSetupGenerated.java   View source code 5 votes vote down vote up
@Override
public Injector createInjectorAndDoEMFRegistration() {
	TypeExpressionsStandaloneSetup.doSetup();

	Injector injector = createInjector();
	register(injector);
	return injector;
}
 
Example 27
Project: ja-micro   File: ServiceRegistryModule.java   View source code 5 votes vote down vote up
private Object findServiceRegistryPlugin(Injector injector) {
    Object retval = null;
    String pluginName = serviceProperties.getProperty("registry");
    if (StringUtils.isBlank(pluginName)) {
        return null;
    }
    if (serviceRegistryPlugins == null) { // only scan if not already set
        serviceRegistryPlugins = new FastClasspathScanner().scan().getNamesOfClassesWithAnnotation(ServiceRegistryPlugin.class);
    }
    boolean found = false;
    for (String plugin : serviceRegistryPlugins) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends ServiceRegistryPlugin> pluginClass =
                    (Class<? extends ServiceRegistryPlugin>) Class.forName(plugin);
            ServiceRegistryPlugin anno = pluginClass.getAnnotation(ServiceRegistryPlugin.class);
            if (anno != null && pluginName.equals(anno.name())) {
                retval = injector.getInstance(pluginClass);
                found = true;
                break;
            }
        } catch (ClassNotFoundException e) {
            logger.error("ServiceRegistryPlugin not found", e);
        }
    }
    if (! found) {
        logger.warn("Registry plugin '{}' was not found in the class path", pluginName);
    }
    return retval;
}
 
Example 28
Project: parabuild-ci   File: DwrGuiceServlet.java   View source code 5 votes vote down vote up
private static void initApplicationScoped()
{
    Injector injector = getInjector();
    for (Key<?> key : DwrScopes.APPLICATION.getKeysInScope())
    {
        // Eagerly create application-scoped object.
        injector.getInstance(key);
    }
}
 
Example 29
Project: projectegon   File: ProjectEgon.java   View source code 5 votes vote down vote up
public static Injector getInjector() {
    if(injector == null) {
        injector = Guice.createInjector(
            new ServerModule(),
            new DataModule()
        );
    }
    return injector;
}
 
Example 30
Project: java8-jersey2-guice4-webapp   File: AppServletContextListener.java   View source code 5 votes vote down vote up
@Override
protected Injector getInjector() {
  Injector injector = Guice.createInjector(
    Stage.PRODUCTION,
    new JerseyGuiceModule("__HK2_Generated_0"),
    new ServletModule(),
    new AppModule()
  );

  JerseyGuiceUtils.install(injector);

  return injector;
}
 
Example 31
Project: n4js   File: N4ExecutableExtensionFactory.java   View source code 5 votes vote down vote up
@Override
public final Object create() throws CoreException {
	try {
		final Class<?> clazz = getClassLoader().loadClass(clazzName);
		final Injector injector = getInjector();
		final Object result = injector.getInstance(clazz);
		if (result instanceof IExecutableExtension) {
			((IExecutableExtension) result).setInitializationData(config, null, null);
		}
		return result;
	} catch (final Exception e) {
		throw new CoreException(new Status(ERROR, getBunleId(),
				nullToEmpty(e.getMessage()) + " ExtensionFactory: " + getClass().getName(), e));
	}
}
 
Example 32
Project: jedai-ui   File: MethodConfiguration.java   View source code 5 votes vote down vote up
/**
 * Display the window with the automatically generated form that allows the user to set a method's parameters.
 *
 * @param callerClass Class to get class loader from, to use for loading the window's FXML file
 * @param injector    Injector to use when loading FXML, so that the model etc. are injected automatically.
 * @param method      Method that the window should display configuration options for.
 */
public static void displayModal(Class callerClass, Injector injector, IDocumentation method, ListProperty<JPair<String, Object>> paramsProperty) {
    Parent root;
    FXMLLoader loader = new FXMLLoader(
            callerClass.getClassLoader().getResource("wizard-fxml/DynamicConfiguration.fxml"),
            null,
            new JavaFXBuilderFactory(),
            injector::getInstance
    );

    try {
        root = loader.load();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    root.getProperties().put("controller", loader.getController());

    Object controller = loader.getController();
    if (controller instanceof DynamicConfigurationController) {
        // Cast the controller instance since we know it's safe here
        DynamicConfigurationController popupController = (DynamicConfigurationController) controller;

        // Give the configuration options to the controller
        JsonArray params = method.getParameterConfiguration();
        popupController.setParameters(params, paramsProperty);

        // Create the popup
        Stage dialog = new Stage();
        dialog.setScene(new Scene(root));
        dialog.setTitle("JedAI - Parameter Configuration");
        dialog.initModality(Modality.APPLICATION_MODAL);

        dialog.show();
    } else {
        // This shouldn't ever happen.
        System.err.println("Error when showing the parameter customization popup (Wrong controller instance?)");
    }
}
 
Example 33
Project: Minefana   File: MinefanaSponge.java   View source code 5 votes vote down vote up
@Inject
MinefanaSponge(Logger logger, Injector injector) {
    this.logger = logger;

    this.core = new AnalyticsCore(this, logger);
    this.playerCollector = new SpongePlayerCollector(core);
    this.injector = injector.createChildInjector(binder -> {
        binder.bind(AnalyticsCore.class).toInstance(core);
        binder.bind(InfluxConnector.class).toInstance(core.getConnector());
    });
}
 
Example 34
Project: gemoc-studio   File: GExpressionsInjectorProvider.java   View source code 5 votes vote down vote up
protected Injector internalCreateInjector() {
	return new GExpressionsStandaloneSetup() {
		@Override
		public Injector createInjector() {
			return Guice.createInjector(createRuntimeModule());
		}
	}.createInjectorAndDoEMFRegistration();
}
 
Example 35
Project: governator-vault   File: LifeCycleConfigurationTest.java   View source code 5 votes vote down vote up
@Test
public void moduleInjection() throws Exception {
    vault.logical().write(SECRET_PATH, STATIC_TEST_DATA_SET);
    Injector injector = lifeCycleInjector(SECRET_PATH, EMPTY_VARIABLE_VALUES);
    StaticConfigObject subject = injector.getInstance(StaticConfigObject.class);
    assertTestDataSet(subject);
}
 
Example 36
Project: Equella   File: DependencyAnalyzer.java   View source code 5 votes vote down vote up
private void analyzeDependencies(final Collection<Dependency<?>> dependencies)
{
	for( final Dependency<?> d : dependencies )
	{
		final Key<?> key = d.getKey();
		InjectionPoint injectionPoint = d.getInjectionPoint();
		if( injectionPoint != null && injectionPoint.isOptional() )
		{
			continue;
		}
		if( key.getAnnotationType() == Assisted.class )
		{
			continue;
		}
		TypeLiteral<?> typeLiteral = key.getTypeLiteral();
		Class<?> rawType = typeLiteral.getRawType();
		if( rawType == Injector.class )
		{
			continue;
		}
		if( rawType == MembersInjector.class )
		{
			Key<?> injectedKey = key
				.ofType(((ParameterizedType) typeLiteral.getType()).getActualTypeArguments()[0]);
			dependentKeys.add(injectedKey);
			analyzeImplementation(injectedKey.getTypeLiteral(), true);
		}
		else if( rawType == Provider.class )
		{
			dependentKeys.add(key.ofType(((ParameterizedType) typeLiteral.getType()).getActualTypeArguments()[0]));
		}
		else
		{
			dependentKeys.add(key);
		}
	}
}
 
Example 37
Project: bromium   File: DefaultModuleTest.java   View source code 5 votes vote down vote up
@Test
public void canSupplyMeasurementsFile() {
    String measurementsFile = "measurements.csv";
    Map<String, Object> opts = new HashMap<>();
    opts.put(MEASUREMENTS, measurementsFile);
    Module module = new DefaultModule(REPLAY, opts);
    Injector injector = Guice.createInjector(module);

    File actualMeasurementsFile = injector.getInstance(Key.get(File.class, Names.named(MEASUREMENTS_FILE)));
    assertEquals(measurementsFile, actualMeasurementsFile.getName());

    File actualHarFile = injector.getInstance(Key.get(File.class, Names.named(HAR_FILE)));
    assertEquals(measurementsFile + HAR_EXTENSION, actualHarFile.getName());
}
 
Example 38
Project: ProjectAres   File: Grapher.java   View source code 5 votes vote down vote up
public void writeGraph(File file, Injector injector) throws IOException {
    final PrintWriter out = new PrintWriter(file, Charsets.UTF_8.name());
    final GraphvizGrapher grapher = Guice.createInjector(new GraphvizModule()).getInstance(GraphvizGrapher.class);

    grapher.setOut(out);
    grapher.setRankdir("TB");
    grapher.graph(injector);
}
 
Example 39
Project: outland   File: GuiceApplication.java   View source code 5 votes vote down vote up
private void registerWithInjector(Environment environment, Injector injector) throws Exception {
  registerHealthChecks(environment, injector);
  registerProviders(environment, injector);
  registerResources(environment, injector);
  registerTasks(environment, injector);
  registerManaged(environment, injector);
}
 
Example 40
Project: json2java4idea   File: GuiceManager.java   View source code 5 votes vote down vote up
@Nonnull
public Injector getInjector() {
    if (injector == null) {
        throw new IllegalStateException("Injector has not been initialized yet, ot has been already disposed");
    }
    return injector;
}