feign.jackson.JacksonDecoder Java Examples

The following examples show how to use feign.jackson.JacksonDecoder. 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: AlertsPublisher.java    From hawkular-apm with 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 #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: 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 #5
Source File: FrostmourneSpiAutoConfiguration.java    From frostmourne with 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 File: SimulatedDeviceFactory.java    From hawkbit-examples with Eclipse Public License 1.0 6 votes vote down vote up
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 #7
Source File: BackendServiceFactory.java    From jrestless-examples with 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 #8
Source File: TracingConfiguration.java    From hola with 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 File: VertxHttp2ClientReconnectTest.java    From feign-vertx with 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 #10
Source File: DecoderIteratorsBenchmark.java    From feign with 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 #11
Source File: ReactiveFeignIntegrationTest.java    From feign with 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 #12
Source File: VertxHttpOptionsTest.java    From feign-vertx with 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 #13
Source File: ModuleConfigurationIntegrationClient.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
@HystrixCommand(fallbackMethod = "getModulesConfigurationPropertiesFallback")
public ModulesConfigurationProperties getModulesConfigurationProperties(String serviceName) {
    log.debug("getModulesConfigurationProperties: " + serviceName);

    if (discoveryClient.getInstances(serviceName).isEmpty()) {
        throw new PlatformCoreException("Can not find any instance for " + serviceName);
    }

    ServiceInstance serviceInstance = discoveryClient.getInstances(serviceName).get(0);
    ModuleConfigurationService moduleConfigurationService = Feign.builder().contract(new JAXRSContract()).encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder()).target(ModuleConfigurationService.class,
                    "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort());

    return moduleConfigurationService.getModulesConfigurationProperties();
}
 
Example #14
Source File: VertxHttp11ClientReconnectTest.java    From feign-vertx with Apache License 2.0 5 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 HTTP 1.1 test, set up the pool size to 3. Then in the server side, there should be only 3 connections created per client.
  HttpClientOptions options = new HttpClientOptions();
  options.setMaxPoolSize(3);

  client = VertxFeign
      .builder()
      .vertx(this.vertx)
      .options(options)
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .target(HelloServiceAPI.class, "http://localhost:8091");
}
 
Example #15
Source File: FeignApiConfig.java    From frostmourne with 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 #16
Source File: Application.java    From hawkbit-examples with Eclipse Public License 1.0 5 votes vote down vote up
private static MgmtSoftwareModuleClientResource uploadSoftwareModule(
        final ClientConfigurationProperties configuration) {
    final ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(new Jackson2HalModule());
    return Feign.builder().contract(new IgnoreMultipleConsumersProducersSpringMvcContract()).decode404()
            .requestInterceptor(
                    new BasicAuthRequestInterceptor(configuration.getUsername(), configuration.getPassword()))
            .logger(new Slf4jLogger()).encoder(new FeignMultipartEncoder())
            .decoder(new ResponseEntityDecoder(new JacksonDecoder(mapper)))
            .target(MgmtSoftwareModuleClientResource.class, configuration.getUrl());
}
 
Example #17
Source File: VertxHttpOptionsTest.java    From feign-vertx with Apache License 2.0 5 votes vote down vote up
/**
 * Test the Vert.x HttpClientOptions version of the Vert.x Feign Client.
 * This is useful for use-cases like HTTPS/2 or gzip compressed responses.
 * @param context Test Context
 */
@Test
public void testHttpClientOptions(TestContext context) {
  // NOTE: We cannot use HTTPS/2 because Wiremock 2.1.0-beta uses Jetty 9.2.13.v20150730.
  //       Jetty 9.3 is required for HTTPS/2. So we use HttpClientOptions.TryUseCompression(true)
  //       instead to verify we're using the Vert.x HttpClientOptions object.
  HttpClientOptions options = new HttpClientOptions().
          setTryUseCompression(true). // Attribute under test, not available with Feign Request.Options
          setConnectTimeout(5000).
          setIdleTimeout(5000);

  IcecreamServiceApi client = VertxFeign
          .builder()
          .vertx(vertx)
          .options(options) // New feature! Accepts HttpClientOptions
          .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", equalTo("deflate, gzip")) // Test setTryUseCompression(true) affected the request
          .willReturn(aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody(flavorsStr)));

  testClient(client, context);
}
 
Example #18
Source File: FeignClientFactory.java    From web-budget with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the default values of this factory
 *
 * @return the feign builder to create the clients
 */
private Feign.Builder getDefaults() {
    return Feign.builder()
            .logLevel(FULL)
            .decode404()
            .encoder(new JacksonEncoder(this.configureMapper()))
            .decoder(new JacksonDecoder(this.configureMapper()));
}
 
Example #19
Source File: RabbitMQManagementAPI.java    From james-project with Apache License 2.0 5 votes vote down vote up
static RabbitMQManagementAPI from(RabbitMQConfiguration configuration) {
    RabbitMQConfiguration.ManagementCredentials credentials = configuration.getManagementCredentials();
    return Feign.builder()
        .requestInterceptor(new BasicAuthRequestInterceptor(credentials.getUser(), new String(credentials.getPassword())))
        .logger(new Slf4jLogger(RabbitMQManagementAPI.class))
        .logLevel(Logger.Level.FULL)
        .encoder(new JacksonEncoder())
        .decoder(new JacksonDecoder())
        .retryer(new Retryer.Default())
        .errorDecoder(RETRY_500)
        .target(RabbitMQManagementAPI.class, configuration.getManagementUri().toString());
}
 
Example #20
Source File: ConfigurationClient.java    From james-project with Apache License 2.0 5 votes vote down vote up
static ConfigurationClient from(Host mockServerHttpHost) {
    return Feign.builder()
        .logger(new Slf4jLogger(ConfigurationClient.class))
        .logLevel(Logger.Level.FULL)
        .encoder(new JacksonEncoder(OBJECT_MAPPER))
        .decoder(new JacksonDecoder(OBJECT_MAPPER))
        .target(ConfigurationClient.class, "http://" + mockServerHttpHost.asString());
}
 
Example #21
Source File: LinshareAPI.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static LinshareAPI from(LinshareConfiguration configuration) {
    return Feign.builder()
        .requestInterceptor(
            new BasicAuthRequestInterceptor(
                configuration.getUuid().toString(),
                configuration.getPassword()))
        .logger(new Slf4jLogger(LinshareAPI.class))
        .logLevel(Logger.Level.FULL)
        .encoder(new FormEncoder(new JacksonEncoder()))
        .decoder(new JacksonDecoder())
        .target(LinshareAPI.class, configuration.getUrl().toString());
}
 
Example #22
Source File: LinshareExtension.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static LinshareAPIForAdminTesting from(LinshareFixture.Credential credential) {

    return Feign.builder()
        .requestInterceptor(new BasicAuthRequestInterceptor(credential.getUsername(), credential.getPassword()))
        .logger(new Slf4jLogger(LinshareAPIForAdminTesting.class))
        .logLevel(Logger.Level.FULL)
        .encoder(new FormEncoder(new JacksonEncoder()))
        .decoder(CombinedDecoder.builder()
            .defaultDecoder(new JacksonDecoder())
            .registerSingleTypeDecoder(new ByteArrayDecoder())
            .build())
        .target(LinshareAPIForAdminTesting.class, linshare.getUrl());
}
 
Example #23
Source File: LinshareExtension.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static LinshareAPIForTechnicalAccountTesting from(LinshareFixture.Credential credential) {

    return Feign.builder()
        .requestInterceptor(new BasicAuthRequestInterceptor(credential.getUsername(), credential.getPassword()))
        .logger(new Slf4jLogger(LinshareAPIForTechnicalAccountTesting.class))
        .logLevel(Logger.Level.FULL)
        .encoder(new FormEncoder(new JacksonEncoder()))
        .decoder(CombinedDecoder.builder()
            .defaultDecoder(new JacksonDecoder())
            .registerSingleTypeDecoder(new ByteArrayDecoder())
            .build())
        .target(LinshareAPIForTechnicalAccountTesting.class, linshare.getUrl());
}
 
Example #24
Source File: LinshareExtension.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
 static LinshareAPIForUserTesting from(LinshareFixture.Credential credential) {

    return Feign.builder()
        .requestInterceptor(new BasicAuthRequestInterceptor(credential.getUsername(), credential.getPassword()))
        .logger(new Slf4jLogger(LinshareAPIForUserTesting.class))
        .logLevel(Logger.Level.FULL)
        .encoder(new FormEncoder(new JacksonEncoder()))
        .decoder(CombinedDecoder.builder()
            .defaultDecoder(new JacksonDecoder())
            .registerSingleTypeDecoder(new ByteArrayDecoder())
            .build())
        .target(LinshareAPIForUserTesting.class, linshare.getUrl());
}
 
Example #25
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 #26
Source File: FeignClientFactory.java    From web-budget with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the default values of this factory
 *
 * @return the feign builder to create the clients
 */
private Feign.Builder getDefaults() {
    return Feign.builder()
            .logLevel(FULL)
            .decode404()
            .encoder(new JacksonEncoder(this.configureMapper()))
            .decoder(new JacksonDecoder(this.configureMapper()));
}
 
Example #27
Source File: ReactiveFeignIntegrationTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void testReactorTargetFull() throws Exception {
  this.webServer.enqueue(new MockResponse().setBody("1.0"));
  this.webServer.enqueue(new MockResponse().setBody("{ \"username\": \"test\" }"));

  TestReactorService service = ReactorFeign.builder()
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .logger(new ConsoleLogger())
      .decode404()
      .options(new Options())
      .logLevel(Level.FULL)
      .target(TestReactorService.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 #28
Source File: GitHubExample.java    From feign with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) {
  GitHub github = Feign.builder()
      .decoder(new JacksonDecoder())
      .target(GitHub.class, "https://api.github.com");

  System.out.println("Let's fetch and print a list of the contributors to this library.");
  List<Contributor> contributors = github.contributors("netflix", "feign");
  for (Contributor contributor : contributors) {
    System.out.println(contributor.login + " (" + contributor.contributions + ")");
  }
}
 
Example #29
Source File: SpringContractTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  mockClient = new MockClient()
      .noContent(HttpMethod.GET, "/health")
      .noContent(HttpMethod.GET, "/health/1")
      .noContent(HttpMethod.GET, "/health/1?deep=true")
      .noContent(HttpMethod.GET, "/health/1?deep=true&dryRun=true")
      .ok(HttpMethod.GET, "/health/generic", "{}");
  resource = Feign.builder()
      .contract(new SpringContract())
      .encoder(new JacksonEncoder())
      .decoder(new JacksonDecoder())
      .client(mockClient)
      .target(new MockTarget<>(HealthResource.class));
}
 
Example #30
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();
}