Search in sources :

Example 21 with Single

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());
}
Also used : DbClientHealthCheck(io.helidon.dbclient.health.DbClientHealthCheck) Config(io.helidon.config.Config) CompletableFuture(java.util.concurrent.CompletableFuture) Logger(java.util.logging.Logger) Supplier(java.util.function.Supplier) Json(jakarta.json.Json) ServerRequest(io.helidon.webserver.ServerRequest) Type(io.helidon.tests.integration.dbclient.appl.model.Type) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) HealthCheckResponse(org.eclipse.microprofile.health.HealthCheckResponse) AppResponse.exceptionStatus(io.helidon.tests.integration.tools.service.AppResponse.exceptionStatus) Pokemon(io.helidon.tests.integration.dbclient.appl.model.Pokemon) Map(java.util.Map) ServerResponse(io.helidon.webserver.ServerResponse) Single(io.helidon.common.reactive.Single) AppResponse.okStatus(io.helidon.tests.integration.tools.service.AppResponse.okStatus) Service(io.helidon.webserver.Service) DbClient(io.helidon.dbclient.DbClient) Routing(io.helidon.webserver.Routing) HealthCheck(org.eclipse.microprofile.health.HealthCheck) Type(io.helidon.tests.integration.dbclient.appl.model.Type) Pokemon(io.helidon.tests.integration.dbclient.appl.model.Pokemon) Map(java.util.Map)

Example 22 with Single

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));
        }
    }
}
Also used : HttpServer(com.sun.net.httpserver.HttpServer) DataChunk(io.helidon.common.http.DataChunk) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Duration(java.time.Duration) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Single(io.helidon.common.reactive.Single) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LogConfig(io.helidon.common.LogConfig) ExecutorService(java.util.concurrent.ExecutorService) Multi(io.helidon.common.reactive.Multi) CompletableFuture(java.util.concurrent.CompletableFuture) Single(io.helidon.common.reactive.Single) InetSocketAddress(java.net.InetSocketAddress) ExecutorService(java.util.concurrent.ExecutorService) HttpServer(com.sun.net.httpserver.HttpServer) Test(org.junit.jupiter.api.Test)

Example 23 with Single

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)));
}
Also used : Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) SpanContext(io.opentracing.SpanContext) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) Security(io.helidon.security.Security) WebClientServiceRequest(io.helidon.webclient.WebClientServiceRequest) WebClientService(io.helidon.webclient.spi.WebClientService) Tracer(io.opentracing.Tracer) Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) UUID(java.util.UUID) Logger(java.util.logging.Logger) OutboundSecurityClientBuilder(io.helidon.security.OutboundSecurityClientBuilder) OutboundConfig(io.helidon.security.providers.common.OutboundConfig) WebClientRequestHeaders(io.helidon.webclient.WebClientRequestHeaders) Contexts(io.helidon.common.context.Contexts) Tags(io.opentracing.tag.Tags) SpanContext(io.opentracing.SpanContext) List(java.util.List) EndpointConfig(io.helidon.security.EndpointConfig) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Map(java.util.Map) Optional(java.util.Optional) Single(io.helidon.common.reactive.Single) Span(io.opentracing.Span) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Span(io.opentracing.Span) SecurityContext(io.helidon.security.SecurityContext) OutboundSecurityClientBuilder(io.helidon.security.OutboundSecurityClientBuilder) EndpointConfig(io.helidon.security.EndpointConfig)

Example 24 with Single

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);
    });
}
Also used : Counter(io.micrometer.core.instrument.Counter) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Timer(io.micrometer.core.instrument.Timer) MicrometerSupport(io.helidon.integrations.micrometer.MicrometerSupport) Config(io.helidon.config.Config) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig)

Example 25 with Single

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);
    });
}
Also used : Single(io.helidon.common.reactive.Single) AtomicLong(java.util.concurrent.atomic.AtomicLong) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Single (io.helidon.common.reactive.Single)39 Config (io.helidon.config.Config)23 Routing (io.helidon.webserver.Routing)18 WebServer (io.helidon.webserver.WebServer)18 LogConfig (io.helidon.common.LogConfig)16 JsonpSupport (io.helidon.media.jsonp.JsonpSupport)15 MetricsSupport (io.helidon.metrics.MetricsSupport)12 Optional (java.util.Optional)12 Logger (java.util.logging.Logger)12 Http (io.helidon.common.http.Http)11 MediaType (io.helidon.common.http.MediaType)9 DataChunk (io.helidon.common.http.DataChunk)8 HealthSupport (io.helidon.health.HealthSupport)8 HealthChecks (io.helidon.health.checks.HealthChecks)8 WebClient (io.helidon.webclient.WebClient)8 WebClientRequestBuilder (io.helidon.webclient.WebClientRequestBuilder)8 JsonBuilderFactory (jakarta.json.JsonBuilderFactory)8 JsonObject (jakarta.json.JsonObject)8 Supplier (java.util.function.Supplier)8 Contexts (io.helidon.common.context.Contexts)7