com.google.inject.Module Java Examples

The following examples show how to use com.google.inject.Module. 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 File: AbstractServiceTest_initializeGuice.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: AbstractSystemTestCase.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #3
Source File: ObjectMapperModuleTest.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@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\"");
}
 
Example #4
Source File: SagaModuleBuilderTest.java    From saga-lib with Apache License 2.0 6 votes vote down vote up
/**
 * <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));
}
 
Example #5
Source File: SuroServer.java    From suro with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #6
Source File: RiemannInputPlugin.java    From ffwd with Apache License 2.0 6 votes vote down vote up
@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);
        }
    };
}
 
Example #7
Source File: ComputeServiceBuilderUtil.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
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();
    }
 
Example #8
Source File: AuthenticationModules.java    From presto with Apache License 2.0 6 votes vote down vote up
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);
        }
    };
}
 
Example #9
Source File: WarehouseExport.java    From usergrid with Apache License 2.0 6 votes vote down vote up
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());
    }
 
Example #10
Source File: AdminResourcesContainer.java    From karyon with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: MbusServerConformanceTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public Module newConfigModule() {
    return new AbstractModule() {

        @Override
        protected void configure() {
            bind(ServerSession.class).toInstance(session);
        }
    };
}
 
Example #12
Source File: JenkinsClient.java    From jenkins-rest with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: AWSEC2ApiMetadata.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #14
Source File: AggregateGuiceModuleTestRule.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Module getModule() {
    List<Module> modules = subrule
                .stream()
                .map(GuiceModuleTestRule::getModule)
                .collect(Guavate.toImmutableList());

    return Modules.combine(modules);
}
 
Example #15
Source File: NeutronNetworkingApi.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
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);
    }
 
Example #16
Source File: ConfigurationContext.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * @param modules overriding guice modules to register
 */
public void registerModulesOverride(final Module... modules) {
    ModuleItemInfoImpl.overrideScope(() -> {
        for (Module module : modules) {
            register(ConfigItem.Module, module);
        }
    });
}
 
Example #17
Source File: TestRMWebAppFairScheduler.java    From big-c with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: ConfigurationContext.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * 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));
    }
}
 
Example #19
Source File: StandardInjectorProvider.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
public final Injector get(T configuration, Environment environment, Module additionalModule)
{
    List<Module> localModules = Lists.newArrayList();
    Collections.addAll(localModules, modules);
    if ( additionalModule != null )
    {
        localModules.add(additionalModule);
    }
    internalAddModules(localModules, configuration, environment);
    return Guice.createInjector(localModules);
}
 
Example #20
Source File: TckListener.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Module createModule(ITestContext testContext, String name) {
  final Iterator<TckModule> moduleIterator = ServiceLoader.load(TckModule.class).iterator();
  if (!moduleIterator.hasNext()) {
    throw new IllegalStateException(
        format(
            "Couldn't find a TckModule configuration. "
                + "You probably forgot to configure resources/META-INF/services/%s, or even "
                + "provide an implementation of the TckModule which is required by the jpa test class %s",
            TckModule.class.getName(), name));
  }
  return new CompoundModule(testContext, moduleIterator);
}
 
Example #21
Source File: DefaultApplicationContextTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private DefaultApplicationContext newApplicationContext() {
        ProfilerConfig profilerConfig = spy(new DefaultProfilerConfig());
        when(profilerConfig.getStaticResourceCleanup()).thenReturn(true);
//        when(profilerConfig.getTransportModule()).thenReturn("GRPC");

        Instrumentation instrumentation = mock(Instrumentation.class);
        AgentOption agentOption = new DefaultAgentOption(instrumentation, "mockAgent", "mockApplicationName", false,
                profilerConfig, Collections.<String>emptyList(), null);

        InterceptorRegistryBinder interceptorRegistryBinder = new TestInterceptorRegistryBinder();
        Module interceptorRegistryModule = InterceptorRegistryModule.wrap(interceptorRegistryBinder);
        ModuleFactory moduleFactory = new OverrideModuleFactory(interceptorRegistryModule);

        return new DefaultApplicationContext(agentOption, moduleFactory);
    }
 
Example #22
Source File: BackupModule.java    From presto with Apache License 2.0 5 votes vote down vote up
public BackupModule(Map<String, Module> providers)
{
    this.providers = ImmutableMap.<String, Module>builder()
            .put("file", new FileBackupModule())
            .put("http", new HttpBackupModule())
            .putAll(providers)
            .build();
}
 
Example #23
Source File: Bootstrap.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public Builder withModuleClassnames(Collection<String> classes) throws ClassNotFoundException {
   if(classes != null) {
      Set<Class<? extends Module>> moduleClasses = classnamesToClasses(classes);
      this.moduleClasses.addAll(moduleClasses);
   }

   return this;
}
 
Example #24
Source File: BookServiceBootstrap.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected List<Module> getModules() {
    List<Module> modules = new ArrayList<Module>();
    modules.add(new Module() {
        @Override
        public void configure(Binder binder) {
            binder.bind(BookService.class);
            binder.bind(BookStorage.class);
            binder.bind(BookNotFoundExceptionMapper.class);
        }
    });
    return modules;
}
 
Example #25
Source File: DefaultSharedContributionOverridingRegistry.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #26
Source File: TestTSOClientRequestAndResponseBehaviours.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void beforeMethod() throws Exception {

    TSOServerConfig tsoConfig = new TSOServerConfig();
    tsoConfig.setConflictMapSize(1000);
    tsoConfig.setPort(TSO_SERVER_PORT);
    tsoConfig.setNumConcurrentCTWriters(2);
    Module tsoServerMockModule = new TSOMockModule(tsoConfig);
    Injector injector = Guice.createInjector(tsoServerMockModule);

    LOG.info("==================================================================================================");
    LOG.info("======================================= Init TSO Server ==========================================");
    LOG.info("==================================================================================================");

    tsoServer = injector.getInstance(TSOServer.class);
    tsoServer.startAndWait();
    TestUtils.waitForSocketListening(TSO_SERVER_HOST, TSO_SERVER_PORT, 100);

    LOG.info("==================================================================================================");
    LOG.info("===================================== TSO Server Initialized =====================================");
    LOG.info("==================================================================================================");

    pausableTSOracle = (PausableTimestampOracle) injector.getInstance(TimestampOracle.class);
    commitTable = injector.getInstance(CommitTable.class);

    OmidClientConfiguration tsoClientConf = new OmidClientConfiguration();
    tsoClientConf.setConnectionString(TSO_SERVER_HOST + ":" + TSO_SERVER_PORT);

    this.tsoClientConf = tsoClientConf;

}
 
Example #27
Source File: LabelProviderInjectionTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: ServerProviderConformanceTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static Module newServerBinding(final String serverBinding) {
    return new AbstractModule() {

        @Override
        protected void configure() {
            bind(String.class).annotatedWith(Names.named("serverBinding")).toInstance(serverBinding);
        }
    };
}
 
Example #29
Source File: MockTraceContextFactory.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
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);
    }
 
Example #30
Source File: Modules2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
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;
}