Java Code Examples for javax.inject.Singleton

The following are top voted examples for showing how to use javax.inject.Singleton. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Quran   File: DebugNetworkModule.java   Source Code and License 6 votes vote down vote up
@Provides
@Singleton
static OkHttpClient provideOkHttpClient() {
  return new OkHttpClient.Builder()
      .readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
      .connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
      .addNetworkInterceptor(new StethoInterceptor())
      .build();
}
 
Example 2
Project: microprofile-rest-client   File: HasSingletonScopeTest.java   Source Code and License 5 votes vote down vote up
@Deployment
public static WebArchive createDeployment() {
    String url = SimpleGetApi.class.getName() + "/mp-rest/url=http://localhost:8080";
    String scope = SimpleGetApi.class.getName() + "/mp-rest/scope=" + Singleton.class.getName();
    JavaArchive jar = ShrinkWrap.create(JavaArchive.class)
        .addClasses(SimpleGetApi.class, MySingletonApi.class)
        .addAsManifestResource(new StringAsset(url + "\n" + scope), "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    return ShrinkWrap.create(WebArchive.class)
        .addAsLibrary(jar)
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
 
Example 3
Project: LeagueOfAndroid   File: ClientModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
public Cache provideCache(@Named("cacheDir") File cacheDir, @Named("cacheSize") long cacheSize) {

    Cache cache = null;

    try {
        cache = new Cache(new File(cacheDir.getPath(), "http-cache"), cacheSize);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return cache;
}
 
Example 4
Project: Aurora   File: ClientModule.java   Source Code and License 5 votes vote down vote up
/**
 * 提供处理 RxJava 错误的管理器
 *
 * @return
 */
@Singleton
@Provides
RxErrorHandler proRxErrorHandler(Application application, ResponseErrorListener listener) {
    return RxErrorHandler
            .builder()
            .with(application)
            .responseErrorListener(listener)
            .build();
}
 
Example 5
Project: GitHub   File: ClientModule.java   Source Code and License 5 votes vote down vote up
/**
 * 需要单独给RxCache提供缓存路径
 * 提供RxCache缓存地址
 */
@Singleton
@Provides
@Named("RxCacheDirectory")
File provideRxCacheDirectory(File cacheDir) {
    File cacheDirectory = new File(cacheDir, "RxCache");
    return DataHelper.makeDirs(cacheDirectory);
}
 
Example 6
Project: yabaking   File: NetworkingModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
public Converter.Factory providesGsonConverterFactory() {
    Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(AutoValuesGsonAdapterFactory.create())
            .create();
    return GsonConverterFactory.create(gson);
}
 
Example 7
Project: curiostack   File: DatabaseModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
static DataSource dataSource(DatabaseConfig config) {
  HikariConfig hikari = new HikariConfig();
  hikari.setJdbcUrl(config.getJdbcUrl());
  hikari.setUsername(config.getUsername());
  hikari.setPassword(config.getPassword());
  hikari.addDataSourceProperty("cachePrepStmts", "true");
  hikari.addDataSourceProperty(
      "statementInterceptors", "brave.mysql.TracingStatementInterceptor");
  hikari.addDataSourceProperty("useUnicode", "yes");
  hikari.setMetricsTrackerFactory(new PrometheusMetricsTrackerFactory());
  return new HikariDataSource(hikari);
}
 
Example 8
Project: Nird2   File: PluginModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
Poller providePoller(@IoExecutor Executor ioExecutor,
		@Scheduler ScheduledExecutorService scheduler,
		ConnectionManager connectionManager,
		ConnectionRegistry connectionRegistry, PluginManager pluginManager,
		SecureRandom random, Clock clock, EventBus eventBus) {
	Poller poller = new Poller(ioExecutor, scheduler, connectionManager,
			connectionRegistry, pluginManager, random, clock);
	eventBus.addListener(poller);
	return poller;
}
 
Example 9
Project: Markwon   File: AppModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
OkHttpClient client() {
    return new OkHttpClient.Builder()
            .cache(new Cache(app.getCacheDir(), 1024L * 20))
            .followRedirects(true)
            .retryOnConnectionFailure(true)
            .build();
}
 
Example 10
Project: GitHub   File: AppModule.java   Source Code and License 5 votes vote down vote up
@Singleton
@Provides
ServerAPI provideServerAPI() {
    return new RestAdapter.Builder()
        .setEndpoint(ServerAPI.ENDPOINT)
        .setLogLevel(RestAdapter.LogLevel.FULL)
        .setLog(new RestAdapter.Log() {
            @Override
            public void log(String message) {
                v("Retrofit", message);
            }
        })
        .build().create(ServerAPI.class);
}
 
Example 11
Project: queries   File: QueriesGuiceSupport.java   Source Code and License 5 votes vote down vote up
public static <T> Module proxyModule(Class<T> proxyInterface) {

		return new AbstractModule() {
			@Override
			protected void configure() {
				Provider<Queries> provider = getProvider(Queries.class);

				Multibinder<QueriesSource> sourcesBinder = Multibinder.newSetBinder(binder(), QueriesSource.class);
				sourcesBinder.addBinding().toInstance(QueriesSource.ofClass(proxyInterface));

				bind(proxyInterface).toProvider(new ProxyInterfaceProvider<T>(provider, proxyInterface))
						.in(Singleton.class);
			}
		};
	}
 
Example 12
Project: YandexTranslator   File: ModelModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .connectTimeout(Config.CONNECT_TIMEOUT, SECONDS)
            .writeTimeout(Config.WRITE_TIMEOUT, SECONDS)
            .readTimeout(Config.READ_TIMEOUT, SECONDS);
    if (BuildConfig.DEBUG) {
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    }
    return builder.build();
}
 
Example 13
Project: beadledom   File: FauxModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
ObjectMapper provideObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();

  objectMapper.setPropertyNamingStrategy(
      PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
  objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

  return objectMapper;
}
 
Example 14
Project: MVPArmsTest1   File: ClientModule.java   Source Code and License 5 votes vote down vote up
/**
 * 提供处理Rxjava错误的管理器
 *
 * @return
 */
@Singleton
@Provides
RxErrorHandler proRxErrorHandler(Application application, ResponseErroListener listener) {
    return RxErrorHandler
            .builder()
            .with(application)
            .responseErroListener(listener)
            .build();
}
 
Example 15
Project: Nird2   File: SharingModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
BlogSharingValidator provideBlogSharingValidator(
		ValidationManager validationManager, MessageEncoder messageEncoder,
		ClientHelper clientHelper, MetadataEncoder metadataEncoder,
		Clock clock, BlogFactory blogFactory, AuthorFactory authorFactory) {
	BlogSharingValidator validator =
			new BlogSharingValidator(messageEncoder, clientHelper,
					metadataEncoder, clock, blogFactory, authorFactory);
	validationManager.registerMessageValidator(BlogSharingManager.CLIENT_ID,
			validator);
	return validator;
}
 
Example 16
Project: Nird2   File: SyncModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
ValidationManager provideValidationManager(
		LifecycleManager lifecycleManager, EventBus eventBus,
		ValidationManagerImpl validationManager) {
	lifecycleManager.registerService(validationManager);
	eventBus.addListener(validationManager);
	return validationManager;
}
 
Example 17
Project: starwarsshop   File: ChartModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
@SuppressWarnings("unused")
public ChartInteractor providesChartInteractor(
        ProductService productService) {
    return new ChartInteractorImpl(productService);
}
 
Example 18
Project: Subs   File: ApplicationModule.java   Source Code and License 5 votes vote down vote up
@Provides @Singleton GoogleApiClient provideGoogleApiClient() {
    GoogleSignInOptions gso =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(
                    provideApplicationContext().getString(R.string.default_web_client_id))
                    .requestEmail()
                    .build();
    return new GoogleApiClient.Builder(provideApplicationContext()).addApi(
            Auth.GOOGLE_SIGN_IN_API, gso).build();
}
 
Example 19
Project: abhot   File: OAuthModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configureServlets()
{
	bind(ConsumerTokenStore.class).toInstance(m_tokenStore);

	bind(OAuthFilter.class).in(Singleton.class);
	filter("/api/*").through(OAuthFilter.class);
}
 
Example 20
Project: Nird2   File: LifecycleModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
@IoExecutor
Executor provideIoExecutor(LifecycleManager lifecycleManager) {
	lifecycleManager.registerForShutdown(ioExecutor);
	return ioExecutor;
}
 
Example 21
Project: trust-wallet-android   File: RepositoriesModule.java   Source Code and License 5 votes vote down vote up
@Singleton
@Provides
BlockExplorerClientType provideBlockExplorerClient(
		OkHttpClient httpClient,
		Gson gson,
		EthereumNetworkRepositoryType ethereumNetworkRepository) {
	return new BlockExplorerClient(httpClient, gson, ethereumNetworkRepository);
}
 
Example 22
Project: ProjectAres   File: TestModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configure() {
    bind(Loggers.class).to(SimpleLoggerFactory.class);
    bind(Configuration.class).to(YamlConfiguration.class);
    bind(ExceptionHandler.class).to(LoggingExceptionHandler.class).in(Singleton.class);


}
 
Example 23
Project: verify-matching-service-adapter   File: MatchingServiceAdapterModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
@Named("VerifyFixedCertificateChainValidator")
public FixedCertificateChainValidator getFixedChainCertificateValidator(
    @Named("VerifyTrustStore") KeyStore keyStore,
    CertificateChainValidator certificateChainValidator) {
    return new FixedCertificateChainValidator(keyStore, certificateChainValidator);
}
 
Example 24
Project: DuckDuckDefine-Android   File: NetworkModule.java   Source Code and License 5 votes vote down vote up
/**
 * Provide an instance of OkHttpClient for use with API interfaces/libraries
 *
 * @return Initialised instance of OkHttpClient
 */
@Provides @Singleton
OkHttpClient provideOkHttpClient() {
    // Enable/Disable HTTP log statements
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(BuildConfig.DEBUG ?
            HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

    return new OkHttpClient().newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .addNetworkInterceptor(httpLoggingInterceptor)
            .build();
}
 
Example 25
Project: OAuth2Android   File: APIModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
Retrofit provideRetrofit(@Named("serverUrl") String serverUrl, OkHttpClient okHttpClient) {
    return new Retrofit.Builder()
            .addConverterFactory(JacksonConverterFactory.create())
            .baseUrl(serverUrl)
            .client(okHttpClient)
            .build();
}
 
Example 26
Project: verify-matching-service-adapter   File: MatchingServiceAdapterModule.java   Source Code and License 5 votes vote down vote up
@Override
protected void configure() {

    bind(PKIXParametersProvider.class).toInstance(new PKIXParametersProvider());
    bind(SoapMessageManager.class).toInstance(new SoapMessageManager());
    bind(X509CertificateFactory.class);
    bind(KeyStoreLoader.class);
    bind(IdGenerator.class);
    bind(IdaKeyStoreCredentialRetriever.class);
    bind(ExpiredCertificateMetadataFilter.class);
    bind(ExceptionResponseFactory.class);
    bind(InboundMatchingServiceRequestToMatchingServiceRequestDtoMapper.class);
    bind(MatchingServiceResponseDtoToOutboundResponseFromMatchingServiceMapper.class);
    bind(MatchingServiceAdapterMetadataRepository.class);
    bind(DocumentToInboundMatchingServiceRequestMapper.class);
    bind(IdGenerator.class);
    bind(MatchingServiceAssertionFactory.class);
    bind(UserAccountCreationAttributeExtractor.class);
    bind(UnknownUserAttributeQueryHandler.class);

    bind(SigningKeyStore.class).to(MetadataPublicKeyStore.class).in(Singleton.class);
    bind(EncryptionKeyStore.class).to(MetadataPublicKeyStore.class).in(Singleton.class);
    bind(PublicKeyInputStreamFactory.class).to(PublicKeyFileInputStreamFactory.class).in(Singleton.class);
    bind(AssertionLifetimeConfiguration.class).to(MatchingServiceAdapterConfiguration.class).in(Singleton.class);
    bind(MatchingServiceProxy.class).to(MatchingServiceProxyImpl.class).in(Singleton.class);
    bind(ManifestReader.class).toInstance(new ManifestReader());
    bind(MatchingDatasetToMatchingDatasetDtoMapper.class).toInstance(new MatchingDatasetToMatchingDatasetDtoMapper());
}
 
Example 27
Project: GitHub   File: ClientModule.java   Source Code and License 5 votes vote down vote up
/**
 * @param builder
 * @param client
 * @param httpUrl
 * @return
 * @author: jess
 * @date 8/30/16 1:15 PM
 * @description:提供retrofit
 */
@Singleton
@Provides
Retrofit provideRetrofit(Retrofit.Builder builder, OkHttpClient client, HttpUrl httpUrl) {
    return builder
            .baseUrl(httpUrl)//域名
            .client(client)//设置okhttp
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//使用rxjava
            .addConverterFactory(GsonConverterFactory.create())//使用Gson
            .build();
}
 
Example 28
Project: androidadvanced   File: LibsModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
Fragment providesFragment(){
    return this.fragment;
}
 
Example 29
Project: Nird2   File: AppModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
Application providesApplication() {
	return application;
}
 
Example 30
Project: aDictOnCopy   File: SystemModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
DictionaryOnCopyService.IntentLauncher provideIntentLauncher() {
    return INTENT_LAUNCHER;
}
 
Example 31
Project: Paprika   File: NetworkModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
@NetworkInterceptor
Interceptor provideNetworkInterceptor() {
    return new Interceptor() {
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            String cacheControl = originalResponse.header("Cache-Control");
            if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
                    cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=" + 86400)// cache and reuse for 1 day(86400 seconds)
                        .build();
            } else {
                return originalResponse;
            }
        }
    };
}
 
Example 32
Project: MVPArms_Fragment-fragment   File: GlobalConfigModule.java   Source Code and License 4 votes vote down vote up
/**
 * 提供缓存文件
 */
@Singleton
@Provides
File provideCacheFile(Application application) {
    return mCacheFile == null ? DataHelper.getCacheFile(application) : mCacheFile;
}
 
Example 33
Project: GitHub   File: ServiceModule.java   Source Code and License 4 votes vote down vote up
@Singleton
@Provides
CommonService provideCommonService(Retrofit retrofit) {
    return retrofit.create(CommonService.class);
}
 
Example 34
Project: egma-shapi   File: ShapeIdentificationModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
ShapeIdentifier provideShapeIdentifier(EventTracker eventTracker) {
    return new ShapeIdentifier(eventTracker);
}
 
Example 35
Project: cleanarchitecture-unidirectional   File: ThreadModule.java   Source Code and License 4 votes vote down vote up
@Named(NAMED_DELIVERY)
@Singleton
@Provides
Scheduler provideDelivery() {
    return AndroidSchedulers.mainThread();
}
 
Example 36
Project: NeiHanDuanZiTV   File: GlobalConfigModule.java   Source Code and License 4 votes vote down vote up
@Singleton
@Provides
@Nullable
ClientModule.RxCacheConfiguration provideRxCacheConfiguration() {
    return mRxCacheConfiguration;
}
 
Example 37
Project: MVPArms_Fragment-fragment   File: GlobalConfigModule.java   Source Code and License 4 votes vote down vote up
@Singleton
@Provides
HttpUrl provideBaseUrl() {
    if (mBaseUrl != null) {
        HttpUrl httpUrl = mBaseUrl.url();
        if (httpUrl != null) {
            return httpUrl;
        }
    }
    return mApiUrl == null ? HttpUrl.parse("https://api.github.com/") : mApiUrl;
}
 
Example 38
Project: navigator   File: SchedulerModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Named("LOOPER_SCHEDULER")
@Singleton
SchedulerHolder looperScheduler(SchedulerHolder schedulerHolder) {
    return schedulerHolder;
}
 
Example 39
Project: CrazyDaily   File: AppModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
NeihanRepository provideNeihanRepository(NeihanDataRepository neihanRepository) {
    return neihanRepository;
}
 
Example 40
Project: SimpleCalculator   File: ApplicationModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
Context provideApplicationContext() {
    return application.getApplicationContext();
}