ratpack.http.client.HttpClient Java Examples

The following examples show how to use ratpack.http.client.HttpClient. 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: ServerTracingModule.java    From ratpack-zipkin with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
  bind(ServerTracingHandler.class)
      .to(DefaultServerTracingHandler.class)
      .in(Singleton.class);

  bind(HttpClient.class).annotatedWith(Zipkin.class)
      .to(ZipkinHttpClientImpl.class)
      .in(Singleton.class);

  bind(ZipkinHttpClientImpl.class);

  Provider<ServerTracingHandler> serverTracingHandlerProvider =
      getProvider(ServerTracingHandler.class);

  Multibinder.newSetBinder(binder(), HandlerDecorator.class).addBinding()
      .toProvider(() -> HandlerDecorator.prepend(serverTracingHandlerProvider.get()))
      .in(Singleton.class);
}
 
Example #2
Source File: RatpackHystrixApp.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final int timeout = Integer.valueOf(System.getProperty("ratpack.hystrix.timeout"));
    final URI eugenGithubProfileUri = new URI("https://api.github.com/users/eugenp");

    RatpackServer.start(server -> server
      .registry(Guice.registry(bindingsSpec -> bindingsSpec.module(new HystrixModule().sse())))
      .handlers(chain -> chain
        .get("rx", ctx -> new HystrixReactiveHttpCommand(ctx.get(HttpClient.class), eugenGithubProfileUri, timeout)
          .toObservable()
          .subscribe(ctx::render))
        .get("async", ctx -> ctx.render(new HystrixAsyncHttpCommand(eugenGithubProfileUri, timeout)
          .queue()
          .get()))
        .get("sync", ctx -> ctx.render(new HystrixSyncHttpCommand(eugenGithubProfileUri, timeout).execute()))
        .get("hystrix", new HystrixMetricsEventStreamHandler())));

}
 
Example #3
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 5 votes vote down vote up
@Inject
public ZipkinHttpClientImpl(final HttpClient delegate, final HttpTracing httpTracing) {
    this.delegate = delegate;
    this.threadLocalSpan = ThreadLocalSpan.create(httpTracing.tracing().tracer());
    this.currentTraceContext = httpTracing.tracing().currentTraceContext();
    this.nextThreadLocalSpan = new NextSpan(threadLocalSpan, httpTracing.clientSampler());
    this.handler = HttpClientHandler.create(httpTracing, ADAPTER);
    this.injector = httpTracing.tracing().propagation().injector(MutableHeaders::set);
}
 
Example #4
Source File: ITZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 5 votes vote down vote up
@Override protected HttpClient newClient(int port) {
    return Exceptions.uncheck(() -> new ZipkinHttpClientImpl( HttpClient.of(s -> s
        .poolSize(0)
        .byteBufAllocator(UnpooledByteBufAllocator.DEFAULT)
        .maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH)
    ), httpTracing));
}
 
Example #5
Source File: ITZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 5 votes vote down vote up
@Override protected void post(HttpClient client, String pathIncludingQuery, String body)
    throws Exception {
    harness.yield(e ->
        client.post(URI.create(url(pathIncludingQuery)), (request ->
            request.body(b -> b.text(body))
        ))
    ).getValueOrThrow();
}
 
Example #6
Source File: JsonRpcClientModule.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Provides
JsonRpcClient provideJsonRpcClient(Factory<? extends HttpClient> httpClientFactory,
                                   JacksonConverterFactory converterFactory,
                                   RpcConfig rpcConfig) {
    return RatpackRetrofit
            .client(rpcConfig.getURI())
            .httpClient(httpClientFactory)
            .configure(b -> {
                b.addConverterFactory(converterFactory);
            })
            .build(JsonRpcClient.class);
}
 
Example #7
Source File: JsonRpcClientModule.java    From consensusj with Apache License 2.0 5 votes vote down vote up
/**
 * Return an HttpClient Factory that will create a client that adds an Authorization header to HTTP requests
 *
 * @param rpcConfig JSON-RPC Configuration with username and password
 * @return A factory that will produce an HttpClient tthat sets the "Authorization" header
 */
@Provides
Factory<? extends HttpClient> authClientFactory(RpcConfig rpcConfig) {
    final String auth = authString(rpcConfig.getUsername(), rpcConfig.getPassword());
    return () -> clientFactory
            .create()
            .copyWith(
                    spec -> spec.requestIntercept(
                            requestSpec -> requestSpec.headers(
                                    mutableHeaders ->
                                            mutableHeaders.add("Authorization", auth)
                            )
                    )
            );
}
 
Example #8
Source File: HystrixReactiveHttpCommand.java    From tutorials with MIT License 5 votes vote down vote up
HystrixReactiveHttpCommand(HttpClient httpClient, URI uri, int timeoutMillis) {
    super(Setter
      .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-reactive"))
      .andCommandPropertiesDefaults(HystrixCommandProperties
        .Setter()
        .withExecutionTimeoutInMilliseconds(timeoutMillis)));
    this.httpClient = httpClient;
    this.uri = uri;
}
 
Example #9
Source File: RedirectHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void handle(Context ctx) throws Exception {
    HttpClient client = ctx.get(HttpClient.class);
    URI uri = URI.create("http://localhost:5050/employee/1");
    Promise<ReceivedResponse> responsePromise = client.get(uri);
    responsePromise.map(response -> response.getBody()
        .getText()
        .toUpperCase())
        .then(responseText -> ctx.getResponse()
            .send(responseText));
}
 
Example #10
Source File: RatpackITest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final RatpackServer server = RatpackServer.start(new Action<RatpackServerSpec>() {
    @Override
    public void execute(final RatpackServerSpec ratpackServerSpec) {
      ratpackServerSpec.handlers(new Action<Chain>() {
        @Override
        public void execute(final Chain chain) {
          chain.get(new Handler() {
            @Override
            public void handle(final Context context) {
              TestUtil.checkActiveSpan();
              context.render("Test");
            }
          });
        }
      });
    }
  });

  final HttpClient client = HttpClient.of(new Action<HttpClientSpec>() {
    @Override
    public void execute(final HttpClientSpec httpClientSpec) {
      httpClientSpec
        .poolSize(10)
        .maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH)
        .readTimeout(Duration.of(60, ChronoUnit.SECONDS))
        .byteBufAllocator(PooledByteBufAllocator.DEFAULT);
    }
  });

  try (final ExecHarness harness = ExecHarness.harness()) {
    final ExecResult<ReceivedResponse> result = harness.yield(new Function<Execution,Promise<ReceivedResponse>>() {
      @Override
      public Promise<ReceivedResponse> apply(final Execution execution) {
        return client.get(URI.create("http://localhost:5050"));
      }
    });

    final int statusCode = result.getValue().getStatusCode();
    if (200 != statusCode)
      throw new AssertionError("ERROR: response: " + statusCode);
  }

  server.stop();
  TestUtil.checkSpan(new ComponentSpanCount("netty", 2, true));
}
 
Example #11
Source File: ITZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
@Override protected void closeClient(HttpClient client) throws IOException {
    client.close();
}
 
Example #12
Source File: ITZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
@Override protected void get(HttpClient client, String pathIncludingQuery) throws Exception {
    harness.yield(e -> client.get(URI.create(url(pathIncludingQuery)))).getValueOrThrow();
}
 
Example #13
Source File: ITZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
@Override protected void getAsync(HttpClient client, String pathIncludingQuery)
    throws Exception {
    harness.yield(e -> client.requestStream(URI.create(url(pathIncludingQuery)), r -> {
    })).getValueOrThrow();
}
 
Example #14
Source File: Application.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        final Action<HikariConfig> hikariConfigAction = hikariConfig -> {
            hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
            hikariConfig.addDataSourceProperty("URL", "jdbc:h2:mem:baeldung;INIT=RUNSCRIPT FROM 'classpath:/DDL.sql'");
        };

        final Action<BindingsSpec> bindingsSpecAction = bindings -> bindings.module(HikariModule.class, hikariConfigAction);
        final HttpClient httpClient = HttpClient.of(httpClientSpec -> {
            httpClientSpec.poolSize(10)
                .connectTimeout(Duration.of(60, ChronoUnit.SECONDS))
                .maxContentLength(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH)
                .responseMaxChunkSize(16384)
                .readTimeout(Duration.of(60, ChronoUnit.SECONDS))
                .byteBufAllocator(PooledByteBufAllocator.DEFAULT);
        });
        final Function<Registry, Registry> registryFunction = Guice.registry(bindingsSpecAction);

        final Action<Chain> chainAction = chain -> chain.all(new RequestValidatorFilter())
            .get(ctx -> ctx.render("Welcome to baeldung ratpack!!!"))
            .get("data/employees", ctx -> ctx.render(Jackson.json(createEmpList())))
            .get(":name", ctx -> ctx.render("Hello " + ctx.getPathTokens()
                .get("name") + "!!!"))
            .post(":amount", ctx -> ctx.render(" Amount $" + ctx.getPathTokens()
                .get("amount") + " added successfully !!!"));

        final Action<Chain> routerChainAction = routerChain -> {
            routerChain.path("redirect", new RedirectHandler())
                .prefix("employee", empChain -> {
                    empChain.get(":id", new EmployeeHandler());
                });
        };
        final Action<RatpackServerSpec> ratpackServerSpecAction = serverSpec -> serverSpec.registry(registryFunction)
            .registryOf(registrySpec -> {
                registrySpec.add(EmployeeRepository.class, new EmployeeRepositoryImpl());
                registrySpec.add(HttpClient.class, httpClient);
            })
            .handlers(chain -> chain.insert(routerChainAction)
                .insert(chainAction));

        RatpackServer.start(ratpackServerSpecAction);
    }