下面列出了怎么用com.google.inject.Provides的API类实例代码及写法,或者点击链接到github查看源代码。
@Singleton
@Provides
KuduClientSession createKuduClientSession(KuduClientConfig config)
{
requireNonNull(config, "config is null");
KuduClient.KuduClientBuilder builder = new KuduClient.KuduClientBuilder(config.getMasterAddresses());
builder.defaultAdminOperationTimeoutMs(config.getDefaultAdminOperationTimeout().toMillis());
builder.defaultOperationTimeoutMs(config.getDefaultOperationTimeout().toMillis());
builder.defaultSocketReadTimeoutMs(config.getDefaultSocketReadTimeout().toMillis());
if (config.isDisableStatistics()) {
builder.disableStatistics();
}
KuduClient client = builder.build();
SchemaEmulation strategy;
if (config.isSchemaEmulationEnabled()) {
strategy = new SchemaEmulationByTableNameConvention(config.getSchemaEmulationPrefix());
}
else {
strategy = new NoSchemaEmulation();
}
return new KuduClientSession(client, strategy);
}
@Provides
@Singleton
private static Optional<BackupStore> createBackupStore(
@Nullable BackupStore store,
LifeCycleManager lifeCycleManager,
MBeanExporter exporter,
RaptorConnectorId connectorId,
BackupConfig config)
{
if (store == null) {
return Optional.empty();
}
BackupStore proxy = new TimeoutBackupStore(
store,
connectorId.toString(),
config.getTimeout(),
config.getTimeoutThreads());
lifeCycleManager.addInstance(proxy);
BackupStore managed = new ManagedBackupStore(proxy);
exporter.exportWithGeneratedName(managed, BackupStore.class, connectorId.toString());
return Optional.of(managed);
}
public static Module kerberosImpersonatingHdfsAuthenticationModule()
{
return new Module()
{
@Override
public void configure(Binder binder)
{
binder.bind(HdfsAuthentication.class)
.to(ImpersonatingHdfsAuthentication.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);
}
};
}
@Provides
@Singleton
public HeartbeatManager provideHeartBeat(EventBus eventBus, Clock clock) {
HeartbeatManager heartbeatManager =
new HeartbeatManager(
new ConcurrentHashMap<>(),
MoreExecutors.getExitingScheduledExecutorService(
(ScheduledThreadPoolExecutor)
Executors.newScheduledThreadPool(
1,
new ThreadFactoryBuilder().setNameFormat("heartbeat-manager-%d").build())),
eventBus,
clock,
heartbeatConfiguration);
eventBus.register(heartbeatManager);
return heartbeatManager;
}
@Provides
@Singleton
public WarningCollectorFactory createWarningCollectorFactory(WarningCollectorConfig config)
{
requireNonNull(config, "config is null");
return () -> new DefaultWarningCollector(config);
}
@Provides
@Singleton
public ExecutorService previewImageExecutor(PreviewConfig config) {
return new ThreadPoolBuilder()
.withBlockingBacklog()
.withMaxPoolSize(config.getStorageAzureMaxThreads())
.withKeepAliveMs(config.getStorageAzureKeepAliveMs())
.withNameFormat("preview-image-writer-%d")
.withMetrics("preview.azure")
.build();
}
@Singleton
@Provides
public static MongoSession createMongoSession(TypeManager typeManager, MongoClientConfig config)
{
requireNonNull(config, "config is null");
MongoClientOptions.Builder options = MongoClientOptions.builder();
options.connectionsPerHost(config.getConnectionsPerHost())
.connectTimeout(config.getConnectionTimeout())
.socketTimeout(config.getSocketTimeout())
.socketKeepAlive(config.getSocketKeepAlive())
.sslEnabled(config.getSslEnabled())
.maxWaitTime(config.getMaxWaitTime())
.minConnectionsPerHost(config.getMinConnectionsPerHost())
.readPreference(config.getReadPreference().getReadPreference())
.writeConcern(config.getWriteConcern().getWriteConcern());
if (config.getRequiredReplicaSetName() != null) {
options.requiredReplicaSetName(config.getRequiredReplicaSetName());
}
MongoClient client = new MongoClient(config.getSeeds(), config.getCredentials(), options.build());
return new MongoSession(
typeManager,
client,
config);
}
@Singleton
@Provides
public Gson gson () {
return new GsonBuilder()
.serializeNulls()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
.create();
}
@Provides
@Singleton
@ForBaseJdbc
public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider)
{
return new DriverConnectionFactory(new Driver(), config, credentialProvider);
}
@Provides
@Named(GroovyDriverModule.NAME_GROOVY_DRIVER_DIRECTORIES)
public Set<URL> groovyDriverUrls(DriverConfig config) throws MalformedURLException {
Set<URL> urls = new LinkedHashSet<>();
urls.add(new File(config.evaluateAbsoluteDriverDirectory()).toURI().toURL());
return urls;
}
@Singleton
@Inject
@Provides
SsmParameterCachingClient ssmParameterCachingClient() {
String path = String.format("/applications/apprepo/%s/", System.getProperty("integtests.stage"));
return new SsmParameterCachingClient(SsmClient.builder()
.httpClientBuilder(UrlConnectionHttpClient.builder())
.build(),
Duration.ofMinutes(5), path);
}
@Singleton
@Inject
@Provides
AWSServerlessApplicationRepository AWSServerlessApplicationRepository(final SsmParameterCachingClient ssm, final CognitoUserManager cognitoUserManager) {
String endpoint = ssm.getAsString("apigateway/ApplicationsApi/Endpoint");
return new AWSServerlessApplicationRepositoryRecordingClient(AWSServerlessApplicationRepository.builder()
.endpoint(endpoint)
.signer(new CognitoAuthorizerImpl(cognitoUserManager))
.build());
}
@Provides
@Singleton
@ForEnvironment
public String getEnvironment(ResourceGroupConfigurationManagerContext context)
{
return context.getEnvironment();
}
@Provides
public Scheduler scheduler(SubsystemConfig config) {
ScheduledExecutorService executor =
Executors
.newScheduledThreadPool(
config.getSchedulerThreads(),
ThreadPoolBuilder
.defaultFactoryBuilder()
.setNameFormat("subsystem-scheduler-%d")
.build()
);
return new ExecutorScheduler(executor);
}
@Provides
@Singleton
public HiveMetastore createCachingHiveMetastore(
@ForCachingHiveMetastore HiveMetastore delegate,
@ForCachingHiveMetastore Executor executor,
CachingHiveMetastoreConfig config,
Optional<HiveMetastoreDecorator> hiveMetastoreDecorator)
{
HiveMetastore decoratedDelegate = hiveMetastoreDecorator.map(decorator -> decorator.decorate(delegate))
.orElse(delegate);
return cachingHiveMetastore(decoratedDelegate, executor, config);
}
@Provides @Named("tcpChannelOptions")
public Map<ChannelOption<?>, Object> provideTcpChannelOptions(BridgeServerConfig serverConfig) {
return ImmutableMap.of(
ChannelOption.TCP_NODELAY, true,
ChannelOption.AUTO_CLOSE, true,
ChannelOption.SO_KEEPALIVE, serverConfig.isSoKeepAlive()
);
}
@Provides @Singleton
public PreviewStorage provideSnapshotStorage(PreviewConfig config) {
switch (config.getStorageType()) {
case PreviewConfig.PREVIEWS_STORAGE_TYPE_FS:
return new PreviewStorageFile(config.getStorageFsBasePath());
case PreviewConfig.PREVIEWS_STORAGE_TYPE_AZURE:
return new PreviewStorageAzure(config.getStorageAzureAccounts(),config.getStorageAzureContainer(),previewImageExecutor(config));
case PreviewConfig.PREVIEWS_STORAGE_TYPE_NULL:
return new PreviewStorageNull();
default:
throw new RuntimeException("unknown video storage type: " + config.getStorageType());
}
}
@Singleton
@Inject
@Provides
SsmParameterCachingClient ssmParameterCachingClient() {
String path = String.format("/applications/apprepo/%s/", System.getProperty("integtests.stage"));
return new SsmParameterCachingClient(SsmClient.builder()
.httpClientBuilder(UrlConnectionHttpClient.builder())
.build(),
Duration.ofMinutes(5), path);
}
@ForMetadata
@Singleton
@Provides
public IDBI createDBI(@ForMetadata ConnectionFactory connectionFactory, TypeManager typeManager)
{
DBI dbi = new DBI(connectionFactory);
dbi.registerMapper(new TableColumn.Mapper(typeManager));
dbi.registerMapper(new Distribution.Mapper(typeManager));
createTablesWithRetry(dbi);
return dbi;
}
@Provides
@Named(VoiceConfig.NAME_TIMEOUT_TIMER)
@Singleton
public HashedWheelTimer timeoutTimer() {
return new HashedWheelTimer(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("voice-execute-timeout-%d")
.setUncaughtExceptionHandler(new LoggingUncaughtExceptionHandler(LoggerFactory.getLogger(CommandExecutor.class)))
.build());
}
@Provides
@Singleton
public BigQueryClient provideBigQueryClient(BigQueryConfig config, HeaderProvider headerProvider, BigQueryCredentialsSupplier bigQueryCredentialsSupplier)
{
String billingProjectId = calculateBillingProjectId(config.getParentProjectId(), bigQueryCredentialsSupplier.getCredentials());
BigQueryOptions.Builder options = BigQueryOptions.newBuilder()
.setHeaderProvider(headerProvider)
.setProjectId(billingProjectId);
// set credentials of provided
bigQueryCredentialsSupplier.getCredentials().ifPresent(options::setCredentials);
return new BigQueryClient(options.build().getService(), config);
}
@Provides
public List<Authenticator> getAuthenticatorList(SecurityConfig config, Map<String, Authenticator> authenticators)
{
return authenticationTypes(config).stream()
.map(type -> {
Authenticator authenticator = authenticators.get(type);
if (authenticator == null) {
throw new RuntimeException("Unknown authenticator type: " + type);
}
return authenticator;
})
.collect(toImmutableList());
}
@Provides @Singleton TemplateService templateService(){
HandlebarsTemplateService hbTemplateService = new HandlebarsTemplateService(templatePath, cacheSize);
if(helpers!=null){
hbTemplateService.registerHelpers(helpers);
}
return hbTemplateService;
}
@Provides @Named("notifications.executor")
public ExecutorService getNotificationsExecutor(NotificationServiceConfig config) {
return new ThreadPoolBuilder()
.withMaxPoolSize(config.getMaxThreads())
.withKeepAliveMs(config.getThreadKeepAliveMs())
.withNameFormat("notification-dispatcher-%d")
.withBlockingBacklog()
.withMetrics("service.notifications")
.build();
}
@Provides
@Singleton
public GroovyScriptEngine scriptEngine(Set<CompilationCustomizer> customizers) {
GroovyScriptEngine engine = scriptEngine();
for(CompilationCustomizer customizer: customizers) {
engine.getConfig().addCompilationCustomizers(customizer);
}
engine.getConfig().setScriptExtensions(ImmutableSet.of("driver", "capability", "groovy"));
return engine;
}
@ForHiveTransactionHeartbeats
@Singleton
@Provides
public ScheduledExecutorService createHiveTransactionHeartbeatExecutor(CatalogName catalogName, HiveConfig hiveConfig)
{
return newScheduledThreadPool(
hiveConfig.getHiveTransactionHeartbeatThreads(),
daemonThreadsNamed("hive-heartbeat-" + catalogName + "-%s"));
}
@Provides @Named(PopulationService.PROP_THREADPOOL)
public Executor populationExecutor() {
return executor;
}
@Provides
public TableMasterClient provideCatalogMasterClient(AlluxioHiveMetastoreConfig config)
{
return createCatalogMasterClient(config);
}
@Provides @Named(ClusterService.NAME_EXECUTOR) @Singleton
public ScheduledExecutorService clusterServiceHeartbeatExecutor() {
return ThreadPoolBuilder.newSingleThreadedScheduler("cluster-heartbeat-executor");
}
@Provides
StealingArtefactsConfig getStealingArtefactsConfig(ConfigManager configManager)
{
return configManager.getConfig(StealingArtefactsConfig.class);
}