类com.google.inject.Module源码实例Demo

下面列出了怎么用com.google.inject.Module的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void initializeGuice_ProvideImmutableListViaExtendingService_NoProblem() throws Exception {
    // given
    final AbstractService service = new AbstractService() {
        @Override
        public void displayHelp(PrintStream out) {

        }

        @Override
        protected List<Module> getGuiceModules() {
            return Collections.emptyList();
        }
    };

    // when
    service.initializeGuice();

    // then
    // no exception should be raised
    assertThat(service.injector).isNotNull();
}
 
源代码2 项目: arcusplatform   文件: AbstractSystemTestCase.java
public static void startIrisSystem(Collection<? extends Class<? extends Module>> extra) throws Exception {
   File basePath = BASE_PATH.get();
   if (basePath != null) {
      throw new IllegalStateException("iris test harness already started: " + basePath);
   }

   basePath = Files.createTempDir();
   if (!BASE_PATH.compareAndSet(null, basePath)) {
      FileUtils.deleteDirectory(basePath);
      throw new IllegalStateException("iris test harness startup race condition");
   }

   System.out.println("Starting up simulated iris hal: " + basePath + "...");
   FileUtils.deleteDirectory(basePath);

   BootUtils.addExtraModules(extra);
   BootUtils.initialize(new IrisHalTest(), basePath, Collections.<String>emptyList());
}
 
@Test
public void testModulesRegisteredThroughInjectionWithAnnotation() throws Exception
{
    final Injector injector = Guice.createInjector(
            new ObjectMapperModule().registerModule(IntegerAsBase16Module.class, Ann.class),
            new Module()
            {
                @Override
                public void configure(Binder binder)
                {
                    binder.bind(IntegerAsBase16Module.class).annotatedWith(Ann.class).to(IntegerAsBase16Module.class);
                }
            }
    );

    final ObjectMapper mapper = injector.getInstance(ObjectMapper.class);

    Assert.assertEquals(mapper.writeValueAsString(Integer.valueOf(10)), "\"A\"");
}
 
源代码4 项目: saga-lib   文件: SagaModuleBuilderTest.java
/**
 * <pre>
 * Given => Custom interceptor is configured
 * When  => String message is handled
 * Then  => Interceptor has been called
 * </pre>
 */
@Test
public void handleString_interceptorConfigured_interceptorIsCalled() throws InvocationTargetException, IllegalAccessException {
    // given
    Module sagaModule = SagaModuleBuilder.configure().callInterceptor(CustomInterceptor.class).build();
    Injector injector = Guice.createInjector(sagaModule, new CustomModule());
    MessageStream msgStream = injector.getInstance(MessageStream.class);
    Set<SagaLifetimeInterceptor> interceptors = injector.getInstance(Key.get(new TypeLiteral<Set<SagaLifetimeInterceptor>>() {}));

    // when
    msgStream.handle("anyString");

    // then
    CustomInterceptor interceptor = (CustomInterceptor) interceptors.iterator().next();
    assertThat("Expected interceptor to be called.", interceptor.hasStartingBeenCalled(), equalTo(true));
}
 
源代码5 项目: suro   文件: SuroServer.java
public static void create(AtomicReference<Injector> injector, final Properties properties, Module... modules) throws Exception {
    // Create the injector
    injector.set(LifecycleInjector.builder()
            .withBootstrapModule(
                    new BootstrapModule() {
                        @Override
                        public void configure(BootstrapBinder binder) {
                            binder.bindConfigurationProvider().toInstance(
                                    new PropertiesConfigurationProvider(properties));
                        }
                    }
            )
            .withModules(
                    new RoutingPlugin(),
                    new ServerSinkPlugin(),
                    new SuroInputPlugin(),
                    new SuroDynamicPropertyModule(),
                    new SuroModule(),
                    StatusServer.createJerseyServletModule()
            )
            .withAdditionalModules(modules)
            .build().createInjector());
}
 
源代码6 项目: ffwd   文件: RiemannInputPlugin.java
@Override
public Module module(final Key<PluginSource> key, final String id) {
    return new PrivateModule() {
        @Override
        protected void configure() {
            bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON);
            bind(Protocol.class).toInstance(protocol);

            bind(RiemannFrameDecoder.class);
            bind(RiemannResponder.class).in(Scopes.SINGLETON);
            bind(RiemannDatagramDecoder.class).in(Scopes.SINGLETON);
            bind(RiemannMessageDecoder.class).in(Scopes.SINGLETON);
            bind(Logger.class).toInstance(log);

            bind(RetryPolicy.class).toInstance(retry);

            bind(key).to(ProtocolPluginSource.class).in(Scopes.SINGLETON);
            expose(key);
        }
    };
}
 
源代码7 项目: attic-stratos   文件: ComputeServiceBuilderUtil.java
public static ComputeService buildDefaultComputeService(IaasProvider iaasProvider) {

        Properties properties = new Properties();

        // load properties
        for (Map.Entry<String, String> entry : iaasProvider.getProperties().entrySet()) {
            properties.put(entry.getKey(), entry.getValue());
        }

        // set modules
        Iterable<Module> modules =
                ImmutableSet.<Module>of(new SshjSshClientModule(), new SLF4JLoggingModule(),
                        new EnterpriseConfigurationModule());

        // build context
        ContextBuilder builder =
                ContextBuilder.newBuilder(iaasProvider.getProvider())
                        .credentials(iaasProvider.getIdentity(), iaasProvider.getCredential()).modules(modules)
                        .overrides(properties);

        return builder.buildView(ComputeServiceContext.class).getComputeService();
    }
 
源代码8 项目: presto   文件: AuthenticationModules.java
public static Module kerberosHdfsAuthenticationModule()
{
    return new Module()
    {
        @Override
        public void configure(Binder binder)
        {
            binder.bind(HdfsAuthentication.class)
                    .to(DirectHdfsAuthentication.class)
                    .in(SINGLETON);
            configBinder(binder).bindConfig(HdfsKerberosConfig.class);
        }

        @Inject
        @Provides
        @Singleton
        @ForHdfs
        HadoopAuthentication createHadoopAuthentication(HdfsKerberosConfig config, HdfsConfigurationInitializer updater)
        {
            String principal = config.getHdfsPrestoPrincipal();
            String keytabLocation = config.getHdfsPrestoKeytab();
            return createCachingKerberosHadoopAuthentication(principal, keytabLocation, updater);
        }
    };
}
 
源代码9 项目: usergrid   文件: WarehouseExport.java
private void copyToS3( String fileName ) {

        String bucketName = ( String ) properties.get( BUCKET_PROPNAME );
        String accessId = ( String ) properties.get( ACCESS_ID_PROPNAME );
        String secretKey = ( String ) properties.get( SECRET_KEY_PROPNAME );

        Properties overrides = new Properties();
        overrides.setProperty( "s3" + ".identity", accessId );
        overrides.setProperty( "s3" + ".credential", secretKey );

        final Iterable<? extends Module> MODULES = ImmutableSet
                .of( new JavaUrlHttpCommandExecutorServiceModule(), new Log4JLoggingModule(),
                        new NettyPayloadModule() );

        AWSCredentials credentials = new BasicAWSCredentials(accessId, secretKey);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol( Protocol.HTTP);

        AmazonS3Client s3Client = new AmazonS3Client(credentials, clientConfig);

        s3Client.createBucket( bucketName );
        File uploadFile = new File( fileName );
        PutObjectResult putObjectResult = s3Client.putObject( bucketName, uploadFile.getName(), uploadFile );
        logger.info("Uploaded file etag={}", putObjectResult.getETag());
    }
 
源代码10 项目: karyon   文件: AdminResourcesContainer.java
private List<Module> buildAdminPluginsGuiceModules() {
    List<Module> guiceModules = new ArrayList<>();
    if (adminPageRegistry != null) {
        final Collection<AdminPageInfo> allPages = adminPageRegistry.getAllPages();
        for (AdminPageInfo adminPlugin : allPages) {
            logger.info("Adding admin page {}: jersey={} modules{}", 
                    adminPlugin.getName(),
                    adminPlugin.getJerseyResourcePackageList(),
                    adminPlugin.getGuiceModules());
            final List<Module> guiceModuleList = adminPlugin.getGuiceModules();
            if (guiceModuleList != null && !guiceModuleList.isEmpty()) {
                guiceModules.addAll(adminPlugin.getGuiceModules());
            }
        }
    }
    guiceModules.add(getAdditionalBindings());
    return guiceModules;
}
 
源代码11 项目: smartapp-sdk-java   文件: DefaultBindingsSpec.java
private <T extends Module> T createModule(Class<T> clazz) {
    try {
        return clazz.newInstance();
    } catch (ReflectiveOperationException e) {
        throw new IllegalStateException("Module " + clazz.getName() + " is not reflectively instantiable", e);
    }
}
 
源代码12 项目: soabase   文件: TestGuiceBundle.java
@Test
public void testIt() throws Exception
{
    Module module = new AbstractModule()
    {
        @Override
        protected void configure()
        {
            bind(MockGuiceInjected.class).asEagerSingleton();
        }
    };
    final MockApplication mockApplication = new MockApplication(module);

    Callable callable = new Callable()
    {
        @Override
        public Object call() throws Exception
        {
            String[] args = {"server"};
            mockApplication.run(args);
            return null;
        }
    };
    Future future = Executors.newSingleThreadExecutor().submit(callable);
    try
    {
        Assert.assertTrue(mockApplication.getStartedLatch().await(5, TimeUnit.SECONDS));
        URI uri = new URI("http://localhost:8080/test");
        String str = CharStreams.toString(new InputStreamReader(uri.toURL().openStream()));
        Assert.assertEquals("guice - hk2", str);
    }
    finally
    {
        future.cancel(true);
        ShutdownThread.getInstance().run();
    }
}
 
源代码13 项目: spoofax   文件: MetaBorgGeneric.java
/**
 * Instantiate the generic MetaBorg API.
 * 
 * @param loader
 *            Module plugin loader to use.
 * @param module
 *            MetaBorg module to use, which should implement all services in this facade. Do not use
 *            {@link MetaborgModule}.
 * @param additionalModules
 *            Additional modules to use.
 * 
 * @throws MetaborgException
 *             When loading plugins or dependency injection fails.
 */
public MetaBorgGeneric(Class<I> iClass, Class<P> pClass, Class<A> aClass, Class<AU> auClass, Type tClass,
    Type tpClass, Type taClass, Class<F> fClass, IModulePluginLoader loader, MetaborgModule module,
    Module... additionalModules) throws MetaborgException {
    super(loader, module, additionalModules);

    this.dialectService = injector.getInstance(IDialectService.class);
    this.dialectIdentifier = injector.getInstance(IDialectIdentifier.class);

    this.unitService = instance(new TypeLiteral<IUnitService<I, P, A, AU, TP, TA>>() {}, iClass, pClass, aClass,
        auClass, tpClass, taClass);

    this.syntaxService = instance(new TypeLiteral<ISyntaxService<I, P>>() {}, iClass, pClass);
    this.analysisService = instance(new TypeLiteral<IAnalysisService<P, A, AU>>() {}, pClass, aClass, auClass);
    this.transformService =
        instance(new TypeLiteral<ITransformService<P, A, TP, TA>>() {}, pClass, aClass, tpClass, taClass);

    this.builder = instance(new TypeLiteral<IBuilder<P, A, AU, T>>() {}, pClass, aClass, auClass, tClass);
    this.processorRunner =
        instance(new TypeLiteral<IProcessorRunner<P, A, AU, T>>() {}, pClass, aClass, auClass, tClass);

    this.parseResultProcessor = instance(new TypeLiteral<IParseResultProcessor<I, P>>() {}, iClass, pClass);
    this.analysisResultProcessor =
        instance(new TypeLiteral<IAnalysisResultProcessor<I, P, A>>() {}, iClass, pClass, aClass);
    this.analysisResultRequester =
        instance(new TypeLiteral<IAnalysisResultRequester<I, A>>() {}, iClass, aClass);

    this.actionService = injector.getInstance(IActionService.class);
    this.menuService = injector.getInstance(IMenuService.class);

    this.tracingService =
        instance(new TypeLiteral<ITracingService<P, A, T, F>>() {}, pClass, aClass, tClass, fClass);

    this.categorizerService = instance(new TypeLiteral<ICategorizerService<P, A, F>>() {}, pClass, aClass, fClass);
    this.stylerService = instance(new TypeLiteral<IStylerService<F>>() {}, fClass);
    this.hoverService = instance(new TypeLiteral<IHoverService<P, A>>() {}, pClass, aClass);
    this.resolverService = instance(new TypeLiteral<IResolverService<P, A>>() {}, pClass, aClass);
    this.outlineService = instance(new TypeLiteral<IOutlineService<P, A>>() {}, pClass, aClass);
    this.completionService = instance(new TypeLiteral<ICompletionService<P>>() {}, pClass);
}
 
源代码14 项目: nexus-public   文件: NexusContextListener.java
/**
 * Registers our locator service with Pax-Exam to handle injection of test classes.
 */
private void registerLocatorWithPaxExam(final Provider<BeanLocator> locatorProvider) {
  // ensure this service is ranked higher than the Pax-Exam one
  final Dictionary<String, Object> examProperties = new Hashtable<>();
  examProperties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE);
  examProperties.put("name", "nexus");

  bundleContext.registerService(org.ops4j.pax.exam.util.Injector.class, new org.ops4j.pax.exam.util.Injector()
  {
    @Override
    public void injectFields(final Object target) {
      Module testModule = new WireModule(new AbstractModule()
      {
        @Override
        protected void configure() {
          // support injection of application components by wiring via shared locator
          // (use provider to avoid auto-publishing test-instance to the application)
          bind(BeanLocator.class).toProvider(locatorProvider);

          // support injection of application properties
          bind(ParameterKeys.PROPERTIES).toInstance(
              locatorProvider.get().locate(ParameterKeys.PROPERTIES).iterator().next().getValue());

          // inject the test-instance
          requestInjection(target);
        }
      });

      // lock locator to avoid a potential concurrency issue while injecting the target
      // (just in case there was a startup problem that left things in an odd state and
      // a Jetty thread is now trying to initialize the same singletons via the filter)
      // - locking the locator holds back dynamic injection while we populate the test
      synchronized (locatorProvider.get()) {
        Guice.createInjector(testModule);
      }
    }
  }, examProperties);
}
 
源代码15 项目: attic-stratos   文件: AWSEC2ApiMetadata.java
public Builder() {
   id("aws-ec2")
   .version("2014-02-01")
   .name("Amazon-specific EC2 API")
   .identityName("Access Key ID")
   .credentialName("Secret Access Key")
   .defaultEndpoint("https://ec2.us-east-1.amazonaws.com")
   .documentation(URI.create("http://docs.amazonwebservices.com/AWSEC2/latest/APIReference"))
   .defaultProperties(AWSEC2ApiMetadata.defaultProperties())
   .view(AWSEC2ComputeServiceContext.class)
   .defaultModules(ImmutableSet.<Class<? extends Module>>of(AWSEC2HttpApiModule.class, EC2ResolveImagesModule.class, AWSEC2ComputeServiceContextModule.class));
}
 
源代码16 项目: dsl-devkit   文件: ScopeActivator.java
protected Module getUiModule(String grammar) {
	if (COM_AVALOQ_TOOLS_DDK_XTEXT_SCOPE_SCOPE.equals(grammar)) {
		return new com.avaloq.tools.ddk.xtext.scope.ui.ScopeUiModule(this);
	}
	
	throw new IllegalArgumentException(grammar);
}
 
private List<Module> convertModuleNamesToModules() throws InstantiationException, IllegalAccessException {
    List<Module> modules = new ArrayList<Module>(moduleNames.size());
    for (String moduleName : moduleNames) {
        Class< ? > klass = loadType(moduleName).getUnderlyingClass();
        modules.add(( Module ) klass.newInstance());
    }
    return modules;
}
 
源代码18 项目: jenkins-rest   文件: JenkinsClient.java
private JenkinsApi createApi(final String endPoint, final JenkinsAuthentication authentication, final Properties overrides, final List<Module> modules) {
    final List<Module> allModules = Lists.newArrayList(new JenkinsAuthenticationModule(authentication));
    if (modules != null) {
        allModules.addAll(modules);
    }
    return ContextBuilder
            .newBuilder(new JenkinsApiMetadata.Builder().build())
            .endpoint(endPoint)
            .modules(allModules)
            .overrides(overrides)
            .buildApi(JenkinsApi.class);
}
 
@Override
public Module getModule() {
    List<Module> modules = subrule
                .stream()
                .map(GuiceModuleTestRule::getModule)
                .collect(Guavate.toImmutableList());

    return Modules.combine(modules);
}
 
源代码20 项目: attic-stratos   文件: NeutronNetworkingApi.java
private void buildNeutronApi() {

        String iaasProviderNullMsg = "IaasProvider is null. Unable to build neutron API";
        assertNotNull(iaasProvider, iaasProviderNullMsg);

        String region = ComputeServiceBuilderUtil.extractRegion(iaasProvider);
        String regionNullOrEmptyErrorMsg = String.format("Region is not set. Unable to build neutron API for the iaas provider %s",
                iaasProvider.getProvider());
        assertNotNullAndNotEmpty(region, regionNullOrEmptyErrorMsg);

        String endpoint = iaasProvider.getProperty(CloudControllerConstants.JCLOUDS_ENDPOINT);
        String endpointNullOrEmptyErrorMsg = String.format("Endpoint is not set. Unable to build neutorn API for the iaas provider %s",
                iaasProvider.getProvider());
        assertNotNullAndNotEmpty(endpoint, endpointNullOrEmptyErrorMsg);

        Iterable<Module> modules = ImmutableSet.<Module>of(new SLF4JLoggingModule());

        try {
            this.neutronApi = ContextBuilder.newBuilder(provider).credentials(iaasProvider.getIdentity(),
                    iaasProvider.getCredential()).endpoint(endpoint).modules(modules).buildApi(NeutronApi.class);
        } catch (Exception e) {
            String msg = String.format("Unable to build neutron API for [provider=%s, identity=%s, credential=%s, endpoint=%s]",
                    provider, iaasProvider.getIdentity(), iaasProvider.getCredential(), endpoint);
            log.error(msg, e);
            throw new CloudControllerException(msg, e);
        }

        this.portApi = neutronApi.getPortApi(region);
        String portApiNullOrEmptyErrorMessage = String.format("Unable to get port Api from neutron Api for region ", region);
        assertNotNull(portApi, portApiNullOrEmptyErrorMessage);

        this.floatingIPApi = neutronApi.getFloatingIPApi(region).get();
        String floatingIPApiNullOrEmptyErrorMessage = String.format("Unable to get floatingIP Api from neutron Api for region ", region);
        assertNotNull(floatingIPApi, floatingIPApiNullOrEmptyErrorMessage);
    }
 
源代码21 项目: dropwizard-guicey   文件: ConfigurationContext.java
/**
 * @param modules overriding guice modules to register
 */
public void registerModulesOverride(final Module... modules) {
    ModuleItemInfoImpl.overrideScope(() -> {
        for (Module module : modules) {
            register(ConfigItem.Module, module);
        }
    });
}
 
源代码22 项目: big-c   文件: TestRMWebAppFairScheduler.java
@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);
}
 
源代码23 项目: dropwizard-guicey   文件: ConfigurationContext.java
/**
 * Guice module manual disable registration from
 * {@link ru.vyarus.dropwizard.guice.GuiceBundle.Builder#disableModules(Class[])}.
 *
 * @param modules modules to disable
 */
@SuppressWarnings("PMD.UseVarargs")
public void disableModules(final Class<? extends Module>[] modules) {
    for (Class<? extends Module> module : modules) {
        registerDisable(ConfigItem.Module, ItemId.from(module));
    }
}
 
源代码24 项目: presto   文件: BackupModule.java
public BackupModule(Map<String, Module> providers)
{
    this.providers = ImmutableMap.<String, Module>builder()
            .put("file", new FileBackupModule())
            .put("http", new HttpBackupModule())
            .putAll(providers)
            .build();
}
 
源代码25 项目: arcusplatform   文件: Bootstrap.java
public Builder withModuleClassnames(Collection<String> classes) throws ClassNotFoundException {
   if(classes != null) {
      Set<Class<? extends Module>> moduleClasses = classnamesToClasses(classes);
      this.moduleClasses.addAll(moduleClasses);
   }

   return this;
}
 
/**
 * Here we override the childModule if it is a {@link DefaultSharedContribution}. In that case, we enhance it with
 * the {@link ProjectStateChangeListenerModule}.
 *
 * @param childModule
 *            the module that shall be used to configure the contribution.
 */
@Override
public SharedStateContribution createContribution(Module childModule) {
	if (childModule.getClass().equals(DefaultSharedContribution.class)) {
		childModule = Modules.override(childModule).with(new ProjectStateChangeListenerModule());
	}
	return super.createContribution(childModule);
}
 
源代码27 项目: xtext-eclipse   文件: LabelProviderInjectionTest.java
@org.junit.Test public void testLabelProviderInjection() throws Exception {
	Module module = new Module() {
		@Override
		public void configure(Binder binder) {
			binder.bind(ILabelProvider.class).annotatedWith(ResourceServiceDescriptionLabelProvider.class).to(LabelProvider.class);
		}
	};
	Injector injector = Guice.createInjector(module);
	Test instance = injector.getInstance(Test.class);
	assertTrue(instance.labelProvider instanceof LabelProvider);
}
 
源代码28 项目: vespa   文件: ServerProviderConformanceTest.java
private static Module newServerBinding(final String serverBinding) {
    return new AbstractModule() {

        @Override
        protected void configure() {
            bind(String.class).annotatedWith(Names.named("serverBinding")).toInstance(serverBinding);
        }
    };
}
 
源代码29 项目: pinpoint   文件: MockTraceContextFactory.java
public static DefaultApplicationContext newMockApplicationContext(ProfilerConfig profilerConfig) {

        Module loggingModule = new LoggingModule();

        InterceptorRegistryBinder interceptorRegistryBinder = new EmptyInterceptorRegistryBinder();
        Module interceptorRegistryModule = InterceptorRegistryModule.wrap(interceptorRegistryBinder);
        ModuleFactory moduleFactory = new OverrideModuleFactory(loggingModule, interceptorRegistryModule);

        MockApplicationContextFactory factory = new MockApplicationContextFactory();
        return factory.build(profilerConfig, moduleFactory);
    }
 
源代码30 项目: xtext-core   文件: Modules2.java
public static Module mixin(Module...m) {
	if (m.length==0)
		return null;
	Module current = m[0];
	for (int i=1;i<m.length;i++) {
		current = Modules.override(current).with(m[i]);
	}
	return current;
}
 
 类所在包
 类方法
 同包方法