public static <C> PrivateModule module(final PropertyIdentifier propertyIdentifier, final ConfigDescriptor desc) { return new PrivateModule() { @Override protected void configure() { // Alias the private module scoped bindings for the un-annotated ConstantValuePropertyAccessor and PropertyIdentifier to globally scoped and annotated ones. // Intent here is to make the implementation of this nice and guicified but support a number of different instances. bind(ConstantValuePropertyAccessor.class).to(Key.get(ConstantValuePropertyAccessor.class, propertyIdentifier)); bind(PropertyIdentifier.class).to(Key.get(PropertyIdentifier.class, propertyIdentifier)); TypeLiteral<PropertyAccessor<C>> accessorType = (TypeLiteral<PropertyAccessor<C>>) TypeLiteral.get(Types.newParameterizedType(PropertyAccessor.class, desc.getConfigType())); bind(Key.get(accessorType, propertyIdentifier)).to(accessorType).in(Scopes.SINGLETON); expose(Key.get(accessorType, propertyIdentifier)); } }; }
@Override protected void configure() { install(new PrivateModule() { @Override protected void configure() { bind(ScheduledExecutorService.class).toInstance(executor); bind(UpdateFactory.class).to(UpdateFactory.UpdateFactoryImpl.class); bind(UpdateFactory.UpdateFactoryImpl.class).in(Singleton.class); bind(JobUpdateController.class).to(JobUpdateControllerImpl.class); bind(JobUpdateControllerImpl.class).in(Singleton.class); expose(JobUpdateController.class); bind(JobUpdateEventSubscriber.class); expose(JobUpdateEventSubscriber.class); } }); PubsubEventModule.bindSubscriber(binder(), JobUpdateEventSubscriber.class); SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()) .to(JobUpdateEventSubscriber.class); }
@Override protected void configure() { install(new PrivateModule() { @Override protected void configure() { bind(Driver.class).to(SchedulerDriverService.class); bind(SchedulerDriverService.class).in(Singleton.class); expose(Driver.class); bind(Scheduler.class).to(MesosSchedulerImpl.class); bind(MesosSchedulerImpl.class).in(Singleton.class); expose(Scheduler.class); // TODO(zmanji): Create singleThreadedExecutor (non-scheduled) variant. bind(Executor.class).annotatedWith(MesosSchedulerImpl.SchedulerExecutor.class) .toInstance(AsyncUtil.singleThreadLoggingScheduledExecutor("SchedulerImpl-%d", LOG)); } }); PubsubEventModule.bindSubscriber(binder(), TaskStatusStats.class); bind(TaskStatusStats.class).in(Singleton.class); }
@Override protected void configure() { install(new PrivateModule() { @Override protected void configure() { bind(OfferManager.OfferReturnDelay.class).toInstance( new RandomJitterReturnDelay( MIN_OFFER_HOLD_TIME.get().as(Time.MILLISECONDS), OFFER_HOLD_JITTER_WINDOW.get().as(Time.MILLISECONDS), Random.Util.newDefaultRandom())); bind(OfferManager.class).to(OfferManager.OfferManagerImpl.class); bind(OfferManager.OfferManagerImpl.class).in(Singleton.class); expose(OfferManager.class); } }); PubsubEventModule.bindSubscriber(binder(), OfferManager.class); }
@Override protected void configure() { install(new PrivateModule() { @Override protected void configure() { bind(RowGarbageCollector.class).in(Singleton.class); bind(AbstractScheduledService.Scheduler.class).toInstance( AbstractScheduledService.Scheduler.newFixedRateSchedule( 0L, DB_ROW_GC_INTERVAL.get().getValue(), DB_ROW_GC_INTERVAL.get().getUnit().getTimeUnit())); expose(RowGarbageCollector.class); } }); SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()) .to(RowGarbageCollector.class); }
@Override protected void configure() { install(new PrivateModule() { @Override protected void configure() { bind(ScheduledThreadPoolExecutor.class).toInstance(afterTransaction); bind(ScheduledExecutorService.class).toInstance(afterTransaction); bind(GatingDelayExecutor.class).in(Singleton.class); expose(GatingDelayExecutor.class); bind(RegisterGauges.class).in(Singleton.class); expose(RegisterGauges.class); } }); SchedulerServicesModule.addAppStartupServiceBinding(binder()).to(RegisterGauges.class); bind(Executor.class).annotatedWith(AsyncExecutor.class).to(GatingDelayExecutor.class); bind(DelayExecutor.class).annotatedWith(AsyncExecutor.class).to(GatingDelayExecutor.class); bind(GatedWorkQueue.class).annotatedWith(AsyncExecutor.class).to(GatingDelayExecutor.class); }
@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); } }; }
@Override public Module getModule(Configuration configuration) { return new PrivateModule() { @Override protected void configure() { bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class); bind(HttpClient.class).toInstance(new JettyHttpClient()); } @Inject @Provides @Exposed @Singleton QueryStatsClient getQueryStatsClient(HttpClient httpClient, ObjectMapper objectMapper, @Named("presto_rest.base_uri") String prestoRestInterfaceBaseUri) { return new HttpQueryStatsClient(httpClient, objectMapper, URI.create(prestoRestInterfaceBaseUri)); } }; }
public Module build() { checkState(implementation != null, "No implementation set for %s", key); return new AbstractModule() { @Override protected void configure() { install(new PrivateModule() { @Override protected void configure() { install(dependencies); bind(key).to(implementation).in(Singleton.class); expose(key); } }); Multibinder<CuratorService> curatorServices = Multibinder.newSetBinder(binder(), CuratorService.class); curatorServices.addBinding().to(key); } }; }
public void testPrivateModuleInheritScanner_usingPrivateModule() { Injector injector = Guice.createInjector( NamedMunger.module(), new PrivateModule() { @Override protected void configure() {} @Exposed @TestProvides @Named("foo") String foo() { return "foo"; } }); assertMungedBinding(injector, String.class, "foo", "foo"); }
public void testPrivateModule_skipSourcesWithinPrivateModule() { Injector injector = Guice.createInjector( NamedMunger.module(), new PrivateModule() { @Override protected void configure() { binder() .skipSources(getClass()) .install( new AbstractModule() { @Exposed @TestProvides @Named("foo") String foo() { return "foo"; } }); } }); assertMungedBinding(injector, String.class, "foo", "foo"); }
public void testPrivateModule_skipSourcesForPrivateModule() { Injector injector = Guice.createInjector( NamedMunger.module(), new AbstractModule() { @Override protected void configure() { binder() .skipSources(getClass()) .install( new PrivateModule() { @Override protected void configure() {} @Exposed @TestProvides @Named("foo") String foo() { return "foo"; } }); } }); assertMungedBinding(injector, String.class, "foo", "foo"); }
public void testPrivateModuleWithinPrivateModule() { Injector injector = Guice.createInjector( NamedMunger.module(), new PrivateModule() { @Override protected void configure() { expose(Key.get(String.class, named("foo-munged"))); install( new PrivateModule() { @Override protected void configure() {} @Exposed @TestProvides @Named("foo") String foo() { return "foo"; } }); } }); assertMungedBinding(injector, String.class, "foo", "foo"); }
public void testOverrideModuleAndPrivateModule() { Module exposes5 = new PrivateModule() { @Override protected void configure() { bind(Integer.class).toInstance(5); expose(Integer.class); } }; Module binds15 = new AbstractModule() { @Override protected void configure() { bind(Integer.class).toInstance(15); } }; Injector injector = Guice.createInjector(Modules.override(exposes5).with(binds15)); assertEquals(15, injector.getInstance(Integer.class).intValue()); Injector reverse = Guice.createInjector(Modules.override(binds15).with(exposes5)); assertEquals(5, reverse.getInstance(Integer.class).intValue()); }
public Module build() { checkState(namespaceValue != null, "Namespace not provided."); checkState(annotationHolder != null, "Target annotation not provided."); return new PrivateModule() { @Override protected void configure() { bind(CuratorFramework.class).annotatedWith(Private.class).to( Key.get(CuratorFramework.class, Curator.class)); bind(String.class).annotatedWith(Private.class).toProvider(Providers.of(namespaceValue.orNull())); Key<CuratorFramework> frameworkKey = annotationHolder.generateKey(CuratorFramework.class); bind(frameworkKey).to(NamespacedCuratorFramework.class).in(Scopes.SINGLETON); expose(frameworkKey); } }; }
@Override protected void doConfigure() { bind(MailService.class); bind(MailAccountManager.class); bind(SmtpClient.class); install(new PrivateModule() { @Override protected void configure() { bind(MutableInt.class).in(ModuleScoped.class); bind(MailArchiver.class); // expose only MailArchiver expose(MailArchiver.class); } }); install(new FactoryModuleBuilder().build(StoreManager.Factory.class)); bindEventHandler().to(MailboxPurger.class); bindEventHandler().to(MailAccountReleaser.class); }
public void install(Module module) { if (modules.add(module)) { Binder binder = this; if (module instanceof PrivateModule) { binder = binder.newPrivateBinder(); } try { module.configure(binder); } catch (RuntimeException e) { Collection<Message> messages = Errors.getMessagesFromThrowable(e); if (!messages.isEmpty()) { elements.addAll(messages); } else { addError(e); } } binder.install(ProviderMethodsModule.forModule(module)); } }
private Module createLoadTestModule() { return new PrivateModule() { @Override protected void configure() { bind(LoadTestDriver.class).to(loadTestDriverClass).in(Singleton.class); bind(LoadTestDriversCoordinator.class).in(Singleton.class); bind(WorkerEntryProcessor.class).to(entryProcessorClass).in(Singleton.class); bind(Generator.class).annotatedWith(Names.named(KEY_GENERATOR)).to(keyGeneratorClass) .in(Singleton.class); bind(Generator.class).annotatedWith(Names.named(VALUE_GENERATOR)).to(valueGeneratorClass) .in(Singleton.class); bind(LoadTestConfig.class).toInstance(LoadTestConfig.defaultConfig()); } }; }
public static Module module(final Named name) { return new PrivateModule() { @Override protected void configure() { // Alias unannotated config to annotated one bind(Config.class).to(Key.get(Config.class, name)); bind(ExampleSubComponent.class).annotatedWith(name).to(ExampleSubComponent.class); expose(Key.get(ExampleSubComponent.class, name)); } }; }
public static Module module(final Named name) { return Modules.combine( new AbstractModule() { @Override protected void configure() { // ConfigSystem.configModule() creates a module with a lot of bindings that need to be non-private. // make sure you don't specify this within the PrivateModule. install(ConfigSystem.configModule(ProviderExample.Config.class, name)); } }, new PrivateModule() { @Override protected void configure() { // NOTE: MUST explicitly bind and expose this class within the private module for Guice to be able // to use the alias binding below during injection of this class. bind(ProviderExample.class).annotatedWith(name).to(ProviderExample.class); expose(Key.get(ProviderExample.class, name)); // alias binding; only applies to other bind() or install() methods in this private module. Do not expose this. // This allows us to @Inject a Config instance into this class w/o knowing the bound name in advance. bind(Config.class).to(Key.get(Config.class, name)); // Binding for the class being provided by the provider bind(ProviderExample.Foo.class) .annotatedWith(name) .toProvider(Key.get(ProviderExample.class, name)) .in(Scopes.SINGLETON); expose(Key.get(ProviderExample.Foo.class, name)); } }); }
public static Module module(final Named name) { return new PrivateModule() { @Override protected void configure() { // Alias named Example3B to unnamed bind(Config.class).to(Key.get(Config.class, name)); bind(Example3B.class).annotatedWith(name).to(Example3B.class); expose(Key.get(Example3B.class, name)); } }; }
/** * Creates a module that hides all the given module's bindings and only exposes bindings for * the given key. * * @param keys The keys of the bindings to expose. * @param module The module to hide most bindings for. * @return A limited visibility module. */ public static Module exposing(final Iterable<? extends Key<?>> keys, final Module module) { Preconditions.checkNotNull(keys); Preconditions.checkNotNull(module); return new PrivateModule() { @Override protected void configure() { install(module); for (Key<?> key : keys) { expose(key); } } }; }
@Override protected void configure() { bind(TaskIdGenerator.class).to(TaskIdGeneratorImpl.class); install(new PrivateModule() { @Override protected void configure() { bind(LeadingOptions.class).toInstance( new LeadingOptions(MAX_REGISTRATION_DELAY.get(), MAX_LEADING_DURATION.get())); final ScheduledExecutorService executor = AsyncUtil.singleThreadLoggingScheduledExecutor("Lifecycle-%d", LOG); bind(ScheduledExecutorService.class).toInstance(executor); bind(SchedulerLifecycle.class).in(Singleton.class); expose(SchedulerLifecycle.class); } }); PubsubEventModule.bindSubscriber(binder(), SchedulerLifecycle.class); bind(TaskVars.class).in(Singleton.class); PubsubEventModule.bindSubscriber(binder(), TaskVars.class); addSchedulerActiveServiceBinding(binder()).to(TaskVars.class); bind(new TypeLiteral<BlockingQueue<Protos.TaskStatus>>() { }) .annotatedWith(TaskStatusHandlerImpl.StatusUpdateQueue.class) .toInstance(new LinkedBlockingQueue<>()); bind(new TypeLiteral<Integer>() { }) .annotatedWith(TaskStatusHandlerImpl.MaxBatchSize.class) .toInstance(MAX_STATUS_UPDATE_BATCH_SIZE.get()); bind(TaskStatusHandler.class).to(TaskStatusHandlerImpl.class); bind(TaskStatusHandlerImpl.class).in(Singleton.class); addSchedulerActiveServiceBinding(binder()).to(TaskStatusHandlerImpl.class); }
@Override protected void configure() { install(new PrivateModule() { @Override protected void configure() { // TODO(ksweeney): Create a configuration validator module so this can be injected. // TODO(William Farner): Revert this once large task counts is cheap ala hierarchichal store bind(HistoryPrunnerSettings.class).toInstance(new HistoryPrunnerSettings( HISTORY_PRUNE_THRESHOLD.get(), HISTORY_MIN_RETENTION_THRESHOLD.get(), HISTORY_MAX_PER_JOB_THRESHOLD.get() )); bind(TaskHistoryPruner.class).in(Singleton.class); expose(TaskHistoryPruner.class); } }); PubsubEventModule.bindSubscriber(binder(), TaskHistoryPruner.class); install(new PrivateModule() { @Override protected void configure() { bind(JobUpdateHistoryPruner.HistoryPrunerSettings.class).toInstance( new JobUpdateHistoryPruner.HistoryPrunerSettings( JOB_UPDATE_HISTORY_PRUNING_INTERVAL.get(), JOB_UPDATE_HISTORY_PRUNING_THRESHOLD.get(), JOB_UPDATE_HISTORY_PER_JOB_THRESHOLD.get())); bind(ScheduledExecutorService.class).toInstance( AsyncUtil.singleThreadLoggingScheduledExecutor("JobUpdatePruner-%d", LOG)); bind(JobUpdateHistoryPruner.class).in(Singleton.class); expose(JobUpdateHistoryPruner.class); } }); SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()) .to(JobUpdateHistoryPruner.class); }
@Override protected void configure() { bind(TaskStatCalculator.class).in(Singleton.class); bind(CachedCounters.class).in(Singleton.class); bind(MachineResourceProvider.class).to(OfferAdapter.class); bind(SlotSizeCounter.class).in(Singleton.class); install(new PrivateModule() { @Override protected void configure() { bind(TaskStatUpdaterService.class).in(Singleton.class); bind(Scheduler.class).toInstance( Scheduler.newFixedRateSchedule( TASK_STAT_INTERVAL.get().getValue(), TASK_STAT_INTERVAL.get().getValue(), TASK_STAT_INTERVAL.get().getUnit().getTimeUnit())); expose(TaskStatUpdaterService.class); } }); SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()) .to(TaskStatUpdaterService.class); install(new PrivateModule() { @Override protected void configure() { bind(SlotSizeCounterService.class).in(Singleton.class); bind(Scheduler.class).toInstance( Scheduler.newFixedRateSchedule( SLOT_STAT_INTERVAL.get().getValue(), SLOT_STAT_INTERVAL.get().getValue(), SLOT_STAT_INTERVAL.get().getUnit().getTimeUnit())); expose(SlotSizeCounterService.class); } }); SchedulerServicesModule.addSchedulerActiveServiceBinding(binder()) .to(SlotSizeCounterService.class); }
/** * Creates a binding module that will wrap a storage class with {@link CallOrderEnforcingStorage}, * exposing the order-enforced storage as {@link Storage} and {@link NonVolatileStorage}. * * @param storageClass Non-volatile storage implementation class. * @return Binding module. */ public static Module wrappingModule(final Class<? extends NonVolatileStorage> storageClass) { return new PrivateModule() { @Override protected void configure() { bind(Storage.class).to(CallOrderEnforcingStorage.class); bind(NonVolatileStorage.class).to(CallOrderEnforcingStorage.class); bind(CallOrderEnforcingStorage.class).in(Singleton.class); bind(NonVolatileStorage.class).annotatedWith(EnforceOrderOn.class).to(storageClass); expose(Storage.class); expose(NonVolatileStorage.class); } }; }
public void install(Binder binder) { binder.install(new PrivateModule() { @Override protected void configure() { PassType.this.bind(binder()); } }); }
private Module createPrivateInjectNameModule(final Named name) { return new PrivateModule() { @Override protected void configure() { bind(NameHolder.class).annotatedWith(name).to(NameHolder.class); expose(NameHolder.class).annotatedWith(name); bind(Named.class).toInstance(name); } }; }
public static void main(String[] args) { LifeManager manager = new LifeManager(); manager.add(Guice.createInjector(new PrivateModule() { @Override protected void configure() { bind(Service.class).annotatedWith(Names.named("1")) .to(ServiceImpl.class) .in(Scopes.SINGLETON); expose(Service.class).annotatedWith(Names.named("1")); bind(ImplWorker.class).toInstance(new ImplWorker() { @Override public void work() { System.out.println("work 1 done"); } }); } }, new PrivateModule() { @Override protected void configure() { bind(Service.class).annotatedWith(Names.named("2")) .to(ServiceImpl.class) .in(Scopes.SINGLETON); expose(Service.class).annotatedWith(Names.named("2")); bind(ImplWorker.class).toInstance(new ImplWorker() { @Override public void work() { System.out.println("work 2 done"); } }); } }, new AbstractModule() { @Override protected void configure() { final Annotation id = UniqueAnnotations.create(); bind(Listener.class).annotatedWith(id).to(Client.class).asEagerSingleton(); } })); manager.start(); }
@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(RetryPolicy.class).toInstance(retry); bind(ProtobufDecoder.class).in(Scopes.SINGLETON); bind(key).to(ProtobufPluginSource.class).in(Scopes.SINGLETON); expose(key); } }; }
@Override public Module module(final Key<PluginSource> key, final String id) { return new PrivateModule() { @Override protected void configure() { bind(CarbonDecoder.class).toInstance(new CarbonDecoder(metricKey)); bind(Protocol.class).toInstance(protocol); bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON); bind(RetryPolicy.class).toInstance(retry); bind(key).to(CarbonPluginSource.class).in(Scopes.SINGLETON); expose(key); } }; }
@Override public Module module(final Key<PluginSource> key, final String id) { return new PrivateModule() { @Override protected void configure() { bind(JsonObjectMapperDecoder.class).in(Scopes.SINGLETON); bind(Protocol.class).toInstance(protocol); bind(ProtocolServer.class).to(protocolServer).in(Scopes.SINGLETON); bind(RetryPolicy.class).toInstance(retry); bind(key).to(JsonPluginSource.class).in(Scopes.SINGLETON); expose(key); } }; }
@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(RetryPolicy.class).toInstance(retry); bind(HttpDecoder.class).in(Scopes.SINGLETON); bind(key).to(HttpPluginSource.class).in(Scopes.SINGLETON); expose(key); } }; }
@Override public Module module(final Key<PluginSink> key, final String id) { return new PrivateModule() { @Override protected void configure() { bind(Logger.class).toInstance(LoggerFactory.getLogger(id)); bind(TemplateOutputEncoder.class).toInstance(new TemplateOutputEncoder()); bind(Protocol.class).toInstance(protocol); bind(ProtocolClient.class).toInstance(new TemplateOutputProtocolClient()); bind(key).toInstance(new ProtocolPluginSink(retry)); expose(key); } }; }
/** * This method allows to wrap plugin sink implementation type depending on configuration. * If no additional configuration is specified then subtype of * com.spotify.ffwd.output.BatchedPluginSink will be bound per plugin. * * <code>output := new SubtypeOfBatchedPluginSink()</code> * * If 'flushInterval' key is specified, then corresponding subtype of * com.spotify.ffwd.output.BatchedPluginSink will be wrapped into * com.spotify.ffwd.output.FlushingPluginSink: * * <code>output := new FlushingPluginSink(flushInterval, delegator:=output)</code> * * The resulting plugin sink type may be further wrapped into * com.spotify.ffwd.output.FilteringPluginSink type if 'filter' key is specified * in plugin configuration: * * <code>output := new FilteringPluginSink(filter, delegator:=output)</code> * * @param input binding key with injection type of plugin sink * @param output binding key, containing injection type of wrapping plugin sink * @return module that exposes output binding key */ protected Module wrapPluginSink( final Key<? extends PluginSink> input, final Key<PluginSink> output ) { return new PrivateModule() { @Override protected void configure() { Key<PluginSink> sinkKey = (Key<PluginSink>) input; if (flushInterval != null && flushInterval.isPresent() && BatchedPluginSink.class.isAssignableFrom( sinkKey.getTypeLiteral().getRawType())) { final Key<PluginSink> flushingKey = Key.get(PluginSink.class, Names.named("flushing")); install(new OutputDelegatingModule<>(sinkKey, flushingKey, new FlushingPluginSink(flushInterval.get()))); sinkKey = flushingKey; } if (filter != null && filter.isPresent()) { final Key<PluginSink> filteringKey = Key.get(PluginSink.class, Names.named("filtered")); install(new OutputDelegatingModule<>(sinkKey, filteringKey, new FilteringPluginSink(filter.get()))); sinkKey = filteringKey; } bind(output).to(sinkKey); expose(output); } }; }
@Override public Module module(final Key<PluginSource> key, final String id) { return new PrivateModule() { @Override protected void configure() { bind(key).toInstance(new GeneratedPluginSource(sameHost)); expose(key); } }; }
@Test public void testPrivateModule() throws Exception { Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), new Module() { @Override public void configure(Binder binder) { binder.install(new PrivateModule() { @Override protected void configure() { binder().bind(SimpleBase.class).to(SimpleBaseImpl.class).in(Scopes.SINGLETON); binder().expose(SimpleBase.class); } }); } }); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); Assert.assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl")); lifeCycleManager.destroy(); Assert.assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl", "preSimpleBaseImpl")); }