Java Code Examples for com.google.inject.util.Modules#combine()

The following examples show how to use com.google.inject.util.Modules#combine() . 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: OrienteerInitModule.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 *  Load modules from classpath.
 * </p>
 * <p>
 *  For load modules {@link Module} from classpath uses {@link ServiceLoader}
 *  If present module with annotation {@link OverrideModule}, so will be used {@link Modules#override(Module...)}
 *  for override runtime bindings (bindings created in modules without annotation {@link OverrideModule})
 * </p>
 * @param initModules default modules for init
 * @return {@link Module} created by {@link Modules#combine(Module...)} or {@link Modules#override(Module...)} if need override module
 */
public Module loadFromClasspath(Module... initModules) {
	List<Module> allModules = new LinkedList<Module>();
    List<Module> runtime = new LinkedList<Module>();
    List<Module> overrides = new LinkedList<Module>();
    
    if(initModules != null && initModules.length > 0) {
        allModules.addAll(Arrays.asList(initModules));
    }

    Iterables.addAll(allModules, ServiceLoader.load(Module.class));
    
    for (Module module : allModules) {
        if (module.getClass().isAnnotationPresent(OverrideModule.class))
            overrides.add(module);
        else
            runtime.add(module);
    }
    return overrides.isEmpty() ? Modules.combine(runtime) : Modules.override(runtime).with(overrides);
}
 
Example 2
Source File: Bootstrap.java    From joynr with Apache License 2.0 6 votes vote down vote up
public static final void main(String... args) {
    logger.info("Starting consumer ...");
    Properties joynrProperties = new Properties();
    joynrProperties.put("joynr.messaging.mqtt.brokerUri", "tcp://mqttbroker:1883");
    joynrProperties.put(MessagingPropertyKeys.PROPERTY_MESSAGING_PRIMARYGLOBALTRANSPORT, "mqtt");
    joynrProperties.setProperty(MessagingPropertyKeys.PERSISTENCE_FILE, "consumer-joynr.properties");
    joynrProperties.setProperty(PROPERTY_JOYNR_DOMAIN_LOCAL, "gracefulshutdown_consumer_local_domain");
    Module runtimeModule = Modules.combine(new CCInProcessRuntimeModule(), new HivemqMqttClientModule());
    JoynrInjectorFactory joynrInjectorFactory = new JoynrInjectorFactory(joynrProperties, runtimeModule);
    JoynrApplication application = joynrInjectorFactory.createApplication(ConsumerApplication.class);

    logger.info("Application created.");

    application.run();

    logger.info("Application finished. Shutting down.");

    application.shutdown();
}
 
Example 3
Source File: DockerCassandraRule.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public Module getModule() {
    return Modules.combine(binder -> binder.bind(ClusterConfiguration.class)
        .toInstance(DockerCassandra.configurationBuilder(cassandraContainer.getHost())
            .maxRetry(20)
            .minDelay(5000)
            .build()),
        binder -> binder.bind(KeyspacesConfiguration.class)
            .toInstance(KeyspacesConfiguration.builder()
                .keyspace(DockerCassandra.KEYSPACE)
                .cacheKeyspace(DockerCassandra.CACHE_KEYSPACE)
                .replicationFactor(1)
                .disableDurableWrites()
                .build()),
        binder -> Multibinder.newSetBinder(binder, CleanupTasksPerformer.CleanupTask.class)
            .addBinding()
            .to(CassandraTruncateTableTask.class));
}
 
Example 4
Source File: GuiceUtils.java    From james-project with Apache License 2.0 6 votes vote down vote up
private static Module commonModules(Session session, CassandraTypesProvider typesProvider,
                                    CassandraMessageId.Factory messageIdFactory,
                                    CassandraConfiguration configuration) {
    return Modules.combine(
        binder -> binder.bind(MessageId.Factory.class).toInstance(messageIdFactory),
        binder -> binder.bind(BlobId.Factory.class).toInstance(new HashBlobId.Factory()),
        binder -> binder.bind(BlobStore.class).to(CassandraBlobStore.class),
        binder -> binder.bind(CassandraDumbBlobStore.class).in(SINGLETON),
        binder -> binder.bind(BucketName.class)
            .annotatedWith(Names.named(CassandraDumbBlobStore.DEFAULT_BUCKET))
            .toInstance(BucketName.DEFAULT),
        binder -> binder.bind(Session.class).toInstance(session),
        binder -> binder.bind(CassandraTypesProvider.class).toInstance(typesProvider),
        binder -> binder.bind(CassandraConfiguration.class).toInstance(configuration),
        binder -> binder.bind(CassandraConsistenciesConfiguration.class)
            .toInstance(CassandraConsistenciesConfiguration.fromConfiguration(configuration)));
}
 
Example 5
Source File: TestDrivers.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static Module newConfigModule(
        final ServerConfig.Builder serverConfig,
        final ConnectorConfig.Builder connectorConfigBuilder,
        final Module... guiceModules) {
    return Modules.combine(
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(ServletPathsConfig.class).toInstance(new ServletPathsConfig(new ServletPathsConfig.Builder()));
                    bind(ServerConfig.class).toInstance(new ServerConfig(serverConfig));
                    bind(ConnectorConfig.class).toInstance(new ConnectorConfig(connectorConfigBuilder));
                    bind(FilterBindings.class).toInstance(
                            new FilterBindings(
                                    new BindingRepository<RequestFilter>(),
                                    new BindingRepository<ResponseFilter>()));
                }
            },
            new ConnectorFactoryRegistryModule(connectorConfigBuilder),
            new ServletModule(),
            Modules.combine(guiceModules));
}
 
Example 6
Source File: HttpServerConformanceTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Override
public Module newConfigModule() {
    return Modules.combine(
            new AbstractModule() {
                @Override
                protected void configure() {
                    bind(FilterBindings.class)
                            .toInstance(new FilterBindings(
                                    new BindingRepository<>(),
                                    new BindingRepository<>()));
                    bind(ServerConfig.class)
                            .toInstance(new ServerConfig(new ServerConfig.Builder()));
                    bind(ServletPathsConfig.class)
                            .toInstance(new ServletPathsConfig(new ServletPathsConfig.Builder()));
                }
            },
            new ConnectorFactoryRegistryModule());
}
 
Example 7
Source File: MemQuotaStoreTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected Module getStorageModule() {
  statsProvider = new FakeStatsProvider();
  return Modules.combine(
      new MemStorageModule(),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(StatsProvider.class).toInstance(statsProvider);
        }
      });
}
 
Example 8
Source File: MyRadioConsumerApplication.java    From joynr with Apache License 2.0 5 votes vote down vote up
private static Module getRuntimeModule(String transport, String host, int port, Properties joynrConfig) {
    Module runtimeModule;
    if (transport != null) {
        if (transport.contains("websocket")) {
            joynrConfig.setProperty(WebsocketModule.PROPERTY_WEBSOCKET_MESSAGING_HOST, host);
            joynrConfig.setProperty(WebsocketModule.PROPERTY_WEBSOCKET_MESSAGING_PORT, "" + port);
            joynrConfig.setProperty(WebsocketModule.PROPERTY_WEBSOCKET_MESSAGING_PROTOCOL, "ws");
            joynrConfig.setProperty(WebsocketModule.PROPERTY_WEBSOCKET_MESSAGING_PATH, "");
            runtimeModule = new LibjoynrWebSocketRuntimeModule();
        } else {
            runtimeModule = new CCInProcessRuntimeModule();
        }

        Module backendTransportModules = Modules.EMPTY_MODULE;
        if (transport.contains("http")) {
            backendTransportModules = Modules.combine(backendTransportModules, new AtmosphereMessagingModule());
        }

        if (transport.contains("mqtt")) {
            joynrConfig.put("joynr.messaging.mqtt.brokerUri", "tcp://localhost:1883");
            joynrConfig.put(MessagingPropertyKeys.PROPERTY_MESSAGING_PRIMARYGLOBALTRANSPORT, "mqtt");
            backendTransportModules = Modules.combine(backendTransportModules, new HivemqMqttClientModule());
        }

        return Modules.override(runtimeModule).with(backendTransportModules);
    }

    return Modules.override(new CCInProcessRuntimeModule()).with(new HivemqMqttClientModule());
}
 
Example 9
Source File: ApiTestBase.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Before
@SuppressWarnings("checkstyle:variabledeclarationusagedistance")
public void setUp() throws Exception
{
    SatelliteConnectorImpl stltConnector = Mockito.mock(SatelliteConnectorImpl.class);
    super.setUpWithoutEnteringScope(Modules.combine(
        new CtrlApiCallHandlerModule(),
        new ApiTestModule(stltConnector)
    ));
    // super.setUpWithoutEnteringScope has also initialized satelliteConnector, but with a different
    // mock as we just gave guice to bind to. i.e. override with our local mock
    satelliteConnector = stltConnector;

    testScope.enter();

    TransactionMgrSQL transMgr = new ControllerSQLTransactionMgr(dbConnPool);
    testScope.seed(TransactionMgr.class, transMgr);
    testScope.seed(TransactionMgrSQL.class, transMgr);

    ctrlConf.setConnection(transMgr);
    ctrlConf.setProp(ControllerNetComInitializer.PROPSCON_KEY_DEFAULT_PLAIN_CON_SVC, "ignore");
    ctrlConf.setProp(ControllerNetComInitializer.PROPSCON_KEY_DEFAULT_SSL_CON_SVC, "ignore");

    create(transMgr, ALICE_ACC_CTX);
    create(transMgr, BOB_ACC_CTX);

    transMgr.commit();
    transMgr.returnConnection();

    testScope.exit();

    Mockito.when(netComContainer.getNetComConnector(Mockito.any(ServiceName.class)))
        .thenReturn(tcpConnectorMock);

    enterScope();
}
 
Example 10
Source File: MemTaskStoreTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected Module getStorageModule() {
  statsProvider = new FakeStatsProvider();
  return Modules.combine(
      new MemStorageModule(),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(StatsProvider.class).toInstance(statsProvider);
        }
      });
}
 
Example 11
Source File: MemSchedulerStoreTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected Module getStorageModule() {
  statsProvider = new FakeStatsProvider();
  return Modules.combine(
      new MemStorageModule(),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(StatsProvider.class).toInstance(statsProvider);
        }
      });
}
 
Example 12
Source File: ApiBetaTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected Function<ServletContext, Module> getChildServletModule() {
  return (servletContext) -> Modules.combine(
      new ApiModule(new ApiModule.Options()),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(AnnotatedAuroraAdmin.class).toInstance(thrift);
        }
      }
  );
}
 
Example 13
Source File: MemCronJobStoreTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
protected Module getStorageModule() {
  statsProvider = new FakeStatsProvider();
  return Modules.combine(
      new MemStorageModule(),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(StatsProvider.class).toInstance(statsProvider);
        }
      });
}
 
Example 14
Source File: GuiceGenericLoader.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Inject
public GuiceGenericLoader(Injector injector, ExtendedClassLoader extendedClassLoader, ExtensionConfiguration extensionConfiguration) {

    this.extendedClassLoader = extendedClassLoader;

    Module additionalExtensionBindings = Modules.combine(extensionConfiguration.getAdditionalGuiceModulesForExtensions()
        .stream()
        .map(Throwing.<ClassName, Module>function(className -> instantiateNoChildModule(injector, className)))
        .peek(module -> LOGGER.info("Enabling injects contained in " + module.getClass().getCanonicalName()))
        .collect(Guavate.toImmutableList()));
    this.injector = injector.createChildInjector(additionalExtensionBindings);
}
 
Example 15
Source File: SolidityDomainEditorModuleProvider.java    From solidity-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Module getModule(String... options) {
	return Modules.combine(super.getModule(options), new Module() {
		@Override
		public void configure(Binder binder) {
			binder.bind(IModelCreator.class).to(SolidityModelCreator.class);
		}
	});
}
 
Example 16
Source File: EclipseContextGeneratorExecutorLookup.java    From statecharts with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected Module getContextModule() {
	return Modules.combine(new EclipseContextModule(), new SharedStateModule());
}
 
Example 17
Source File: GuiceJamesServer.java    From james-project with Apache License 2.0 4 votes vote down vote up
public GuiceJamesServer combineWith(Collection<Module> modules) {
    return new GuiceJamesServer(isStartedProbe, Modules.combine(Iterables.concat(Arrays.asList(module), modules)));
}
 
Example 18
Source File: SchedulerMain.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the scheduler by including modules configured from command line arguments in
 * addition to the provided environment-specific module.
 *
 * @param appEnvironmentModule Additional modules based on the execution environment.
 */
@VisibleForTesting
public static void flagConfiguredMain(CliOptions options, Module appEnvironmentModule) {
  AtomicLong uncaughtExceptions = Stats.exportLong("uncaught_exceptions");
  Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
    uncaughtExceptions.incrementAndGet();

    LOG.error("Uncaught exception from " + t + ":" + e, e);
  });

  Module module = Modules.combine(
      appEnvironmentModule,
      getUniversalModule(options),
      new ServiceDiscoveryModule(
          FlaggedZooKeeperConfig.create(options.zk),
          options.main.serversetPath),
      new BackupModule(options.backup, SnapshotterImpl.class),
      new ExecutorModule(options.executor),
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(CliOptions.class).toInstance(options);
          bind(IServerInfo.class).toInstance(
              IServerInfo.build(
                  new ServerInfo()
                      .setClusterName(options.main.clusterName)
                      .setStatsUrlPrefix(options.main.statsUrlPrefix)));
        }
      });

  Lifecycle lifecycle = null;
  try {
    Injector injector = Guice.createInjector(module);
    lifecycle = injector.getInstance(Lifecycle.class);
    SchedulerMain scheduler = new SchedulerMain();
    injector.injectMembers(scheduler);
    try {
      scheduler.run(options.main);
    } finally {
      LOG.info("Application run() exited.");
    }
  } finally {
    if (lifecycle != null) {
      lifecycle.shutdown();
    }
  }
}