下面列出了怎么用com.google.inject.PrivateModule的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void configure() {
// As a workaround to fix GH-724, this is copied from org.eclipse.xtext.ui.shared.internal.SharedModule
// and the default must be kept in sync with the corresponding code there!!
binder().install(new PrivateModule() {
@Override
protected void configure() {
bind(ReferenceSearchViewPage.class);
bind(ReferenceSearchResultLabelProvider.class);
// Workaround to fix GH-724.
bind(ReferenceSearchResultContentProvider.class).to(MyReferenceSearchResultContentProvider.class);
bind(ReferenceSearchViewSorter.class);
expose(ReferenceSearchViewPage.class);
}
});
}
@Override
public void configure(Binder binder) {
binder.install(new PrivateModule() {
@Override
protected void configure() {
// we bind the internally required services of the two exposed bindings
// in a private module. This is to avoid them being available via
// ISharedStateContributionRegistry.getContributedInstances
//
// This is effectively a means to encapsulate the implementation details and hide
// them from the globally available services
bind(IStorage2UriMapperContribution.class).to(BuiltinSchemeUriMapperContribution.class);
bind(IResourceSetInitializer.class).to(BuiltInSchemeResourceSetInitializer.class);
bind(EffectiveRegistrarProvider.class);
bind(BuiltInSchemeRegistrar.class);
bind(ResourceSetWithBuiltInSchemeProvider.class)
.to(ContributionAwareResourceSetWithBuiltInSchemeProvider.class);
bind(UriExtensions.class);
bind(ClassLoader.class).toInstance(getClass().getClassLoader());
// Here we expose the two services that are supposed to be publicly available.
expose(IResourceSetInitializer.class);
expose(IStorage2UriMapperContribution.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 PrivateModule provideAdditionalSecurityModule() {
return new ShiroModule() {
@Override
protected void configureShiro() {
try {
bind(org.apache.shiro.mgt.SecurityManager.class)
.annotatedWith(Names.named("test"))
.toConstructor(DefaultSecurityManager.class.getConstructor(Collection.class))
.asEagerSingleton();
} catch (NoSuchMethodException e) {
throw new RuntimeException("Internal error", e);
}
expose(SecurityManager.class).annotatedWith(Names.named("test"));
}
};
}
@Override
protected void configure() {
install(new PrivateModule() {
@Override
protected void configure() {
// Validator factory
bind(ValidatorFactory.class).toProvider(ValidatorFactoryProvider.class).in(Scopes.SINGLETON);
expose(ValidatorFactory.class);
// Validator
bind(Validator.class).toProvider(ValidatorProvider.class).in(Scopes.SINGLETON);
expose(Validator.class);
// Detected constraint validators
constraintValidators.forEach(this::bind);
}
});
// Validation on injection / method call
enableValidationOnInjectionPoints();
if (isDynamicValidationSupported()) {
configureDynamicValidation();
}
}
@Override
protected void configure() {
bind(new TypeLiteral<Amount<Long, Time>>() { })
.annotatedWith(
MaintenanceController.MaintenanceControllerImpl.PollingInterval.class)
.toInstance(options.hostMaintenancePollingInterval);
bind(MaintenanceController.class).to(MaintenanceController.MaintenanceControllerImpl.class);
bind(MaintenanceController.MaintenanceControllerImpl.class).in(Singleton.class);
PubsubEventModule.bindSubscriber(
binder(),
MaintenanceController.MaintenanceControllerImpl.class);
install(new PrivateModule() {
@Override
protected void configure() {
bind(ScheduledExecutorService.class).toInstance(
AsyncUtil.singleThreadLoggingScheduledExecutor("MaintenanceController-%d", LOG));
}
});
SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
.to(MaintenanceController.MaintenanceControllerImpl.class);
}
@Override
protected void configure() {
install(new PrivateModule() {
@Override
protected void configure() {
bind(ScheduledThreadPoolExecutor.class).toInstance(afterTransaction);
bind(RegisterGauges.class).in(Singleton.class);
expose(RegisterGauges.class);
}
});
SchedulerServicesModule.addAppStartupServiceBinding(binder()).to(RegisterGauges.class);
bind(Executor.class).annotatedWith(AsyncExecutor.class).toInstance(afterTransaction);
bind(ScheduledExecutorService.class).annotatedWith(AsyncExecutor.class)
.toInstance(afterTransaction);
}
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);
}
};
}
@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<PluginSink> key, final String id) {
return new PrivateModule() {
@Override
protected void configure() {
bind(Logger.class).toInstance(LoggerFactory.getLogger(id));
bind(key).toInstance(
new OpenCensusPluginSink(gcpProject, maxViews, outputMetricNamePattern)
);
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);
}
};
}
@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);
}
};
}
@Override
public PrivateModule provideMainSecurityModule(SecurityGuiceConfigurer securityGuiceConfigurer) {
return servletContext != null ? new WebSecurityModule(
servletContext,
securityConfig,
scannedFilters,
applicationId,
securityGuiceConfigurer
) : null;
}
@Override
protected void configure() {
install(new SecurityInternalModule(securityConfigurer, scopeClasses));
install(new SecurityAopModule(crudActionResolvers));
if (elAvailable) {
install(new SecurityExpressionModule());
}
Module mainModuleToInstall = null;
for (SecurityProvider securityProvider : securityProviders) {
PrivateModule mainSecurityModule = securityProvider.provideMainSecurityModule(
new SecurityGuiceConfigurer(securityConfigurer.getSecurityConfiguration()));
if (mainSecurityModule != null) {
if (mainModuleToInstall == null || mainModuleToInstall instanceof DefaultSecurityModule) {
mainModuleToInstall = mainSecurityModule;
} else if (!(mainSecurityModule instanceof DefaultSecurityModule)) {
throw SeedException
.createNew(SecurityErrorCode.MULTIPLE_MAIN_SECURITY_MODULES)
.put("first", mainModuleToInstall.getClass().getCanonicalName())
.put("second", mainSecurityModule.getClass().getCanonicalName());
}
}
PrivateModule additionalSecurityModule = securityProvider.provideAdditionalSecurityModule();
if (additionalSecurityModule != null) {
install(removeSecurityManager(additionalSecurityModule));
}
}
install(mainModuleToInstall);
}
/**
* 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(options.maxRegistrationDelay, options.maxLeadingDuration));
final ScheduledExecutorService executor =
AsyncUtil.singleThreadLoggingScheduledExecutor("Lifecycle-%d", LOG);
bind(ScheduledExecutorService.class).toInstance(executor);
bind(SchedulerLifecycle.class).in(Singleton.class);
expose(SchedulerLifecycle.class);
}
});
PubsubEventModule.bindRegisteredSubscriber(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(options.maxStatusUpdateBatchSize);
bind(TaskStatusHandler.class).to(TaskStatusHandlerImpl.class);
bind(TaskStatusHandlerImpl.class).in(Singleton.class);
addSchedulerActiveServiceBinding(binder()).to(TaskStatusHandlerImpl.class);
bind(TaskEventBatchWorker.class).in(Singleton.class);
addSchedulerActiveServiceBinding(binder()).to(TaskEventBatchWorker.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(TaskHistoryPruner.HistoryPrunerSettings.class).toInstance(
new TaskHistoryPruner.HistoryPrunerSettings(
options.historyPruneThreshold,
options.historyMinRetentionThreshold,
options.historyMaxPerJobThreshold));
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(
options.jobUpdateHistoryPruningInterval,
options.jobUpdateHistoryPruningThreshold,
options.jobUpdateHistoryPerJobThreshold));
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);
Amount<Long, Time> taskStatInterval = options.taskStatInterval;
bind(Scheduler.class).toInstance(
Scheduler.newFixedRateSchedule(
taskStatInterval.getValue(),
taskStatInterval.getValue(),
taskStatInterval.getUnit().getTimeUnit()));
expose(TaskStatUpdaterService.class);
}
});
SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
.to(TaskStatUpdaterService.class);
install(new PrivateModule() {
@Override
protected void configure() {
bind(SlotSizeCounterService.class).in(Singleton.class);
Amount<Long, Time> slotStatInterval = options.slotStatInterval;
bind(Scheduler.class).toInstance(
Scheduler.newFixedRateSchedule(
slotStatInterval.getValue(),
slotStatInterval.getValue(),
slotStatInterval.getUnit().getTimeUnit()));
expose(SlotSizeCounterService.class);
}
});
SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
.to(SlotSizeCounterService.class);
}
@Override
protected void configure() {
install(new PrivateModule() {
@Override
protected void configure() {
bind(new TypeLiteral<Ordering<HostOffer>>() { })
.toInstance(OfferOrderBuilder.create(options.offer.offerOrder));
bind(OfferSetImpl.class).in(Singleton.class);
bind(OfferSet.class).to(OfferSetImpl.class);
expose(OfferSet.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);
}
};
}
/**
* 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.
* <p>
* <code>output := new SubtypeOfBatchedPluginSink()</code>
* <p>
* If 'flushInterval' key is specified, then corresponding subtype of
* com.spotify.ffwd.output.BatchedPluginSink will be wrapped into com.spotify.ffwd.output
* .FlushingPluginSink:
* <p>
* <code>output := new FlushingPluginSink(flushInterval, delegator:=output)</code>
* <p>
* The resulting plugin sink type may be further wrapped into com.spotify.ffwd.output
* .FilteringPluginSink type if 'filter' key is specified in plugin configuration:
* <p>
* <code>output := new FilteringPluginSink(filter, delegator:=output)</code>
*
* @param input binding key with injection type of plugin sink
* @param wrapKey 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> wrapKey
) {
return new PrivateModule() {
@Override
protected void configure() {
@SuppressWarnings("unchecked")
Key<PluginSink> sinkKey = (Key<PluginSink>) input;
if (batching.getFlushInterval() != null &&
BatchablePluginSink.class.isAssignableFrom(
input.getTypeLiteral().getRawType())) {
final Key<PluginSink> flushingKey =
Key.get(PluginSink.class, Names.named("flushing"));
// IDEA doesn't like this cast, but it's correct, tho admittedly not pretty
@SuppressWarnings({"RedundantCast", "unchecked"})
final Key<? extends BatchablePluginSink> batchedPluginSink =
(Key<? extends BatchablePluginSink>) (Key<? extends PluginSink>) sinkKey;
// Use annotation so that we can avoid name space clash
bind(BatchablePluginSink.class)
.annotatedWith(BatchingDelegate.class)
.to(batchedPluginSink);
bind(flushingKey).toInstance(
new BatchingPluginSink(batching.getFlushInterval(),
batching.getBatchSizeLimit(), batching.getMaxPendingFlushes()));
sinkKey = flushingKey;
}
if (filter.isPresent()) {
final Key<PluginSink> filteringKey =
Key.get(PluginSink.class, Names.named("filtered"));
// Use annotation so that we can avoid name space clash
bind(PluginSink.class).annotatedWith(FilteringDelegate.class).to(sinkKey);
bind(filteringKey).toInstance(new FilteringPluginSink(filter.get()));
sinkKey = filteringKey;
}
bind(wrapKey).to(sinkKey);
expose(wrapKey);
}
@Provides
@Singleton
public BatchingStatistics batchingStatisticsProvider(
CoreStatistics statistics, @Named("pluginId") String pluginId, Logger log
) {
if (batching.isReportStatistics()) {
log.info("Enabling reporting of batching-specific metrics for output " +
input.getTypeLiteral().getRawType().getName());
return statistics.newBatching(pluginId);
} else {
return NoopCoreStatistics.noopBatchingStatistics;
}
}
};
}
@Override
public PrivateModule provideAdditionalSecurityModule() {
return null;
}
@Override
public PrivateModule provideMainSecurityModule(SecurityGuiceConfigurer securityGuiceConfigurer) {
return new DefaultSecurityModule(securityGuiceConfigurer);
}
@Override
public PrivateModule provideAdditionalSecurityModule() {
return null;
}
private Module removeSecurityManager(PrivateModule module) {
return new ModuleWithoutSecurityManager((PrivateElements) Elements.getElements(module).iterator().next());
}
@Override
public PrivateModule provideMainSecurityModule(SecurityGuiceConfigurer securityGuiceConfigurer) {
return null;
}
@Override
protected void configure() {
install(new PrivateModule() {
@Override
protected void configure() {
bind(TaskGroups.TaskGroupsSettings.class).toInstance(new TaskGroups.TaskGroupsSettings(
options.firstScheduleDelay,
new TruncatedBinaryBackoff(options.initialSchedulePenalty, options.maxSchedulePenalty),
RateLimiter.create(options.maxScheduleAttemptsPerSec),
options.maxTasksPerScheduleAttempt));
bind(RescheduleCalculatorImpl.RescheduleCalculatorSettings.class)
.toInstance(new RescheduleCalculatorImpl.RescheduleCalculatorSettings(
new TruncatedBinaryBackoff(options.initialFlappingDelay, options.maxFlappingDelay),
options.flappingThreshold,
options.maxReschedulingDelay));
bind(RescheduleCalculator.class).to(RescheduleCalculatorImpl.class).in(Singleton.class);
expose(RescheduleCalculator.class);
bind(TaskGroups.class).in(Singleton.class);
expose(TaskGroups.class);
}
});
PubsubEventModule.bindSubscriber(binder(), TaskGroups.class);
bind(new TypeLiteral<Integer>() { })
.annotatedWith(TaskGroups.SchedulingMaxBatchSize.class)
.toInstance(options.schedulingMaxBatchSize);
bind(TaskGroups.TaskGroupBatchWorker.class).in(Singleton.class);
addSchedulerActiveServiceBinding(binder()).to(TaskGroups.TaskGroupBatchWorker.class);
install(new PrivateModule() {
@Override
protected void configure() {
bind(new TypeLiteral<BiCache<String, TaskGroupKey>>() { }).in(Singleton.class);
bind(BiCache.BiCacheSettings.class).toInstance(
new BiCache.BiCacheSettings(options.reservationDuration, "reservation"));
bind(TaskScheduler.class).to(TaskSchedulerImpl.class);
bind(TaskSchedulerImpl.class).in(Singleton.class);
expose(TaskScheduler.class);
}
});
PubsubEventModule.bindSubscriber(binder(), TaskScheduler.class);
install(new PrivateModule() {
@Override
protected void configure() {
bind(TaskThrottler.class).in(Singleton.class);
expose(TaskThrottler.class);
}
});
PubsubEventModule.bindSubscriber(binder(), TaskThrottler.class);
}