/** * @see org.junit.rules.MethodRule#apply(org.junit.runners.model.Statement, org.junit.runners.model.FrameworkMethod, java.lang.Object) */ @Override public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { return new Statement() { @Override public void evaluate() throws Throwable { final List<Module> moduleWithTarget = new ArrayList<>(Arrays.asList(modules)); if (target instanceof Module) { moduleWithTarget.add((Module) target); } Guice.createInjector(moduleWithTarget).injectMembers(target); try { base.evaluate(); } finally { new ThreadSafeMockingProgress().reset(); } } }; }
@Override protected Injector doWork() throws Exception { long start = System.currentTimeMillis(); Iterable<URL> localClassPath = privatePluginService.getLocalClassPath(pluginId); final ClassLoader classLoader = privatePluginService.getClassLoader(pluginId); Collection<Parameter> params = extension.getParameters("class"); List<Module> modules = new ArrayList<Module>(); for( Parameter param : params ) { Module module = (Module) privatePluginService.getBean(pluginId, param.valueAsString()); modules.add(module); } modules.add(new ScannerModule(privatePluginService, classLoader, localClassPath, getBeanCheckers())); modules.add(new Jsr250Module()); injector = Guice.createInjector(new ExternalProviders(getDependents(), modules)); long end = System.currentTimeMillis(); LOGGER.info("Guice module for " + pluginId + " took:" + (end - start)); return injector; }
private <T> T withCompute(ComputeTask<T> task) throws HekateException { ContextBuilder builder = ContextBuilder.newBuilder(provider) .credentialsSupplier(credentials::get) .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule())); if (!properties.isEmpty()) { builder.overrides(properties); } if (endpoint != null && !endpoint.trim().isEmpty()) { builder.endpoint(endpoint.trim()); } try (ComputeServiceContext ctx = builder.buildView(ComputeServiceContext.class)) { return task.execute(ctx); } }
@Test public void ifCommmandIsInvalidResponseExceptionIsThrown() throws IOException, URISyntaxException { String command = "invalid"; Map<String, Object> opts = new HashMap<>(); opts.put(BROWSER, CHROME); opts.put(DRIVER, chromedriverFile.getAbsolutePath()); opts.put(APPLICATION, configurationFile.getAbsolutePath()); opts.put(URL, localhostUrl); opts.put(CASE, caseFile.getAbsolutePath()); opts.put(SCREEN, screenString); opts.put(TIMEOUT, timeoutString); opts.put(PRECISION, precisionString); Module module = new DefaultModule(command, opts); Injector injector = Guice.createInjector(module); try { IOProvider<ResponseFilter> instance = injector.getInstance(new Key<IOProvider<ResponseFilter>>() {}); instance.get(); } catch (ProvisionException e) { assertTrue(e.getCause() instanceof NoSuchCommandException); } }
@Test public void ifCommmandIsInvalidExceptionIsThrown() throws IOException, URISyntaxException { String command = "invalid"; Map<String, Object> opts = new HashMap<>(); opts.put(BROWSER, CHROME); opts.put(DRIVER, chromedriverFile.getAbsolutePath()); opts.put(APPLICATION, configurationFile.getAbsolutePath()); opts.put(URL, localhostUrl); opts.put(CASE, caseFile.getAbsolutePath()); opts.put(SCREEN, screenString); opts.put(TIMEOUT, timeoutString); opts.put(PRECISION, precisionString); Module module = new DefaultModule(command, opts); Injector injector = Guice.createInjector(module); try { RequestFilter instance = injector.getInstance( Key.get(new TypeLiteral<IOProvider<RequestFilter>>() {})).get(); } catch (ProvisionException e) { assertTrue(e.getCause() instanceof NoSuchCommandException); } }
@Override public Module createModule(ITestContext context, Class<?> testClass){ Module globalModule = new AbstractModule(){ @Override protected void configure(){ for(Module module : modules){ install(module); } } }; Iterable<? extends Module> overriders = getOverriders(); return Modules.override(globalModule).with(overriders); }
@Override public Application<ServerConfiguration> newApplication() { return new ServerMain("outland.feature.server") { @Override protected List<Module> addModules( ServerConfiguration configuration, Environment environment) { return Lists.newArrayList( new ServerModule(configuration), new HystrixModule(), new RedisModule(configuration.redis), new DynamoDbModule(configuration.aws), new AuthModule(configuration.auth), new TestFeatureServiceModule(), new TestGroupModule() ); } }; }
@Test public void canCreateReplayBrowserProvider() throws IOException, URISyntaxException { String command = REPLAY; Map<String, Object> opts = new HashMap<>(); opts.put(BROWSER, CHROME); opts.put(DRIVER, chromedriverFile.getAbsolutePath()); opts.put(APPLICATION, configurationFile.getAbsolutePath()); opts.put(URL, localhostUrl); opts.put(CASE, caseFile.getAbsolutePath()); opts.put(SCREEN, screenString); opts.put(TIMEOUT, timeoutString); opts.put(PRECISION, precisionString); Module module = new DefaultModule(command, opts); Injector injector = Guice.createInjector(module); IOURIProvider<ReplayBrowser> instance = injector.getInstance(new Key<IOURIProvider<ReplayBrowser>>() {}); ReplayBrowser replayBrowser = instance.get(); replayBrowser.forceCleanUp(); }
@Test public void initializeGuice_ProvideNullListViaExtendingService_NoProblem() throws Exception { // given final AbstractService service = new AbstractService() { @Override public void displayHelp(PrintStream out) { } @Override protected List<Module> getGuiceModules() { return null; } }; // when service.initializeGuice(); // then // no exception should be raised assertThat(service.injector).isNotNull(); }
@Test public void test_interceptor() throws ClassNotFoundException { Injector injector = Guice.createInjector((Module) binder -> binder.bindInterceptor( Matchers.identicalTo(TestedRpcHandler.class), Matchers.any(), new RpcHandlerMethodInterceptor() )); TestedRpcHandler methodHandler = injector.getInstance(TestedRpcHandler.class); methodHandler.handleRequest(RpcEnvelope.Request.newBuilder().build(), new OrangeContext()); SameGuiceModuleAssertionOnInterceptorInvokation sameGuiceModuleAssertionOnInterceptorInvokation = injector.getInstance(SameGuiceModuleAssertionOnInterceptorInvokation.class); sameGuiceModuleAssertionOnInterceptorInvokation.test_that_intercepted_rpc_handler_still_verified(); assertThat(ReflectionUtil.findSubClassParameterType(methodHandler, 0)). isEqualTo(RpcEnvelope.Request.class); assertThat(ReflectionUtil.findSubClassParameterType(methodHandler, 1)). isEqualTo(RpcEnvelope.Response.class); }
@Before public void setUp() throws Exception { final RMContext mockRMContext = TestRMWebApp.mockRMContext(3, numberOfRacks, numberOfNodesPerRack, 8 * TestRMWebApp.GiB); injector = WebAppTests.createMockInjector(RMContext.class, mockRMContext, new Module() { @Override public void configure(Binder binder) { try { binder.bind(ResourceManager.class).toInstance( TestRMWebApp.mockRm(mockRMContext)); } catch (IOException e) { throw new IllegalStateException(e); } } }); }
public Module bindingModule() { return new KeyedManifest.Impl(method) { @Override public void configure() { final Binder binder = binder().withSource(method); if(!hasReturnValue()) { binder.addError("Cannot bind this method as a provider because it does not return a value"); return; } install(InjectableMethod.this); final ScopedBindingBuilder builder = binder.bind(providedKey).toProvider(asProvider()); if(scope != null) builder.in(scope); } }; }
protected Injector createInjector(String language) { try { Module runtimeModule = getRuntimeModule(language); Module sharedStateModule = getSharedStateModule(); Module uiModule = getUiModule(language); Module mergedModule = Modules2.mixin(runtimeModule, sharedStateModule, uiModule); return Guice.createInjector(mergedModule); } catch (Exception e) { logger.error("Failed to create injector for " + language); logger.error(e.getMessage(), e); throw new RuntimeException("Failed to create injector for " + language, e); } }
@Test public void testFairSchedulerWebAppPage() { List<RMAppState> appStates = Arrays.asList(RMAppState.NEW, RMAppState.NEW_SAVING, RMAppState.SUBMITTED); final RMContext rmContext = mockRMContext(appStates); Injector injector = WebAppTests.createMockInjector(RMContext.class, rmContext, new Module() { @Override public void configure(Binder binder) { try { ResourceManager mockRmWithFairScheduler = mockRm(rmContext); binder.bind(ResourceManager.class).toInstance (mockRmWithFairScheduler); binder.bind(ApplicationBaseProtocol.class).toInstance( mockRmWithFairScheduler.getClientRMService()); } catch (IOException e) { throw new IllegalStateException(e); } } }); FairSchedulerPage fsViewInstance = injector.getInstance(FairSchedulerPage .class); fsViewInstance.render(); WebAppTests.flushOutput(injector); }
private Module testThreadingModule( ) { return new AbstractModule( ) { @Override protected void configure( ) { bind( ExecutorService.class ).toInstance( MoreExecutors.sameThreadExecutor( ) ); bind( ScheduledExecutorService.class ).toInstance( newScheduledThreadPool( Runtime.getRuntime( ).availableProcessors( ) ) ); } }; }
/** Creates the injector for the test and injects all fields with the initialized injector. */ private void initInjection(Properties properties) { // STEP 1: set up language N4JS // the following is doing roughly the same as N4JSStandaloneSetup.doSetup(), but is using a custom-built // Guice module for injector creation: TypesPackage.eINSTANCE.getNsURI(); TypeRefsPackage.eINSTANCE.getNsURI(); N4JSPackage.eINSTANCE.getNsURI(); N4mfPackage.eINSTANCE.getNsURI(); XMLTypePackage.eINSTANCE.getNsURI(); // combine all modules for N4JSC final Module combinedModule = Modules.combine(new N4JSRuntimeModule(), new TesterModule(), new N4JSHeadlessGeneratorModule(properties)); // override with customized bindings final Module overridenModule = Modules.override(combinedModule).with(binder -> { binder.bind(TestTreeTransformer.class) .to(CliTestTreeTransformer.class); binder.bind(IHeadlessLogger.class) .toInstance(new ConfigurableHeadlessLogger(verbose, debug)); }); RegularExpressionStandaloneSetup.doSetup(); TypesStandaloneSetup.doSetup(); N4MFStandaloneSetup.doSetup(); TypeExpressionsStandaloneSetup.doSetup(); final Injector injector = Guice.createInjector(overridenModule); new N4JSStandaloneSetup().register(injector); injector.injectMembers(this); }
@Test public void testView() { Injector injector = WebAppTests.createMockInjector(RMContext.class, mockRMContext(15, 1, 2, 8*GiB), new Module() { @Override public void configure(Binder binder) { try { ResourceManager mockRm = mockRm(3, 1, 2, 8*GiB); binder.bind(ResourceManager.class).toInstance(mockRm); binder.bind(ApplicationBaseProtocol.class) .toInstance(mockRm.getClientRMService()); } catch (IOException e) { throw new IllegalStateException(e); } } }); RmView rmViewInstance = injector.getInstance(RmView.class); rmViewInstance.set(YarnWebParams.APP_STATE, YarnApplicationState.RUNNING.toString()); rmViewInstance.render(); WebAppTests.flushOutput(injector); rmViewInstance.set(YarnWebParams.APP_STATE, StringHelper.cjoin( YarnApplicationState.ACCEPTED.toString(), YarnApplicationState.RUNNING.toString())); rmViewInstance.render(); WebAppTests.flushOutput(injector); }
@Override public void install(final Module module) { @Nullable final DuplexBinderImpl activeBinder = ACTIVE_BINDER.get(); ACTIVE_BINDER.set(this); try { this.privateBinder.install(module); } finally { ACTIVE_BINDER.set(activeBinder); } }
@Test public void invalidBrowserThrowsExceptionWhenDriverServiceSupplier() throws IOException, URISyntaxException { String command = RECORD; Map<String, Object> opts = new HashMap<>(); opts.put(BROWSER, "asd"); Module module = new DefaultModule(command, opts); Injector injector = Guice.createInjector(module); try { DriverServiceSupplier instance = injector.getInstance(DriverServiceSupplier.class); } catch (ProvisionException e) { assertTrue(e.getCause() instanceof BrowserTypeNotSupportedException); } }
protected Module getRuntimeModule(String grammar) { if (ORG_ECLIPSE_N4JS_TS_TYPEEXPRESSIONS.equals(grammar)) { return new TypeExpressionsRuntimeModule(); } if (ORG_ECLIPSE_N4JS_TS_TYPES.equals(grammar)) { return new TypesRuntimeModule(); } throw new IllegalArgumentException(grammar); }
public static List<Module> modules( ) { return ImmutableList.<Module>of( new WallApplicationModule( ), new ThreadingModule( ), new ApiModule( ), new ApiRequestModule( ), new BuildDataModule( ), new ConfigurationModule( ), new ConfigurationViewModule( ), new WallViewModule( ) ); }
/** * 添加模块 */ public synchronized void addModule(Module... modules) { if (null == modules || modules.length == 0) { return; } for (Module module : modules) { if (!BeanFactory.modules.contains(module)) { BeanFactory.modules.add(module); } } }
@Test public void testNodesPage() { // 10 nodes. Two of each type. final RMContext rmContext = mockRMContext(3, 2, 12, 8*GiB); Injector injector = WebAppTests.createMockInjector(RMContext.class, rmContext, new Module() { @Override public void configure(Binder binder) { try { binder.bind(ResourceManager.class).toInstance(mockRm(rmContext)); } catch (IOException e) { throw new IllegalStateException(e); } } }); // All nodes NodesPage instance = injector.getInstance(NodesPage.class); instance.render(); WebAppTests.flushOutput(injector); // Unhealthy nodes instance.moreParams().put(YarnWebParams.NODE_STATE, NodeState.UNHEALTHY.toString()); instance.render(); WebAppTests.flushOutput(injector); // Lost nodes instance.moreParams().put(YarnWebParams.NODE_STATE, NodeState.LOST.toString()); instance.render(); WebAppTests.flushOutput(injector); }
@Override public Module createModule() { return new AbstractModule() { @Override protected void configure() { // singleton scope if (idSequencerFactory != null) { bind(IdSequencer.class).toProvider(idSequencerFactory).in(Singleton.class); } bind(UUID.class).annotatedWith(Names.named(CLUSTER_ID)).toProvider(new ClusterIdProvider()); bind(String.class).annotatedWith(Names.named(RPC_ADDRESS)).toInstance(address); bind(String.class).annotatedWith(Names.named(SUPER_CLUSTER_ADDRESS)) .toInstance(superClusterAddress); bind(DataRecoveryConfig.class).toInstance(dataRecoveryConfig); bind(Serializer.class).to(JavaSerializer.class).in(Singleton.class); bind(ReplicaProducersManager.class).to(ReplicaProducersManagerImpl.class); bind(ReplicaProducersUpdater.class).to(ReplicaProducersManagerImpl.class); bind(RPCManager.class).to(RPCManagerImpl.class); bind(RPCUpdater.class).to(RPCManagerImpl.class); bind(Committer.class).to(ParallelIgniteCommitter.class).in(Singleton.class); bind(KafkaFactory.class).to(KafkaFactoryImpl.class).in(Singleton.class); bind(LeadService.class).to(LeadServiceProxyRetry.class).in(Singleton.class); bind(ConsumerPingCheckStrategy.class).to(DefaultConsumerPingCheckStrategy.class).in(Singleton.class); bind(ActiveCacheStoreService.class).to(ActiveCacheStoreServiceImpl.class).in(Singleton.class); bind(BufferOverflowCondition.class).toInstance(new SimpleBufferOverflowCondition(consumerBufferLimit)); bind(ReconciliationState.class).to(ReconciliationStateImpl.class); bind(Long.class).annotatedWith(Names.named(Lead.MAIN_PING_CHECK_KEY)).toInstance(MAIN_PING_CHECK_TIME); bind(Long.class).annotatedWith(Names.named(Lead.CONSUMER_PING_CHECK_KEY)) .toInstance(CONSUMER_PING_CHECK_TIME); listeners.add(LocalKafkaKVListener.class); bind(new TypeLiteral<List<KeyValueListener>>() {}).toProvider(new ListOf<>(listeners)).in(Singleton.class); bind(UUID.class).annotatedWith(Names.named(NODE_ID)).toProvider(new NodeIdFactory()).in(Singleton.class); // request scope bind(GapDetectionStrategy.class).to(DefaultGapDetectionStrategy.class); } }; }
@Override public LifecycleInjector createInjector() { List<Module> allModules = new ArrayList<Module>(); allModules.addAll(modules); allModules.add(new ShutdownHookModule()); allModules.add(new LifecycleModule()); return GovernatorLifecycleInjector.create( InjectorBuilder.fromModules(allModules).createInjector()); }
@Test public void canCreateStepsDumper() throws IOException { Map<String, Object> opts = new HashMap<>(); opts.put(APPLICATION, configurationFile.getAbsolutePath()); Module module = new DefaultModule(RECORD, opts); Injector injector = Guice.createInjector(module); IOProvider<StepsDumper> ioProvider = injector.getInstance(Key.get(new TypeLiteral<IOProvider<StepsDumper>>() { })); ioProvider.get(); }
protected Module getRuntimeModule(String grammar) { if ("org.ioicompanies.lang.IOI".equals(grammar)) { return new org.ioicompanies.lang.IOIRuntimeModule(); } throw new IllegalArgumentException(grammar); }
protected Module getUiModule(String grammar) { if ("org.ioicompanies.lang.IOI".equals(grammar)) { return new org.ioicompanies.lang.ui.IOIUiModule(this); } throw new IllegalArgumentException(grammar); }
protected Module getRuntimeModule(String grammar) { if (ORG_ECLIPSE_GEMOC_GEXPRESSIONS_XTEXT_GEXPRESSIONS.equals(grammar)) { return new org.eclipse.gemoc.gexpressions.xtext.GExpressionsRuntimeModule(); } throw new IllegalArgumentException(grammar); }
public static void startup(Class<? extends AbstractTopologyRunner> klass, Module module) { String overridesFile = null; if (System.getProperty("storm.topology.config.overrides.file") != null) { overridesFile = System.getProperty("storm.topology.config.overrides.file"); } else { overridesFile = klass.getResource("kilda-overrides.yml").getPath(); } Injector injector = Guice .createInjector(new YamlConfigModule(overridesFile), module); AbstractTopologyRunner runner = injector.getInstance(klass); runner.run(); }
protected Module bindInfinispan(Provider<InfinispanCacheManager> cacheManagerProvider) { return new AbstractModule() { @Override protected void configure() { bind(InfinispanCacheManager.class).toProvider(cacheManagerProvider); } }; }
@Override protected Module bindInfinispan(Provider<InfinispanCacheManager> cacheManagerProvider) { return new AbstractModule() { @Override protected void configure() { bind(InfinispanCacheManager.class).toInstance(infinispanCacheManager); } }; }
protected Module bindInfinispan(Provider<InfinispanCacheManager> infinispanCacheManagerProvider) { return new AbstractModule() { @Override protected void configure() { bind(InfinispanCacheManager.class).toProvider(infinispanCacheManagerProvider); } }; }
@Override protected Module bindInfinispan(Provider<InfinispanCacheManager> ignored) { return new AbstractModule() { @Override protected void configure() { bind(InfinispanCacheManager.class).toProvider((javax.inject.Provider<InfinispanCacheManager>) () -> new InfinispanCacheManager(mock(MetricRegistry.class, RETURNS_MOCKS), TestCacheManagerFactory.createCacheManager())); } }; }
private static DependencyContainer create(final Ignite ignite, Module configuration) { final LifecycleQueue lifecycleBeans = new LifecycleQueue(); Module module = Modules.override(configuration).with(new AbstractModule() { @Override protected void configure() { bind(Ignite.class).toInstance(ignite); bindListener(Matchers.any(), new PostCreationListener(lifecycleBeans, ignite)); } }); return new DependencyContainer(module, lifecycleBeans); }
public DBConfig() { try { Thread.sleep(20000); } catch(Exception e) { } Module module = new DatabaseModule(); Guice.createInjector(module).injectMembers(this); }