/** * 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); } }
@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); }
@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()); }
@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; }
/** {@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; }
@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; }
@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!"); }
@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(); }
@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"); }
@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); }
/** * 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 'Authorization: Bearer <token>'. * * @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()); }
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; }
@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); } } }
@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()); }
public Injector getInjector(String language) { synchronized (injectors) { Injector injector = injectors.get(language); if (injector == null) { injectors.put(language, injector = createInjector(language)); } return injector; } }
@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"); }
@Override public Injector createInjectorAndDoEMFRegistration() { TerminalsStandaloneSetup.doSetup(); Injector injector = createInjector(); register(injector); return injector; }
@BeforeEach @SuppressWarnings("unchecked") public void start() { Injector injector = Guice.createInjector( Modules.override(new DragomanModule()).with(new RestOverridesModule())); injector.injectMembers(this); startHttpServer(); }
@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(); }
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(); } }
private Injector getNoAuthInjectorFair() { return Guice.createInjector(new FairTestServletModule() { @Override protected void configureServlets() { setAuthFilter = false; super.configureServlets(); } }); }
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); }
@Override public Injector getInjector() { if (injector == null) { stateBeforeInjectorCreation = GlobalRegistries.makeCopyOfGlobalState(); this.injector = internalCreateInjector(); stateAfterInjectorCreation = GlobalRegistries.makeCopyOfGlobalState(); } return injector; }
@Provides public ServiceDiscoveryProvider getDiscoveryProvider(Injector injector) { if (discoveryProvider == null) { Object plugin = getServiceRegistryPlugin(injector); if (plugin != null && plugin instanceof ServiceDiscoveryProvider) { discoveryProvider = (ServiceDiscoveryProvider) plugin; } } return discoveryProvider; }
@Override protected void applicationOnRun(ServerConfiguration configuration, Environment environment, Injector injector) { enableContentEncodingGzip(environment); configureAuth(configuration.auth, environment, injector); }
@Override public Injector createInjectorAndDoEMFRegistration() { TypeExpressionsStandaloneSetup.doSetup(); Injector injector = createInjector(); register(injector); return injector; }
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; }
private static void initApplicationScoped() { Injector injector = getInjector(); for (Key<?> key : DwrScopes.APPLICATION.getKeysInScope()) { // Eagerly create application-scoped object. injector.getInstance(key); } }
public static Injector getInjector() { if(injector == null) { injector = Guice.createInjector( new ServerModule(), new DataModule() ); } return injector; }
@Override protected Injector getInjector() { Injector injector = Guice.createInjector( Stage.PRODUCTION, new JerseyGuiceModule("__HK2_Generated_0"), new ServletModule(), new AppModule() ); JerseyGuiceUtils.install(injector); return injector; }
@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)); } }
/** * 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?)"); } }
@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()); }); }
protected Injector internalCreateInjector() { return new GExpressionsStandaloneSetup() { @Override public Injector createInjector() { return Guice.createInjector(createRuntimeModule()); } }.createInjectorAndDoEMFRegistration(); }
@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); }
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); } } }
@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()); }
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); }
private void registerWithInjector(Environment environment, Injector injector) throws Exception { registerHealthChecks(environment, injector); registerProviders(environment, injector); registerResources(environment, injector); registerTasks(environment, injector); registerManaged(environment, injector); }
@Nonnull public Injector getInjector() { if (injector == null) { throw new IllegalStateException("Injector has not been initialized yet, ot has been already disposed"); } return injector; }