ratpack.exec.Promise Java Examples
The following examples show how to use
ratpack.exec.Promise.
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: ZipkinHttpClientImpl.java From ratpack-zipkin with Apache License 2.0 | 6 votes |
@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 #2
Source File: PgClientRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public Promise<List<World>> getWorlds(int[] ids) { PgClient pgClient = pgClients.getOne(); Observable<World> observable = Observable.range(0, ids.length) .flatMap(i -> pgClient.rxPreparedQuery("SELECT * FROM world WHERE id = $1", Tuple.of(ids[i])) .map(rowset -> { final Row row = rowset.iterator().next(); return new World(row.getInteger(0), row.getInteger(1)); }) .toObservable()); return RxRatpack.promiseAll(observable); }
Example #3
Source File: PgClientRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public Promise<List<World>> findAndUpdateWorlds(int[] ids, int[] randomNumbers) { return getWorlds(ids).flatMap(worlds -> { PgClient pgClient = pgClients.getOne(); Observable<World> observable = Observable.range(0, worlds.size()) .flatMap(i -> { World world = worlds.get(i); world.randomNumber = randomNumbers[i]; return pgClient .rxPreparedQuery("UPDATE world SET randomnumber = $1 WHERE id = $2", Tuple.of(world.randomNumber, world.id)) .map(rowset -> world) .toObservable(); }); return RxRatpack.promiseAll(observable); }); }
Example #4
Source File: AbstractTransformer.java From resilience4j with Apache License 2.0 | 6 votes |
protected void handleRecovery(Downstream<? super T> down, Throwable throwable) { try { if (recoverer != null) { T result = recoverer.apply(throwable); if (result instanceof Promise) { ((Promise) result) .onError((t) -> down.error((Throwable) t)) .then((r) -> down.success((T) r)); } else { down.success(result); } } else { down.error(throwable); } } catch (Exception ex) { down.error(ex); } }
Example #5
Source File: AbstractMethodInterceptor.java From resilience4j with Apache License 2.0 | 6 votes |
@Nullable protected Object proceed(MethodInvocation invocation) throws Throwable { Class<?> returnType = invocation.getMethod().getReturnType(); Object result; try { result = invocation.proceed(); } catch (Exception e) { if (Promise.class.isAssignableFrom(returnType)) { return Promise.error(e); } else if (Flux.class.isAssignableFrom(returnType)) { return Flux.error(e); } else if (Mono.class.isAssignableFrom(returnType)) { return Mono.error(e); } else if (CompletionStage.class.isAssignableFrom(returnType)) { CompletableFuture<?> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } else { throw e; } } return result; }
Example #6
Source File: JdbcRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public Promise<List<World>> getWorlds(int[] ids) { return Blocking.get(() -> { World[] worlds = new World[ids.length]; try (Connection connection = dataSource.getConnection()) { Arrays.setAll(worlds, value -> { try { PreparedStatement statement = connection.prepareStatement("SELECT id, randomnumber FROM world WHERE id = ?"); statement.setInt(1, ids[value]); ResultSet rs = statement.executeQuery(); rs.next(); World world = new World(rs.getInt(1), rs.getInt(2)); statement.close(); return world; } catch (SQLException e) { throw new RuntimeException(e); } }); } return Arrays.asList(worlds); }); }
Example #7
Source File: JdbcRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public Promise<List<World>> findAndUpdateWorlds(int[] ids, int[] randomNumbers) { return getWorlds(ids).flatMap(worlds -> { return Blocking.get(() -> { try (Connection connection = dataSource.getConnection()) { int i = 0; for(World world: worlds) { PreparedStatement statement = connection.prepareStatement("UPDATE world SET randomnumber = ? WHERE id = ?"); world.randomNumber = randomNumbers[i++]; statement.setInt(1, world.randomNumber); statement.setInt(2, world.id); statement.executeUpdate(); statement.close(); } return worlds; } }); }); }
Example #8
Source File: MoviePromiseServiceImpl.java From tutorials with MIT License | 6 votes |
@Override public Promise<List<Movie>> getMovies() { Movie movie = new Movie(); movie.setName("The Godfather"); movie.setYear("1972"); movie.setDirector("Coppola"); movie.setRating(9.2); Movie movie2 = new Movie(); movie2.setName("The Godfather Part 2"); movie2.setYear("1974"); movie2.setDirector("Coppola"); movie2.setRating(9.0); List<Movie> movies = new ArrayList<>(); movies.add(movie); movies.add(movie2); return Promise.value(movies); }
Example #9
Source File: ZipkinHttpClientImpl.java From ratpack-zipkin with Apache License 2.0 | 6 votes |
@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 #10
Source File: EmployeeHandler.java From tutorials with MIT License | 5 votes |
@Override public void handle(Context ctx) throws Exception { EmployeeRepository repository = ctx.get(EmployeeRepository.class); Long id = Long.valueOf(ctx.getPathTokens() .get("id")); Promise<Employee> employeePromise = repository.findEmployeeById(id); employeePromise.map(employee -> employee.getName()) .then(name -> ctx.getResponse() .send(name)); }
Example #11
Source File: EmployeeRepositoryImpl.java From tutorials with MIT License | 5 votes |
@Override public Promise<Employee> findEmployeeById(Long id) throws Exception { return Promise.async(downstream -> { Thread.sleep(500); downstream.success(EMPLOYEE_MAP.get(id)); }); }
Example #12
Source File: RedirectHandler.java From tutorials with MIT License | 5 votes |
@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 #13
Source File: MoviePromiseServiceImpl.java From tutorials with MIT License | 5 votes |
@Override public Promise<Movie> getMovie() { Movie movie = new Movie(); movie.setName("The Godfather"); movie.setYear("1972"); movie.setDirector("Coppola"); movie.setRating(9.2); return Promise.value(movie); }
Example #14
Source File: CircuitBreakerMethodInterceptor.java From resilience4j with Apache License 2.0 | 5 votes |
@Nullable private Object proceed(MethodInvocation invocation, io.github.resilience4j.circuitbreaker.CircuitBreaker breaker) throws Throwable { Class<?> returnType = invocation.getMethod().getReturnType(); Object result; long start = System.nanoTime(); try { result = invocation.proceed(); } catch (Exception e) { long durationInNanos = System.nanoTime() - start; breaker.onError(durationInNanos, TimeUnit.NANOSECONDS, e); if (Promise.class.isAssignableFrom(returnType)) { return Promise.error(e); } else if (Flux.class.isAssignableFrom(returnType)) { return Flux.error(e); } else if (Mono.class.isAssignableFrom(returnType)) { return Mono.error(e); } else if (CompletionStage.class.isAssignableFrom(returnType)) { CompletableFuture<?> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } else { throw e; } } return result; }
Example #15
Source File: TimeLimiterMethodInterceptor.java From resilience4j with Apache License 2.0 | 5 votes |
@Nullable @Override public Object invoke(MethodInvocation invocation) throws Throwable { TimeLimiter annotation = invocation.getMethod().getAnnotation(TimeLimiter.class); if (annotation == null) { annotation = invocation.getMethod().getDeclaringClass() .getAnnotation(TimeLimiter.class); } final RecoveryFunction<?> fallbackMethod = Optional .ofNullable(createRecoveryFunction(invocation, annotation.fallbackMethod())) .orElse(new DefaultRecoveryFunction<>()); if (registry == null) { registry = TimeLimiterRegistry.ofDefaults(); } io.github.resilience4j.timelimiter.TimeLimiter timeLimiter = registry.timeLimiter(annotation.name()); Class<?> returnType = invocation.getMethod().getReturnType(); if (Promise.class.isAssignableFrom(returnType)) { return invokeForPromise(invocation, fallbackMethod, timeLimiter); } else if (Flux.class.isAssignableFrom(returnType)) { return invokeForFlux(invocation, fallbackMethod, timeLimiter); } else if (Mono.class.isAssignableFrom(returnType)) { return invokeForMono(invocation, fallbackMethod, timeLimiter); } else if (CompletionStage.class.isAssignableFrom(returnType)) { return invokeForCompletionStage(invocation, fallbackMethod, timeLimiter); } else { throw new IllegalArgumentException(String.join(" ", returnType.getName(), invocation.getMethod().getName(), "has unsupported by @TimeLimiter return type.", "Promise, Mono, Flux, or CompletionStage expected.")); } }
Example #16
Source File: TimeLimiterMethodInterceptor.java From resilience4j with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public Object invokeForPromise(MethodInvocation invocation, RecoveryFunction<?> fallbackMethod, io.github.resilience4j.timelimiter.TimeLimiter timeLimiter) throws Throwable { Promise<?> result = (Promise<?>) proceed(invocation); if (result != null) { TimeLimiterTransformer transformer = TimeLimiterTransformer.of(timeLimiter) .recover(fallbackMethod); result = result.transform(transformer); } return result; }
Example #17
Source File: RatpackITest.java From java-specialagent with Apache License 2.0 | 4 votes |
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 #18
Source File: JdbcRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public Promise<World> getWorld(int id) { return getWorlds(new int[]{id}).map(worlds -> worlds.get(0)); }
Example #19
Source File: AppHttpUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void givenSyncDataSource_GetDataFromPromise() throws Exception { String value = ExecHarness.yieldSingle(execution -> Promise.sync(() -> "Foo")) .getValueOrThrow(); assertEquals("Foo", value); }
Example #20
Source File: PgClientRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public Promise<World> getWorld(int id) { return getWorlds(new int[] { id }).map(worlds -> worlds.get(0)); }
Example #21
Source File: JsonRpcClient.java From consensusj with Apache License 2.0 | 4 votes |
@POST("/") Promise<JsonRpcResponse<JsonNode>> call(@Body JsonRpcRequest request);
Example #22
Source File: TracedParallelBatch.java From ratpack-zipkin with Apache License 2.0 | 4 votes |
private TracedParallelBatch(Iterable<? extends Promise<T>> promises) { this.promises = promises; }
Example #23
Source File: ZipkinHttpClientImpl.java From ratpack-zipkin with Apache License 2.0 | 4 votes |
@Override public Promise<ReceivedResponse> post(final URI uri, final Action<? super RequestSpec> requestConfigurer) { return request(uri, requestConfigurer.prepend(RequestSpec::post)); }
Example #24
Source File: ZipkinHttpClientImpl.java From ratpack-zipkin with Apache License 2.0 | 4 votes |
@Override public Promise<ReceivedResponse> get(final URI uri, final Action<? super RequestSpec> requestConfigurer) { return request(uri, requestConfigurer.prepend(RequestSpec::get)); }
Example #25
Source File: TracedParallelBatch.java From ratpack-zipkin with Apache License 2.0 | 2 votes |
/** * Create a {@link TracedParallelBatch} for list of {@link Promise}s, * with the specified trace context. * * @param context the trace context. * @param promises vararg containing a list of {@link Promise}s. * @param <T> the type of value produced by each promise * * @return an instance of {@link ParallelBatch}. */ public static <T> ParallelBatch<T> of(final TraceContext context, Promise<T>... promises) { return of(context, Arrays.asList(promises)); }
Example #26
Source File: TracedParallelBatch.java From ratpack-zipkin with Apache License 2.0 | 2 votes |
/** * Create a {@link TracedParallelBatch} for list of {@link Promise}s, * with the specified trace context. * * @param context the trace context * @param promises an iterable of Promises * @param <T> the type of value produced by each promise * * @return an instance of {@link ParallelBatch}. */ public static <T> ParallelBatch<T> of(final TraceContext context, Iterable<? extends Promise<T>> promises) { return ParallelBatch.of(promises) .execInit(execution -> execution.add(RatpackCurrentTraceContext.wrap(context))); }
Example #27
Source File: TracedParallelBatch.java From ratpack-zipkin with Apache License 2.0 | 2 votes |
/** * Create a {@link TracedParallelBatch} for list of {@link Promise}s. * * @param promises vararg containing a list of {@link Promise}s. * @param <T> the type of value produced by each promise * * @return an instance of {@link TracedParallelBatch}. */ public static <T> TracedParallelBatch<T> of(Promise<T>... promises) { return new TracedParallelBatch<>(Arrays.asList(promises)); }
Example #28
Source File: TracedParallelBatch.java From ratpack-zipkin with Apache License 2.0 | 2 votes |
/** * Create a {@link TracedParallelBatch} for list of {@link Promise}s. * * @param promises an iterable of Promises * @param <T> the type of value produced by each promise * * @return an instance of {@link TracedParallelBatch}. */ public static <T> TracedParallelBatch<T> of(Iterable<? extends Promise<T>> promises) { return new TracedParallelBatch<>(promises); }
Example #29
Source File: DbRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | votes |
Promise<List<Fortune>> fortunes();
Example #30
Source File: DbRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | votes |
Promise<List<World>> findAndUpdateWorlds(int[] ids, int[] randomNumbers);