ratpack.func.Action Java Examples

The following examples show how to use ratpack.func.Action. 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: NewsServiceApp.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
@Bean
public Action<Chain> home() {
    return chain -> chain.get(ctx -> {

        FindPublisher<News> databasePublisher =
                databaseNews().lookupNews();
        Observable<News> httpNewsObservable =
                externalNews().retrieveNews();
        TransformablePublisher<News> stream = Streams.merge(
                databasePublisher,
                RxReactiveStreams.toPublisher(httpNewsObservable)
        );

        ctx.render(
                stream.toList()
                      .map(Jackson::json)
        );
    });
}
 
Example #2
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 6 votes vote down vote up
@Override
public Promise<ReceivedResponse> request(URI uri, Action<? super RequestSpec> action) {
    // save off the current span as the parent of a future client span
    TraceContext parent = currentTraceContext.get();
    // this reference is used to manually propagate the span from the request to the response
    // we use this because we cannot assume a thread context exists betweeen them.
    AtomicReference<Span> currentSpan = new AtomicReference<>();
    return delegate.request(uri, (RequestSpec requestSpec) -> {
        try {
            action.execute(new WrappedRequestSpec(requestSpec, parent, currentSpan));
        } finally {
            // moves the span from thread local context to an atomic ref the response can read
            currentSpan.set(threadLocalSpan.remove());
        }
    }).wiretap(response -> responseWithSpan(response, currentSpan.getAndSet(null)));
}
 
Example #3
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 6 votes vote down vote up
@Override
public Promise<StreamedResponse> requestStream(URI uri, Action<? super RequestSpec> action) {
    // save off the current span as the parent of a future client span
    TraceContext parent = currentTraceContext.get();
    // this reference is used to manually propagate the span from the request to the response
    // we use this because we cannot assume a thread context exists betweeen them.
    AtomicReference<Span> currentSpan = new AtomicReference<>();
    return delegate.requestStream(uri, (RequestSpec requestSpec) -> {
        // streamed request doesn't set the http method.
        // start span here until a better solution presents itself.
        WrappedRequestSpec captor = new WrappedRequestSpec(requestSpec, parent, currentSpan);

        Span span = nextThreadLocalSpan.apply(captor, parent);
        try {
            handler.handleSend(injector, captor.getHeaders(), captor, span);
            action.execute(new WrappedRequestSpec(requestSpec, parent, currentSpan));
        } finally {
            // moves the span from thread local context to an atomic ref the response can read
            currentSpan.set(threadLocalSpan.remove());
        }
    }).wiretap(response -> streamedResponseWithSpan(response, currentSpan.getAndSet(null)));
}
 
Example #4
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 5 votes vote down vote up
@Override
public RequestSpec onRedirect(Function<? super ReceivedResponse, Action<? super RequestSpec>> function) {

    Function<? super ReceivedResponse, Action<? super RequestSpec>> wrapped =
        (ReceivedResponse response) -> redirectHandler(response).append(function.apply(response));

    this.delegate.onRedirect(wrapped);
    return this;
}
 
Example #5
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 #6
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
@Override
public Promise<ReceivedResponse> get(final URI uri, final Action<? super RequestSpec> requestConfigurer) {
    return request(uri, requestConfigurer.prepend(RequestSpec::get));
}
 
Example #7
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
@Override
public Promise<ReceivedResponse> post(final URI uri, final Action<? super RequestSpec> requestConfigurer) {
    return request(uri, requestConfigurer.prepend(RequestSpec::post));
}
 
Example #8
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
/**
 * Default redirect handler that ensures the span is marked as received before
 * a new span is created.
 */
private Action<? super RequestSpec> redirectHandler(ReceivedResponse response) {
    Span span = currentSpan.getAndSet(null);
    handler.handleReceive(response.getStatusCode(), null, span);
    return (s) -> new WrappedRequestSpec(s, parent, currentSpan);
}
 
Example #9
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
@Override
public RequestSpec headers(Action<? super MutableHeaders> action) throws Exception {
    this.delegate.headers(action);
    return this;
}
 
Example #10
Source File: ZipkinHttpClientImpl.java    From ratpack-zipkin with Apache License 2.0 4 votes vote down vote up
@Override
public RequestSpec body(Action<? super Body> action) throws Exception {
    this.delegate.body(action);
    return this;
}
 
Example #11
Source File: EmbedRatpackApp.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public Action<Chain> hello() {
    return chain -> chain.get("hello", ctx -> ctx.render(content.body()));
}
 
Example #12
Source File: EmbedRatpackApp.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public Action<Chain> list() {
    return chain -> chain.get("list", ctx -> ctx.render(list
      .articles()
      .toString()));
}
 
Example #13
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);
    }