@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; } } }; }
@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; }
@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(); }
@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"); }
@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; }
/** * 提供处理 RxJava 错误的管理器 * * @return */ @Singleton @Provides RxErrorHandler proRxErrorHandler(Application application, ResponseErrorListener listener) { return RxErrorHandler .builder() .with(application) .responseErrorListener(listener) .build(); }
/** * 需要单独给RxCache提供缓存路径 * 提供RxCache缓存地址 */ @Singleton @Provides @Named("RxCacheDirectory") File provideRxCacheDirectory(File cacheDir) { File cacheDirectory = new File(cacheDir, "RxCache"); return DataHelper.makeDirs(cacheDirectory); }
@Provides @Singleton public Converter.Factory providesGsonConverterFactory() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(AutoValuesGsonAdapterFactory.create()) .create(); return GsonConverterFactory.create(gson); }
@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); }
@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; }
@Provides @Singleton OkHttpClient client() { return new OkHttpClient.Builder() .cache(new Cache(app.getCacheDir(), 1024L * 20)) .followRedirects(true) .retryOnConnectionFailure(true) .build(); }
@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); }
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); } }; }
@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(); }
@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; }
/** * 提供处理Rxjava错误的管理器 * * @return */ @Singleton @Provides RxErrorHandler proRxErrorHandler(Application application, ResponseErroListener listener) { return RxErrorHandler .builder() .with(application) .responseErroListener(listener) .build(); }
@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; }
@Provides @Singleton ValidationManager provideValidationManager( LifecycleManager lifecycleManager, EventBus eventBus, ValidationManagerImpl validationManager) { lifecycleManager.registerService(validationManager); eventBus.addListener(validationManager); return validationManager; }
@Provides @Singleton @SuppressWarnings("unused") public ChartInteractor providesChartInteractor( ProductService productService) { return new ChartInteractorImpl(productService); }
@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(); }
@Override protected void configureServlets() { bind(ConsumerTokenStore.class).toInstance(m_tokenStore); bind(OAuthFilter.class).in(Singleton.class); filter("/api/*").through(OAuthFilter.class); }
@Provides @Singleton @IoExecutor Executor provideIoExecutor(LifecycleManager lifecycleManager) { lifecycleManager.registerForShutdown(ioExecutor); return ioExecutor; }
@Singleton @Provides BlockExplorerClientType provideBlockExplorerClient( OkHttpClient httpClient, Gson gson, EthereumNetworkRepositoryType ethereumNetworkRepository) { return new BlockExplorerClient(httpClient, gson, ethereumNetworkRepository); }
@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); }
@Provides @Singleton @Named("VerifyFixedCertificateChainValidator") public FixedCertificateChainValidator getFixedChainCertificateValidator( @Named("VerifyTrustStore") KeyStore keyStore, CertificateChainValidator certificateChainValidator) { return new FixedCertificateChainValidator(keyStore, certificateChainValidator); }
/** * 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(); }
@Provides @Singleton Retrofit provideRetrofit(@Named("serverUrl") String serverUrl, OkHttpClient okHttpClient) { return new Retrofit.Builder() .addConverterFactory(JacksonConverterFactory.create()) .baseUrl(serverUrl) .client(okHttpClient) .build(); }
@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()); }
/** * @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(); }
@Provides @Singleton Fragment providesFragment(){ return this.fragment; }
@Provides @Singleton Application providesApplication() { return application; }
@Provides @Singleton DictionaryOnCopyService.IntentLauncher provideIntentLauncher() { return INTENT_LAUNCHER; }
/** * 提供缓存文件 */ @Singleton @Provides File provideCacheFile(Application application) { return mCacheFile == null ? DataHelper.getCacheFile(application) : mCacheFile; }
@Singleton @Provides CommonService provideCommonService(Retrofit retrofit) { return retrofit.create(CommonService.class); }
@Provides @Singleton ShapeIdentifier provideShapeIdentifier(EventTracker eventTracker) { return new ShapeIdentifier(eventTracker); }
@Named(NAMED_DELIVERY) @Singleton @Provides Scheduler provideDelivery() { return AndroidSchedulers.mainThread(); }
@Singleton @Provides @Nullable ClientModule.RxCacheConfiguration provideRxCacheConfiguration() { return mRxCacheConfiguration; }
@Provides @Named("LOOPER_SCHEDULER") @Singleton SchedulerHolder looperScheduler(SchedulerHolder schedulerHolder) { return schedulerHolder; }
@Provides @Singleton NeihanRepository provideNeihanRepository(NeihanDataRepository neihanRepository) { return neihanRepository; }
@Provides @Singleton Context provideApplicationContext() { return application.getApplicationContext(); }