Java Code Examples for feign.jackson.JacksonDecoder

The following examples show how to use feign.jackson.JacksonDecoder. These examples are extracted from open source projects. 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 Project: twitch4j   Source File: TwitchHelixBuilder.java    License: 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 Project: twitch4j   Source File: TwitchMessagingInterfaceBuilder.java    License: 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 Project: twitch4j   Source File: TwitchKrakenBuilder.java    License: 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 Project: hawkular-apm   Source File: AlertsPublisher.java    License: Apache License 2.0 7 votes vote down vote up
@Asynchronous
public void publish(final Event event) {
    if (BASE_URL == null || BASE_URL.isEmpty()) {
        logger.hawkularServerNotConfigured();
        return;
    }

    if (USERNAME == null || USERNAME.isEmpty()) {
        logger.hawkularServerUsernameNotConfigured();
        return;
    }

    if (PASSWORD == null || PASSWORD.isEmpty()) {
        logger.hawkularServerPasswordNotConfigured();
        return;
    }

    HystrixFeign.builder()
            .requestInterceptor(new BasicAuthRequestInterceptor(USERNAME, PASSWORD))
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .retryer(new Retryer.Default())
            .target(AlertsService.class, TARGET)
            .addEvent(event);
}
 
Example 5
Source Project: frostmourne   Source File: FrostmourneSpiAutoConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public IFrostmourneSpiApi frostmourneSpiApi() {

    if(frostmourneSpiProperties.getMock()) {
        return new MockFrostmourneSpi();
    }

    return Feign.builder().options(defaultOptions())
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .retryer(feignRetryer())
            .client(okHttpClient)
            .logLevel(feignLoggerLevel())
            .target(IFrostmourneSpiApi.class, frostmourneSpiProperties.getServiceAddr());
}
 
Example 6
Source Project: feign-vertx   Source File: VertxHttpOptionsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test the Feign Request Options version of the Vert.x Feign Client.
 * This proves regression is not broken for existing use-cases.
 * @param context Test Context
 */
@Test
public void testRequestOptions(TestContext context) {
  IcecreamServiceApi client = VertxFeign
          .builder()
          .vertx(vertx)
          .options(new Request.Options(5000,5000) ) // Plain old Feign Request.Options (regression)
          .decoder(new JacksonDecoder(TestUtils.MAPPER))
          .logger(new Slf4jLogger())
          .logLevel(Logger.Level.FULL)
          .target(IcecreamServiceApi.class, "http://localhost:8089");

  stubFor(get(urlEqualTo("/icecream/flavors"))
          .withHeader("Accept", equalTo("application/json"))
          .withHeader("Accept-Encoding", absent()) // Test that Accept-Encoding is missing (since we're using Request.Options)
          .willReturn(aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody(flavorsStr)));

  testClient(client, context);
}
 
Example 7
Source Project: feign-vertx   Source File: VertxHttp2ClientReconnectTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a Feign Vertx client that is built once and used several times
 * during positive and negative test cases.
 * @param context
 */
@Before
public void before(TestContext context) {
  // for HTTP2 test, set up the protocol and the pool size to 1.
  HttpClientOptions options = new HttpClientOptions();
  options
      .setProtocolVersion(HttpVersion.HTTP_2)
      .setHttp2MaxPoolSize(1);

  client = VertxFeign
      .builder()
      .vertx(this.vertx)
      .options(options)
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .target(HelloServiceAPI.class, "http://localhost:8091");
}
 
Example 8
Source Project: hola   Source File: TracingConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This is were the "magic" happens: it creates a Feign, which is a proxy interface for remote calling a REST endpoint with
 * Hystrix fallback support.
 *
 * @return The feign pointing to the service URL and with Hystrix fallback.
 */
@Produces
@Singleton
private AlohaService alohaService(Tracer tracer) {
    // bind current span to Hystrix thread
    TracingConcurrencyStrategy.register();

    return HystrixFeign.builder()
            // Use apache HttpClient which contains the ZipKin Interceptors
            .client(new TracingClient(new ApacheHttpClient(HttpClientBuilder.create().build()), tracer))

            // Bind Zipkin Server Span to Feign Thread
            .logger(new Logger.ErrorLogger()).logLevel(Logger.Level.BASIC)
            .decoder(new JacksonDecoder())
            .target(AlohaService.class,"http://aloha:8080/",
                    () -> Collections.singletonList("Aloha response (fallback)"));
}
 
Example 9
Source Project: jrestless-examples   Source File: BackendServiceFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public BackendServiceFactory(InjectionManager serviceLocator) {
	awsLambdaClient = new AWSLambdaClient();
	awsLambdaClient.configureRegion(BACKEND_SERVICE_REGION);
	backendService = Feign.builder()
			.client(FeignLambdaServiceInvokerClient.builder()
					.setRegion(BACKEND_SERVICE_REGION)
					.setFunctionName(BACKEND_SERVICE_FUNCTION_NAME)
					.build())
			.decoder(new JacksonDecoder())
			.encoder(new JacksonEncoder())
			.logger(new Slf4jLogger())
			.target(new LambdaServiceFunctionTarget<BackendService>(BackendService.class) {
				@Override
				public Request apply(RequestTemplate input) {
					// TODO inject the context directly => requires the context to be bound as proxy
					Context lambdaContext = serviceLocator.getInstance(Context.class);
					// propagate the AWS request ID => the called service can log the original AWS request ID
					input.header("X-Base-Aws-Request-Id", lambdaContext.getAwsRequestId());
					return super.apply(input);
				}
			});
}
 
Example 10
private AbstractSimulatedDevice createDdiDevice(final String id, final String tenant, final int pollDelaySec,
        final URL baseEndpoint, final String gatewayToken) {

    final ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(new Jackson2HalModule());

    final RootControllerResourceClient controllerResource = Feign.builder()
            .requestInterceptor(new GatewayTokenInterceptor(gatewayToken))
            .contract(new IgnoreMultipleConsumersProducersSpringMvcContract()).logLevel(Level.HEADERS)
            .decoder(new ResponseEntityDecoder(new JacksonDecoder(mapper))).encoder(new JacksonEncoder())
            .logger(new Slf4jLogger()).decode404()
            .target(RootControllerResourceClient.class, baseEndpoint.toString());

    return new DDISimulatedDevice(id, tenant, pollDelaySec, controllerResource, deviceUpdater, gatewayToken);
}
 
Example 11
Source Project: feign   Source File: DecoderIteratorsBenchmark.java    License: Apache License 2.0 6 votes vote down vote up
@Setup(Level.Trial)
public void buildDecoder() {
  switch (api) {
    case "list":
      decoder = new JacksonDecoder();
      type = new TypeReference<List<Car>>() {}.getType();
      break;
    case "iterator":
      decoder = JacksonIteratorDecoder.create();
      type = new TypeReference<Iterator<Car>>() {}.getType();
      break;
    case "stream":
      decoder = StreamDecoder.create(JacksonIteratorDecoder.create());
      type = new TypeReference<Stream<Car>>() {}.getType();
      break;
    default:
      throw new IllegalStateException("Unknown api: " + api);
  }
}
 
Example 12
Source Project: feign   Source File: ReactiveFeignIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRxJavaTarget() throws Exception {
  this.webServer.enqueue(new MockResponse().setBody("1.0"));
  this.webServer.enqueue(new MockResponse().setBody("{ \"username\": \"test\" }"));

  TestReactiveXService service = RxJavaFeign.builder()
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .logger(new ConsoleLogger())
      .logLevel(Level.FULL)
      .target(TestReactiveXService.class, this.getServerUrl());
  assertThat(service).isNotNull();

  StepVerifier.create(service.version())
      .expectNext("1.0")
      .expectComplete()
      .verify();
  assertThat(webServer.takeRequest().getPath()).isEqualToIgnoringCase("/version");

  /* test encoding and decoding */
  StepVerifier.create(service.user("test"))
      .assertNext(user -> assertThat(user).hasFieldOrPropertyWithValue("username", "test"))
      .expectComplete()
      .verify();
  assertThat(webServer.takeRequest().getPath()).isEqualToIgnoringCase("/users/test");
}
 
Example 13
Source Project: frostmourne   Source File: FeignApiConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public IXxlJob xxlJobApi(Retryer retryer, Request.Options defaultOptions) {
    if (mock) {
        return new MockXxlJob();
    }
    return Feign.builder().options(defaultOptions)
            .encoder(new FormEncoder(new JacksonEncoder()))
            .decoder(new JacksonDecoder())
            .retryer(retryer)
            .client(okHttpClient())
            .target(IXxlJob.class, xxlJobAdminHost);
}
 
Example 14
Source Project: openapi-generator   Source File: ApiClient.java    License: Apache License 2.0 5 votes vote down vote up
public ApiClient() {
  objectMapper = createObjectMapper();
  apiAuthorizations = new LinkedHashMap<String, RequestInterceptor>();
  feignBuilder = Feign.builder()
              .encoder(new FormEncoder(new JacksonEncoder(objectMapper)))
              .decoder(new JacksonDecoder(objectMapper))
              .logger(new Slf4jLogger());
}
 
Example 15
Source Project: research-graphql   Source File: OrderControllerTest.java    License: MIT License 5 votes vote down vote up
@Before
public void apiSetup() {
    this.api = Feign.builder()
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .logLevel(Logger.Level.BASIC)
            .target(OrderApi.class, "http://localhost:" + port);
}
 
Example 16
Source Project: research-graphql   Source File: UserControllerTest.java    License: MIT License 5 votes vote down vote up
@Before
public void apiSetup() {
    this.api = Feign.builder()
            .encoder(new JacksonEncoder(jacksonMapper))
            .decoder(new JacksonDecoder(jacksonMapper))
            .logLevel(Logger.Level.BASIC)
            .target(UserApi.class, "http://localhost:"+port);
}
 
Example 17
Source Project: research-graphql   Source File: ProductControllerTest.java    License: MIT License 5 votes vote down vote up
@Before
public void apiSetup() {
    this.api = Feign.builder()
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .logLevel(Logger.Level.BASIC)
            .target(ProductApi.class, "http://localhost:" + port);
}
 
Example 18
Source Project: research-graphql   Source File: OrderAdaptor.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void apiSetup() {
    log.info("Connecting {} to {}", OrderApi.class.getSimpleName(), properties.getUrlOrderService());
    this.api = Feign.builder()
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .logLevel(Logger.Level.BASIC)
            .target(OrderApi.class, properties.getUrlOrderService());
}
 
Example 19
Source Project: research-graphql   Source File: UserAdaptor.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void apiSetup() {
    log.info("Connecting {} to {}", UserApi.class.getSimpleName(), properties.getUrlUserService());
    this.api = Feign.builder()
            .encoder(new JacksonEncoder(jacksonMapper))
            .decoder(new JacksonDecoder(jacksonMapper))
            .logLevel(Logger.Level.BASIC)
            .target(UserApi.class, properties.getUrlUserService());
}
 
Example 20
Source Project: research-graphql   Source File: ProductAdaptor.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void apiSetup() {
    log.info("Connecting {} to {}", ProductApi.class.getSimpleName(), properties.getUrlProductService());
    this.api = Feign.builder()
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .logLevel(Logger.Level.BASIC)
            .target(ProductApi.class, properties.getUrlProductService());
}
 
Example 21
Source Project: research-graphql   Source File: AbstractControllerTestCase.java    License: MIT License 5 votes vote down vote up
<T> T apiSetup(Class<T> target) {
    return Feign.builder()
            .encoder(new JacksonEncoder(mapper))
            .decoder(new JacksonDecoder())
            .logLevel(Logger.Level.BASIC)
            .target(target, "http://localhost:" + port);
}
 
Example 22
Source Project: waggle-dance   Source File: WaggleDanceIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void overwritesConfigOnShutdownAfterAddingFederation() throws Exception {
  runner = WaggleDanceRunner
      .builder(configLocation)
      .databaseResolution(DatabaseResolution.PREFIXED)
      .primary("primary", localServer.getThriftConnectionUri(),
          AccessControlType.READ_AND_WRITE_AND_CREATE_ON_DATABASE_WHITELIST)
      .federate(SECONDARY_METASTORE_NAME, remoteServer.getThriftConnectionUri(), REMOTE_DATABASE)
      .build();

  runWaggleDance(runner);
  FederationsAdminClient restClient = Feign
      .builder()
      .contract(new JAXRSContract())
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .target(FederationsAdminClient.class, "http://localhost:" + runner.getRestApiPort() + "/");

  FederatedMetaStore newFederation = new FederatedMetaStore("new_waggle_remote",
      newRemoteServer.getThriftConnectionUri());
  restClient.add(newFederation);

  Federations federations = stopServerAndGetConfiguration();

  List<FederatedMetaStore> federatedMetastores = federations.getFederatedMetaStores();
  assertThat(federatedMetastores.size(), is(2));

  FederatedMetaStore remoteMetastore = federatedMetastores.get(0);
  assertThat(remoteMetastore.getName(), is(SECONDARY_METASTORE_NAME));
  assertThat(remoteMetastore.getMappedDatabases().size(), is(1));
  assertThat(remoteMetastore.getMappedDatabases().get(0), is(REMOTE_DATABASE));

  FederatedMetaStore newRemoteMetastore = federatedMetastores.get(1);
  assertThat(newRemoteMetastore.getName(), is("new_waggle_remote"));
  assertThat(newRemoteMetastore.getMappedDatabases(), is(nullValue()));
}
 
Example 23
Source Project: waggle-dance   Source File: WaggleDanceIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotOverwriteConfigOnShutdownAfterAddingFederation() throws Exception {
  runner = WaggleDanceRunner
      .builder(configLocation)
      .databaseResolution(DatabaseResolution.PREFIXED)
      .overwriteConfigOnShutdown(false)
      .primary("primary", localServer.getThriftConnectionUri(),
          AccessControlType.READ_AND_WRITE_AND_CREATE_ON_DATABASE_WHITELIST)
      .federate(SECONDARY_METASTORE_NAME, remoteServer.getThriftConnectionUri(), REMOTE_DATABASE)
      .build();

  runWaggleDance(runner);
  FederationsAdminClient restClient = Feign
      .builder()
      .contract(new JAXRSContract())
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .target(FederationsAdminClient.class, "http://localhost:" + runner.getRestApiPort() + "/");

  FederatedMetaStore newFederation = new FederatedMetaStore("new_waggle_remote",
      newRemoteServer.getThriftConnectionUri());
  restClient.add(newFederation);

  Federations federations = stopServerAndGetConfiguration();

  List<FederatedMetaStore> federatedMetastores = federations.getFederatedMetaStores();
  assertThat(federatedMetastores.size(), is(1));

  FederatedMetaStore remoteMetastore = federatedMetastores.get(0);
  assertThat(remoteMetastore.getName(), is(SECONDARY_METASTORE_NAME));
  assertThat(remoteMetastore.getMappedDatabases().size(), is(1));
  assertThat(remoteMetastore.getMappedDatabases().get(0), is(REMOTE_DATABASE));
}
 
Example 24
Source Project: feign-client-test   Source File: FeignClientMain.java    License: MIT License 5 votes vote down vote up
public static void main(String args[]) {

        Feign.Builder encoder = Feign.builder()
                .decoder(new JacksonDecoder())
                .encoder(new FeignSpringFormEncoder());

        UploadServiceClient service = encoder.target(UploadServiceClient.class, "http://localhost:8080");

        MultipartFile file = new InMemoryMultipartFile("filename.tmp", new byte[]{65, 66, 67, 68});
        MultipartFile file2 = new InMemoryMultipartFile("filename2.tmp", new byte[]{69, 70, 71, 72, 73, 68});

        UploadInfo test = service.test(new UploadMetadata("pippo"));
        System.out.println("test: " + test);
        
        UploadInfo upload = service.upload("customFolder", file, new UploadMetadata("pippo"));
        System.out.println("Upload test: " + upload);

        UploadInfo uploadSimple = service.uploadSimple("customFolder", file);
        System.out.println("UploadSimple test: " + uploadSimple);

        List<UploadInfo> uploadArray = service.uploadArray("customFolder", new MultipartFile[]{file, file2}, new UploadMetadata("pippo"));
        int i = 0;
        for (UploadInfo uploadInfo : uploadArray) {
            System.out.println("UploadArray test[" + (i++) + "]: " + uploadInfo);
        }

    }
 
Example 25
Source Project: weed-client   Source File: WeedManager.java    License: 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 26
Source Project: weed-client   Source File: WeedManager.java    License: 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 27
Source Project: weed-client   Source File: WeedManager.java    License: 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 28
Source Project: OneSignal-Java-SDK   Source File: OneSignal.java    License: Apache License 2.0 5 votes vote down vote up
private static OneSignalComms oneSignal() {
    JacksonDecoder decoder = new JacksonDecoder(OBJECT_MAPPER);
    return Feign.builder()
            .encoder(new JacksonEncoder(OBJECT_MAPPER))
            .decoder(decoder)
            .decode404()
            .errorDecoder(new OneSignalErrorDecoder(decoder))
            .logger(new Slf4jLogger())
            .logLevel(Level.FULL)
            .target(OneSignalComms.class, "https://onesignal.com/api/v1");
}
 
Example 29
Source Project: ola   Source File: TracingConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * This is were the "magic" happens: it creates a Feign, which is a proxy interface for remote calling a
 * REST endpoint with Hystrix fallback support.
 */
@Bean
public HolaService holaService(Tracer tracer) {
    // bind current span to Hystrix thread
    TracingConcurrencyStrategy.register();

    return HystrixFeign.builder()
            .client(new TracingClient(new ApacheHttpClient(HttpClientBuilder.create().build()), tracer))
            .logger(new Logger.ErrorLogger()).logLevel(Logger.Level.BASIC)
            .decoder(new JacksonDecoder())
            .target(HolaService.class, "http://hola:8080/",
                    () -> Collections.singletonList("Hola response (fallback)"));
}
 
Example 30
Source Project: feign-vertx   Source File: VertxHttpClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFindOrder_404(TestContext context) {

  /* Given */
  stubFor(get(urlEqualTo("/icecream/orders/123"))
      .withHeader("Accept", equalTo("application/json"))
      .willReturn(aResponse().withStatus(404)));

  IcecreamServiceApi client = VertxFeign
      .builder()
      .vertx(vertx)
      .decoder(new JacksonDecoder(TestUtils.MAPPER))
      .target(IcecreamServiceApi.class, "http://localhost:8089");

  Async async = context.async();

  /* When */
  client.findOrder(123).setHandler(res -> {

    /* Then */
    if (res.failed()) {
      try {
        assertThat(res.cause())
            .isInstanceOf(FeignException.class)
            .hasMessageContaining("status 404");
        async.complete();
      } catch (Throwable exception) {
        context.fail(exception);
      }
    } else {
      context.fail("FeignException excepted but not occurred");
    }
  });
}