下面列出了怎么用com.google.inject.Singleton的API类实例代码及写法,或者点击链接到github查看源代码。
@Singleton @Provides @Named("bridgeEventLoopProvider")
public BridgeServerEventLoopProvider provideEventLoopProvider(BridgeServerConfig serverConfig) {
switch (serverConfig.getEventLoopProvider()) {
case BridgeServerConfig.EVENT_LOOP_PROVIDER_DEFAULT:
case BridgeServerConfig.EVENT_LOOP_PROVIDER_NIO:
logger.info("using nio event loop provider");
return new BridgeServerNioEventLoopProvider();
case BridgeServerConfig.EVENT_LOOP_PROVIDER_EPOLL:
logger.info("using epoll event loop provider");
return new BridgeServerEpollEventLoopProvider();
default:
throw new RuntimeException("unknown event loop provider: " + serverConfig.getEventLoopProvider());
}
}
@Provides
@Singleton
public AccessControl createAccessControl(AccessControlManager accessControlManager)
{
Logger logger = Logger.get(AccessControl.class);
AccessControl loggingInvocationsAccessControl = newProxy(
AccessControl.class,
new LoggingInvocationHandler(
accessControlManager,
new LoggingInvocationHandler.ReflectiveParameterNamesProvider(),
logger::debug));
return ForwardingAccessControl.of(() -> {
if (logger.isDebugEnabled()) {
return loggingInvocationsAccessControl;
}
return accessControlManager;
});
}
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);
}
};
}
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);
}
};
}
@Override
protected void configure() {
String disable = System.getenv("ZWAVE_DISABLE");
if (disable != null) {
bind(ZWaveLocalProcessing.class).to(ZWaveLocalProcessingNoop.class).asEagerSingleton();
return;
}
String port = System.getenv("ZWAVE_PORT");
if (port == null) {
bind(String.class).annotatedWith(Names.named("iris.zwave.port")).toInstance("/dev/ttyO1");
} else {
bind(String.class).annotatedWith(Names.named("iris.zwave.port")).toInstance(port);
}
// bind(ZWaveDriverFactory.class).in(Singleton.class);
bind(ZWaveController.class).in(Singleton.class);
bind(ZWaveLocalProcessing.class).to(ZWaveLocalProcessingDefault.class).asEagerSingleton();
}
@Provides
@Named(GoogleHomeHandler.BEARER_AUTH_NAME)
@Singleton
public RequestAuthorizer bearerAuth(
OAuthDAO oauthDao,
BridgeMetrics metrics,
GoogleBridgeConfig config
) {
return new BearerAuth(oauthDao, metrics, config.getOauthAppId(), (req) -> {
Request request = Transformers.GSON.fromJson(req.content().toString(StandardCharsets.UTF_8), Request.class);
Response res = new Response();
res.setRequestId(request.getRequestId());
res.setPayload(ImmutableMap.of(Constants.Response.ERROR_CODE, Constants.Error.AUTH_EXPIRED));
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.content().writeBytes(Transformers.GSON.toJson(res).getBytes(StandardCharsets.UTF_8));
return response;
});
}
@Provides
@Singleton
Configuration getConfiguration(DefaultDataSourceProvider provider) {
DataSource dataSource = provider.get();
return new DefaultConfiguration()
.set(dataSource)
.set(new SpringConnectionProvider(dataSource))
.set(SQLDialect.valueOf(configurationProvider.get().getSqlDialect()));
}
@Provides
@Singleton
DataSourceTransactionManager provideDataSourceTransactionManager(
DataSource dataSource) {
return new DataSourceTransactionManager(
new TransactionAwareDataSourceProxy(dataSource));
}
@Override
protected void configure() {
bind(OzoneConfiguration.class).toProvider(ConfigurationProvider.class);
bind(ReconHttpServer.class).in(Singleton.class);
bind(DBStore.class)
.toProvider(ReconContainerDBProvider.class).in(Singleton.class);
bind(ReconOMMetadataManager.class)
.to(ReconOmMetadataManagerImpl.class);
bind(OMMetadataManager.class).to(ReconOmMetadataManagerImpl.class);
bind(ContainerSchemaManager.class).in(Singleton.class);
bind(ContainerDBServiceProvider.class)
.to(ContainerDBServiceProviderImpl.class).in(Singleton.class);
bind(OzoneManagerServiceProvider.class)
.to(OzoneManagerServiceProviderImpl.class).in(Singleton.class);
bind(ReconUtils.class).in(Singleton.class);
// Persistence - inject configuration provider
install(new JooqPersistenceModule(
getProvider(DataSourceConfiguration.class)));
install(new ReconOmTaskBindingModule());
install(new ReconDaoBindingModule());
bind(ReconTaskController.class)
.to(ReconTaskControllerImpl.class).in(Singleton.class);
bind(StorageContainerServiceProvider.class)
.to(StorageContainerServiceProviderImpl.class).in(Singleton.class);
bind(OzoneStorageContainerManager.class)
.to(ReconStorageContainerManagerFacade.class).in(Singleton.class);
}
@Before
public void setUp() throws IOException {
tempFolder.create();
injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
File dbDir = tempFolder.getRoot();
OzoneConfiguration configuration = new OzoneConfiguration();
configuration.set(OZONE_RECON_DB_DIR, dbDir.getAbsolutePath());
bind(OzoneConfiguration.class).toInstance(configuration);
bind(DBStore.class).toProvider(ReconContainerDBProvider.class).in(
Singleton.class);
}
});
}
/**
* Executor for sending report state after SYNC responses. Report State is delayed to ensure the SYNC
* reaches google.
*/
@Provides
@Named(HomeGraphAPI.EXECUTOR_NAME)
@Singleton
public HashedWheelTimer googleReportStateExecutor(ProactiveReportingConfig config) {
return new HashedWheelTimer(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("voice-service-google-report-state-%d")
.setUncaughtExceptionHandler(new LoggingUncaughtExceptionHandler(LoggerFactory.getLogger(CommandExecutor.class)))
.build());
}
@Provides
@Singleton
@ForBaseJdbc
public static ConnectionFactory createConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider)
{
Properties connectionProperties = new Properties();
return new DriverConnectionFactory(
new Driver(),
config.getConnectionUrl(),
connectionProperties,
credentialProvider);
}
@Provides
@Singleton
@ForBaseJdbc
public ConnectionFactory getConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider)
{
return new DriverConnectionFactory(new SQLServerDriver(), config, credentialProvider);
}
@Provides
@Singleton
public RESTHandlerConfig provideRestHandlerConfig() {
RESTHandlerConfig restHandlerConfig = new RESTHandlerConfig();
restHandlerConfig.setSendChunked(false);
return restHandlerConfig;
}
@Provides
@Named(VoiceConfig.NAME_EXECUTOR)
@Singleton
public ExecutorService voiceServiceExecutor(VoiceConfig config) {
return new ThreadPoolBuilder()
.withBlockingBacklog()
.withMaxPoolSize(config.getServiceMaxThreads())
.withKeepAliveMs(config.getServiceThreadKeepAliveMs())
.withNameFormat("voice-service-%d")
.withMetrics("voice.service")
.build();
}
@Provides
@Singleton
public ConnectionFactory getConnectionFactory(PhoenixConfig config)
throws SQLException
{
return new StatisticsAwareConnectionFactory(
new DriverConnectionFactory(
DriverManager.getDriver(config.getConnectionUrl()),
config.getConnectionUrl(),
getConnectionProperties(config),
new EmptyCredentialProvider()));
}
@Override
protected void configure() {
String disable = System.getenv("REFLEX_DISABLE");
if (disable != null) {
return;
}
bind(ReflexLocalProcessing.class).in(Singleton.class);
bind(ReflexController.class).in(Singleton.class);
}
@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
@Singleton
public CompositeDriverRegistry provideDriverRegistry(Driver1 driver1, Driver1V1 driver1v1, Driver1V2 driver1v2, Driver2 driver2) {
Map<DriverId, DeviceDriver> map0 = new HashMap<>();
map0.put(driver1.getDriverId(), driver1);
Map<DriverId, DeviceDriver> map1 = new HashMap<>();
map1.put(driver1v1.getDriverId(), driver1v1);
Map<DriverId, DeviceDriver> map2 = new HashMap<>();
map2.put(driver1v2.getDriverId(), driver1v2);
Map<DriverId, DeviceDriver> map3 = new HashMap<>();
map3.put(driver2.getDriverId(), driver2);
return new CompositeDriverRegistry(new MapDriverRegistry(map0), new MapDriverRegistry(map1), new MapDriverRegistry(map2), new MapDriverRegistry(map3));
}
@Provides
@Singleton
@ForHiveMetastore
public HadoopAuthentication createHadoopAuthentication(MetastoreKerberosConfig config, HdfsConfigurationInitializer updater)
{
String principal = config.getHiveMetastoreClientPrincipal();
String keytabLocation = config.getHiveMetastoreClientKeytab();
return createCachingKerberosHadoopAuthentication(principal, keytabLocation, updater);
}
@Override
protected void configure() {
super.configure();
bind(ITimeoutConfiguration.class).to(getTimeoutConfigurationImplementation()).in(Singleton.class);
bind(IBrowserProfile.class).to(getBrowserProfileImplementation()).in(Singleton.class);
bind(IElementFactory.class).to(getElementFactoryImplementation());
bind(IConfiguration.class).to(getConfigurationImplementation());
}
@Provides @Singleton
public Optional<Set<PartitionListener>> getPartitionListeners() {
partitionRef = Capture.newInstance();
PartitionListener partitionListener = EasyMock.createMock(PartitionListener.class);
partitionListener.onPartitionsChanged(EasyMock.capture(partitionRef));
EasyMock.expectLastCall().once();
EasyMock.replay(partitionListener);
return Optional.of(ImmutableSet.of(partitionListener));
}
@Singleton
@Inject
@Provides
CognitoUserManager cognitoUserManager(final SsmParameterCachingClient ssm) {
String clientId = ssm.getAsString("cognito/userpoolclient/IntegTest/Id");
String userPoolId = ssm.getAsString("cognito/userpool/ApplicationsApi/Id");
return new CognitoUserManager(CognitoIdentityProviderClient.builder()
.httpClientBuilder(UrlConnectionHttpClient.builder())
.build(), clientId, userPoolId);
}
@Singleton
@Inject
@Provides
AthenaClient athenaClient(){
return AthenaClient.builder()
.httpClientBuilder(UrlConnectionHttpClient.builder())
.build();
}
@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());
}
@Override
protected void configure() {
bind(InMemoryPlatformMessageBus.class).in(Singleton.class);
bind(InMemoryProtocolMessageBus.class).in(Singleton.class);
bind(PlatformMessageBus.class).to(InMemoryPlatformMessageBus.class);
bind(ProtocolMessageBus.class).to(InMemoryProtocolMessageBus.class);
}
@Singleton
@Inject
@Provides
CognitoUserManager cognitoUserManager(final SsmParameterCachingClient ssm) {
String clientId = ssm.getAsString(String.format(
"cognito/userpoolclient/IntegTest/realworld-serverless-application-backend-%s-env/Id",
System.getProperty("integtests.stage")));
String userPoolId = ssm.getAsString("cognito/userpool/ApplicationsApi/Id");
return new CognitoUserManager(CognitoIdentityProviderClient.builder()
.httpClientBuilder(UrlConnectionHttpClient.builder())
.build(), clientId, userPoolId);
}
@Override
protected void configure() {
bind(ModelManager.class).to(OpenTCSModelManager.class).in(Singleton.class);
bind(ModelFileReader.class).to(UnifiedModelReader.class);
bind(ModelFilePersistor.class).to(UnifiedModelPersistor.class);
}
/**
* Sets the recharge position supplier implementation to be used.
*
* @param clazz The implementation.
* @deprecated Will be removed along with the deprecated supplier interface.
*/
@Deprecated
@ScheduledApiChange(when = "5.0")
protected void bindRechargePositionSupplier(
Class<? extends org.opentcs.components.kernel.RechargePositionSupplier> clazz) {
bind(org.opentcs.components.kernel.RechargePositionSupplier.class).to(clazz).in(Singleton.class);
}
@Provides
@Singleton
public GroovyScriptEngine provideGroovyScriptEngine(TestDriverConfig driverConfig, CapabilityRegistry registry) throws MalformedURLException {
File driverDir = new File(driverConfig.getDriverDirectory());
GroovyScriptEngine engine = new GroovyScriptEngine(new URL[] {
driverDir.toURI().toURL(),
new File("src/main/resources").toURI().toURL()
} );
engine.getConfig().addCompilationCustomizers(new DriverCompilationCustomizer(registry));
return engine;
}