use of io.helidon.common.reactive.Single in project helidon by oracle.
the class InitService method testInitPokemonTypes.
// Initialize pokemon types relation
private void testInitPokemonTypes(final ServerRequest request, final ServerResponse response) {
LOGGER.fine(() -> "Running InitResource.testInitPokemonTypes on server");
sendDmlResponse(response, () -> dbClient.inTransaction(tx -> {
Single<Long> stage = null;
for (Map.Entry<Integer, Pokemon> entry : Pokemon.POKEMONS.entrySet()) {
Pokemon pokemon = entry.getValue();
for (Type type : pokemon.getTypes()) {
if (stage == null) {
stage = tx.namedDml("insert-poketype", pokemon.getId(), type.getId());
} else {
stage = stage.flatMapSingle(result -> tx.namedDml("insert-poketype", pokemon.getId(), type.getId()));
}
}
}
return stage;
}).toCompletableFuture());
}
use of io.helidon.common.reactive.Single in project helidon by oracle.
the class OrderOfWritesTest method threadMixUp.
@Test
void threadMixUp() throws IOException, InterruptedException {
LogConfig.configureRuntime();
ExecutorService exec = null;
HttpServer server = null;
CompletableFuture<String> resultFuture = new CompletableFuture<>();
try {
exec = Executors.newFixedThreadPool(3);
server = HttpServer.create(new InetSocketAddress(0), 0);
server.createContext("/", res -> {
resultFuture.complete(new String(res.getRequestBody().readAllBytes()));
res.sendResponseHeaders(200, 0);
});
server.setExecutor(exec);
server.start();
WebClient.builder().baseUri("http://localhost:" + server.getAddress().getPort()).connectTimeout(TIME_OUT.toMillis(), TimeUnit.MILLISECONDS).build().post().submit(Multi.just("1", "2", "3").map(String::valueOf).map(String::getBytes).observeOn(exec).map(n -> DataChunk.create(ByteBuffer.wrap(n))).flatMap(Single::just, 2, true, 2)).await(TIME_OUT);
String result = Single.create(resultFuture).await(TIME_OUT);
assertThat(result, Matchers.equalTo("123"));
} finally {
if (server != null) {
server.stop(0);
}
if (exec != null) {
exec.shutdownNow();
assertTrue(exec.awaitTermination(TIME_OUT.toMillis(), TimeUnit.MILLISECONDS));
}
}
}
use of io.helidon.common.reactive.Single in project helidon by oracle.
the class WebClientSecurity method request.
@Override
public Single<WebClientServiceRequest> request(WebClientServiceRequest request) {
if ("true".equalsIgnoreCase(request.properties().get(OutboundConfig.PROPERTY_DISABLE_OUTBOUND))) {
return Single.just(request);
}
Context requestContext = request.context();
// context either from request or create a new one
Optional<SecurityContext> maybeContext = requestContext.get(SecurityContext.class);
SecurityContext context;
if (null == security) {
if (maybeContext.isEmpty()) {
return Single.just(request);
} else {
context = maybeContext.get();
}
} else {
// we have our own security - we need to use this instance for outbound,
// so we cannot re-use the context
context = createContext(request);
}
Span span = context.tracer().buildSpan("security:outbound").asChildOf(context.tracingSpan()).start();
String explicitProvider = request.properties().get(PROVIDER_NAME);
OutboundSecurityClientBuilder clientBuilder;
try {
SecurityEnvironment.Builder outboundEnv = context.env().derive().clearHeaders();
outboundEnv.method(request.method().name()).path(request.path().toString()).targetUri(request.uri()).headers(request.headers().toMap());
EndpointConfig.Builder outboundEp = context.endpointConfig().derive();
Map<String, String> propMap = request.properties();
for (String name : propMap.keySet()) {
Optional.ofNullable(request.properties().get(name)).ifPresent(property -> outboundEp.addAtribute(name, property));
}
clientBuilder = context.outboundClientBuilder().outboundEnvironment(outboundEnv).outboundEndpointConfig(outboundEp).explicitProvider(explicitProvider);
} catch (Exception e) {
traceError(span, e, null);
throw e;
}
return Single.create(clientBuilder.submit().thenApply(providerResponse -> processResponse(request, span, providerResponse)));
}
use of io.helidon.common.reactive.Single in project helidon by oracle.
the class Main method startServer.
/**
* Start the server.
* @return the created {@link WebServer} instance
*/
static Single<WebServer> startServer() {
// load logging configuration
LogConfig.configureRuntime();
// By default this will pick up application.yaml from the classpath
Config config = Config.create();
// Get webserver config from the "server" section of application.yaml
WebServer server = WebServer.builder(createRouting(config)).config(config.get("server")).port(-1).addMediaSupport(JsonpSupport.create()).build();
// Server threads are not daemon. No need to block. Just react.
return server.start().peek(ws -> {
System.out.println("WEB server is up! http://localhost:" + ws.port() + "/greet");
ws.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!"));
}).onError(t -> {
System.err.println("Startup failed: " + t.getMessage());
t.printStackTrace(System.err);
});
}
use of io.helidon.common.reactive.Single in project helidon by oracle.
the class RetryImpl method retrySingle.
private <T> Single<T> retrySingle(RetryContext<? extends CompletionStage<T>> context) {
int currentCallIndex = context.count.getAndIncrement();
Optional<Long> maybeDelay = computeDelay(context, currentCallIndex);
if (maybeDelay.isEmpty()) {
return Single.error(context.throwable());
}
long delay = maybeDelay.get();
long nanos = System.nanoTime() - context.startedNanos;
if (nanos > maxTimeNanos) {
TimeoutException te = new RetryTimeoutException(context.throwable(), "Execution took too long. Already executing: " + TimeUnit.NANOSECONDS.toMillis(nanos) + " ms, must timeout after: " + TimeUnit.NANOSECONDS.toMillis(maxTimeNanos) + " ms.");
if (context.hasThrowable()) {
te.initCause(context.throwable());
}
return Single.error(te);
}
if (currentCallIndex > 0) {
retryCounter.getAndIncrement();
}
DelayedTask<Single<T>> task = DelayedTask.createSingle(context.supplier);
if (delay == 0) {
task.execute();
} else {
scheduledExecutor.get().schedule(task::execute, delay, TimeUnit.MILLISECONDS);
}
return task.result().onErrorResumeWithSingle(throwable -> {
Throwable cause = FaultTolerance.cause(throwable);
context.thrown.add(cause);
context.lastDelay.set(delay);
if (errorChecker.shouldSkip(cause)) {
return Single.error(context.throwable());
}
return retrySingle(context);
});
}
Aggregations