feign.okhttp.OkHttpClient Java Examples

The following examples show how to use feign.okhttp.OkHttpClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TwitchHelixBuilder.java    From twitch4j with MIT License 8 votes vote down vote up
/**
 * Twitch API Client (Helix)
 *
 * @return TwitchHelix
 */
public TwitchHelix build() {
    log.debug("Helix: Initializing Module ...");

    // Hystrix
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", timeout);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestCache.enabled", false);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.maxQueueSize", getRequestQueueSize());
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.queueSizeRejectionThreshold", getRequestQueueSize());

    // Jackson ObjectMapper
    ObjectMapper mapper = new ObjectMapper();
    // - Modules
    mapper.findAndRegisterModules();

    // Feign
    TwitchHelix client = HystrixFeign.builder()
        .client(new OkHttpClient())
        .encoder(new JacksonEncoder(mapper))
        .decoder(new JacksonDecoder(mapper))
        .logger(new Logger.ErrorLogger())
        .errorDecoder(new TwitchHelixErrorDecoder(new JacksonDecoder()))
        .requestInterceptor(new TwitchHelixClientIdInterceptor(this))
        .options(new Request.Options(timeout / 3, TimeUnit.MILLISECONDS, timeout, TimeUnit.MILLISECONDS, true))
        .retryer(new Retryer.Default(500, timeout, 2))
        .target(TwitchHelix.class, baseUrl);

    return client;
}
 
Example #2
Source File: TwitchMessagingInterfaceBuilder.java    From twitch4j with MIT License 7 votes vote down vote up
/**
 * Twitch API Client (Helix)
 *
 * @return TwitchHelix
 */
public TwitchMessagingInterface build() {
    log.debug("TMI: Initializing Module ...");

    // Hystrix
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", timeout);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestCache.enabled", false);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.maxQueueSize", getRequestQueueSize());
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.queueSizeRejectionThreshold", getRequestQueueSize());

    // Build
    TwitchMessagingInterface client = HystrixFeign.builder()
        .client(new OkHttpClient())
        .encoder(new JacksonEncoder())
        .decoder(new JacksonDecoder())
        .logger(new Logger.ErrorLogger())
        .errorDecoder(new TwitchMessagingInterfaceErrorDecoder(new JacksonDecoder()))
        .logLevel(Logger.Level.BASIC)
        .requestInterceptor(new TwitchClientIdInterceptor(this.clientId, this.userAgent))
        .retryer(new Retryer.Default(1, 10000, 3))
        .options(new Request.Options(5000, TimeUnit.MILLISECONDS, 15000, TimeUnit.MILLISECONDS, true))
        .target(TwitchMessagingInterface.class, baseUrl);

    return client;
}
 
Example #3
Source File: TwitchKrakenBuilder.java    From twitch4j with MIT License 7 votes vote down vote up
/**
 * Twitch API Client (Kraken)
 *
 * @return TwitchKraken
 */
public TwitchKraken build() {
    log.debug("Kraken: Initializing Module ...");

    // Hystrix
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", timeout);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestCache.enabled", false);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.maxQueueSize", getRequestQueueSize());
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.queueSizeRejectionThreshold", getRequestQueueSize());

    // Build
    TwitchKraken client = HystrixFeign.builder()
        .client(new OkHttpClient())
        .encoder(new JacksonEncoder())
        .decoder(new JacksonDecoder())
        .logger(new Logger.ErrorLogger())
        .errorDecoder(new TwitchKrakenErrorDecoder(new JacksonDecoder()))
        .requestInterceptor(new TwitchClientIdInterceptor(this.clientId, this.userAgent))
        .options(new Request.Options(timeout / 3, TimeUnit.MILLISECONDS, timeout, TimeUnit.MILLISECONDS, true))
        .retryer(new Retryer.Default(500, timeout, 2))
        .target(TwitchKraken.class, baseUrl);

    return client;
}
 
Example #4
Source File: OkHttpClientAutoConfiguration.java    From feign-okhttp-spring-cloud-starter with Apache License 2.0 6 votes vote down vote up
@Bean
public Client feignClient() {
    RibbonClient.Builder builder = RibbonClient.builder();

    if (httpClient != null) {
        builder.delegate(new OkHttpClient(httpClient));
    } else {
        builder.delegate(new OkHttpClient());
    }

    if (lbClientFactory != null) {
        builder.lbClientFactory(lbClientFactory);
    }

    return builder.build();
}
 
Example #5
Source File: StoreClient.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public StoreClient(RequestInterceptor requestInterceptor) {

        Feign.Builder builder = Feign.builder().client(new OkHttpClient(
                org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new
                Slf4jLogger())
                .logLevel(Logger.Level.FULL)
                .requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder());
        String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getStoreEndpoint());

        apis = builder.target(APICollectionApi.class, basePath);
        individualApi = builder.target(APIIndividualApi.class, basePath);
        applications = builder.target(ApplicationCollectionApi.class, basePath);
        individualApplication = builder.target(ApplicationIndividualApi.class, basePath);
        subscriptions = builder.target(SubscriptionCollectionApi.class, basePath);
        individualSubscription = builder.target(SubscriptionIndividualApi.class, basePath);
        subscriptionMultitpleApi = builder.target(SubscriptionMultitpleApi.class, basePath);
        tags = builder.target(TagCollectionApi.class, basePath);
        individualTier = builder.target(ThrottlingTierIndividualApi.class, basePath);
        tiers = builder.retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(1L), 1))
                .options(new Request.Options(10000, 5000))
                .target(ThrottlingTierCollectionApi.class, basePath);

    }
 
Example #6
Source File: PublisherClient.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * PublisherClient constructor - Initialize a PublisherClient instance
 *
 */
public PublisherClient(RequestInterceptor requestInterceptor) {
    Feign.Builder builder = Feign.builder().client(new OkHttpClient(
            org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new
            Slf4jLogger())
            .logLevel(Logger.Level.FULL)
            .requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder());
    String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getPublisherEndpoint());

    api = builder.target(APIIndividualApi.class, basePath);
    apis = builder.target(APICollectionApi.class, basePath);
    document = builder.target(DocumentIndividualApi.class, basePath);
    application = builder.target(ApplicationIndividualApi.class, basePath);
    environments = builder.target(EnvironmentCollectionApi.class, basePath);
    subscriptions = builder.target(SubscriptionCollectionApi.class, basePath);
    tiers = builder.target(ThrottlingTierCollectionApi.class, basePath);
}
 
Example #7
Source File: WeedManager.java    From weed-client with MIT License 5 votes vote down vote up
/**
 * Fetch volume server.
 *
 * @param volumeId   Volume id.
 * @param collection Collection.
 * @return ids.
 */
private Set<String> fetchVolume(int volumeId, String collection) {
    Locations locations = getMasterClient().lookup(volumeId, collection);
    Set<String> ids = new HashSet<>();
    locations.getLocations().forEach(location -> {
        final String id = String.format("%s#%s", location.getUrl(), location.getUrl());
        ids.add(id);
        volumeClients.putIfAbsent(id, Feign.builder()
                .client(new OkHttpClient())
                .decoder(new JacksonDecoder())
                .target(WeedVolumeClient.class, String.format("http://%s", location.getPublicUrl())));
    });
    return ids;
}
 
Example #8
Source File: BookControllerFeignClientBuilder.java    From tutorials with MIT License 5 votes vote down vote up
private static <T> T createClient(Class<T> type, String uri) {
    return Feign.builder()
        .client(new OkHttpClient())
        .encoder(new GsonEncoder())
        .decoder(new GsonDecoder())
        .logger(new Slf4jLogger(type))
        .logLevel(Logger.Level.FULL)
        .target(type, uri);
}
 
Example #9
Source File: GameClientResolver.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private GameServerClient buildGameServerClient(String server) {
    return Feign.builder()
            .client(new OkHttpClient())
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .errorDecoder(new ClientErrorDecoder())
            .logger(new Slf4jLogger(GameServerClient.class))
            .logLevel(Level.BASIC)
            .requestInterceptor(new BasicAuthRequestInterceptor(gameProperties.getBasicAuthUser(),
                    Hash.md5(gameProperties.getBasicAuthPassword())))
            .target(GameServerClient.class, gameProperties.getSchema() + "://" + server);
}
 
Example #10
Source File: OkHttpFeignClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
		throws BeansException {
	if (bean instanceof OkHttpClient && !(bean instanceof LazyClient)) {
		return new LazyClient(this.beanFactory, (Client) bean);
	}
	return bean;
}
 
Example #11
Source File: OAuthRequestInterceptor.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an interceptor that authenticates all requests.
 */
public OAuthRequestInterceptor() {
    String username = APIMConfigReader.getInstance().getConfig().getUsername();
    String password = APIMConfigReader.getInstance().getConfig().getPassword();
    dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger())
            .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username,
                    password))
            .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
            .target(DCRClient.class, Utils.replaceProperties(
                    APIMConfigReader.getInstance().getConfig().getDcrEndpoint()));
}
 
Example #12
Source File: WeedManager.java    From weed-client with MIT License 5 votes vote down vote up
/**
 * Fetch master cluster information.
 *
 * @param cluster Master cluster information.
 */
private void fetchMasters(Cluster cluster) {
    if (!leaderMasterUrl.equals(cluster.getLeader())) {
        leaderMasterUrl = cluster.getLeader();
        log.info("Weed leader master server is change to [{}]", leaderMasterUrl);
        leaderMaster = Feign.builder()
                .client(new OkHttpClient())
                .decoder(new JacksonDecoder())
                .target(WeedMasterClient.class, String.format("http://%s", leaderMaster));
    }

    // Cleanup peer master
    Set<String> removeSet = peerMasters.keySet().stream().filter(
            key -> !cluster.getPeers().contains(key) && !cluster.getLeader().equals(key))
            .collect(Collectors.toSet());

    peerMasters.remove(leaderMasterUrl);
    removeSet.forEach(key -> peerMasters.remove(key));

    cluster.getPeers().forEach(url -> {
        if (!peerMasters.containsKey(url)) {
            peerMasters.put(url,
                    Feign.builder()
                            .client(new OkHttpClient())
                            .decoder(new JacksonDecoder())
                            .target(WeedMasterClient.class, String.format("http://%s", url)));
        }
    });
}
 
Example #13
Source File: WeedManager.java    From weed-client with MIT License 5 votes vote down vote up
/**
 * Startup weed manager.
 */
public void start() {
    leaderMasterUrl = assembleUrl(host, port);
    leaderMaster = Feign.builder()
            .client(new OkHttpClient())
            .decoder(new JacksonDecoder())
            .target(WeedMasterClient.class, String.format("http://%s", leaderMasterUrl));

    fetchMasters(leaderMaster.cluster());

    masterHealthCheckThread.start();
    volumeHealthCheckThread.start();
}
 
Example #14
Source File: FeignTracingTest.java    From feign-opentracing with Apache License 2.0 5 votes vote down vote up
protected Feign getClient() {
    return Feign.builder()
            .client(new TracingClient(new OkHttpClient(), mockTracer,
                    Collections.<FeignSpanDecorator>singletonList(new FeignSpanDecorator.StandardTags())))
            .retryer(new Retryer.Default(100, SECONDS.toMillis(1), NUMBER_OF_RETRIES))
            .build();
}
 
Example #15
Source File: FeignLoadBalancerAutoConfigurationTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInstantiateOkHttpFeignClientWhenEnabled() {
	ConfigurableApplicationContext context = initContext(
			"feign.httpclient.enabled=false", "feign.okhttp.enabled=true");
	assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
	assertLoadBalanced(context, OkHttpClient.class);
}
 
Example #16
Source File: FeignAutoConfiguration.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
		ConnectionPool connectionPool,
		FeignHttpClientProperties httpClientProperties) {
	Boolean followRedirects = httpClientProperties.isFollowRedirects();
	Integer connectTimeout = httpClientProperties.getConnectionTimeout();
	Boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
	this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
			.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
			.followRedirects(followRedirects).connectionPool(connectionPool)
			.build();
	return this.okHttpClient;
}
 
Example #17
Source File: OkHttpFeignLoadBalancerConfiguration.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public Client feignClient(okhttp3.OkHttpClient okHttpClient,
		LoadBalancerClient loadBalancerClient) {
	OkHttpClient delegate = new OkHttpClient(okHttpClient);
	return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
}
 
Example #18
Source File: FrostmourneSpiAutoConfiguration.java    From frostmourne with MIT License 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public OkHttpClient okHttpClient() {
    return new OkHttpClient();
}
 
Example #19
Source File: FeignTest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
private static Feign getExplicitClientWithBuilderConstructor() {
  return new Feign.Builder().client(new OkHttpClient()).retryer(new Retryer.Default(100, TimeUnit.SECONDS.toMillis(1), 2)).build();
}
 
Example #20
Source File: FeignAutoConfiguration.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean(Client.class)
public Client feignClient(okhttp3.OkHttpClient client) {
	return new OkHttpClient(client);
}
 
Example #21
Source File: Issue393Tests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Bean
public OkHttpClient myOkHttpClient() {
	return new OkHttpClient();
}
 
Example #22
Source File: AMDefaultKeyManagerImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Override
public void loadConfiguration(KeyManagerConfiguration configuration) throws APIManagementException {

    this.configuration = configuration;

    String consumerKey = (String) configuration.getParameter(APIConstants.KEY_MANAGER_CONSUMER_KEY);
    String consumerSecret = (String) configuration.getParameter(APIConstants.KEY_MANAGER_CONSUMER_SECRET);
    String keyManagerServiceUrl = (String) configuration.getParameter(APIConstants.AUTHSERVER_URL);

    String dcrEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT) != null) {
        dcrEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT);
    } else {
        dcrEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
                .concat(getTenantAwareContext().trim()).concat("/api/identity/oauth2/dcr/v1.1/register");
    }
    String tokenEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT) != null) {
        tokenEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT);
    } else {
        tokenEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
                "/oauth2/token");
    }
    addKeyManagerConfigsAsSystemProperties(tokenEndpoint);
    String revokeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT) != null) {
        revokeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT);
    } else {
        revokeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
                "/oauth2/revoke");
    }
    String scopeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT) != null) {
        scopeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT);
    } else {
        scopeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
                .concat(getTenantAwareContext().trim())
                .concat(APIConstants.KEY_MANAGER_OAUTH2_SCOPES_REST_API_BASE_PATH);
    }
    String introspectionEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT) != null) {
        introspectionEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT);
    } else {
        introspectionEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
                .concat(getTenantAwareContext().trim()).concat("/oauth2/introspect");
    }
    accessTokenGenerator = new AccessTokenGenerator(tokenEndpoint, revokeEndpoint, consumerKey, consumerSecret);

    dcrClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .requestInterceptor(new BearerInterceptor(accessTokenGenerator))
            .errorDecoder(new KMClientErrorDecoder())
            .target(DCRClient.class, dcrEndpoint);
    authClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .errorDecoder(new KMClientErrorDecoder())
            .encoder(new FormEncoder())
            .target(AuthClient.class, tokenEndpoint);

    introspectionClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .requestInterceptor(new BearerInterceptor(accessTokenGenerator))
            .errorDecoder(new KMClientErrorDecoder())
            .encoder(new FormEncoder())
            .target(IntrospectionClient.class, introspectionEndpoint);
    scopeClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .requestInterceptor(new BearerInterceptor(accessTokenGenerator))
            .errorDecoder(new KMClientErrorDecoder())
            .target(ScopeClient.class, scopeEndpoint);
}
 
Example #23
Source File: ClientConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public OkHttpClient client() {
    return new OkHttpClient();
}
 
Example #24
Source File: FeignApiConfig.java    From frostmourne with MIT License 4 votes vote down vote up
@Bean
public OkHttpClient okHttpClient() {
    return new OkHttpClient();
}