Search in sources :

Example 26 with Single

use of io.helidon.common.reactive.Single in project helidon by oracle.

the class Main method startBackendServer.

/**
 * Start the server.
 * @return the created {@link WebServer} instance
 */
public static Single<WebServer> startBackendServer() {
    // configure logging in order to not have the standard JVM defaults
    LogConfig.configureRuntime();
    Config config = Config.builder().sources(ConfigSources.environmentVariables()).build();
    WebServer webServer = WebServer.builder(Routing.builder().register(new TranslatorBackendService())).port(9080).tracer(TracerBuilder.create(config.get("tracing")).serviceName("helidon-webserver-translator-backend").build()).build();
    return webServer.start().peek(ws -> {
        System.out.println("WEB server is up! http://localhost:" + ws.port());
        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 : TracerBuilder(io.helidon.tracing.TracerBuilder) Config(io.helidon.config.Config) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) LogConfig(io.helidon.common.LogConfig) ConfigSources(io.helidon.config.ConfigSources) Routing(io.helidon.webserver.Routing) WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig)

Example 27 with Single

use of io.helidon.common.reactive.Single in project helidon by oracle.

the class ClientMain method saveResponseToFile.

static Single<Void> saveResponseToFile(WebClient webClient) {
    // We have to create file subscriber first. This subscriber will save the content of the response to the file.
    Path file = Paths.get("test.txt");
    try {
        Files.deleteIfExists(file);
        Files.createFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Downloading server response to file: " + file);
    return webClient.get().request().map(WebClientResponse::content).flatMapSingle(content -> content.map(DataChunk::data).flatMapIterable(Arrays::asList).to(IoMulti.writeToFile(file).build())).peek(path -> System.out.println("Download complete!"));
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) WebClient(io.helidon.webclient.WebClient) WebClientService(io.helidon.webclient.spi.WebClientService) Files(java.nio.file.Files) IoMulti(io.helidon.common.reactive.IoMulti) Config(io.helidon.config.Config) WebClientResponse(io.helidon.webclient.WebClientResponse) DataChunk(io.helidon.common.http.DataChunk) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) IOException(java.io.IOException) ConfigValue(io.helidon.config.ConfigValue) Json(jakarta.json.Json) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Counter(org.eclipse.microprofile.metrics.Counter) Paths(java.nio.file.Paths) JsonObject(jakarta.json.JsonObject) Single(io.helidon.common.reactive.Single) MetricRegistry(org.eclipse.microprofile.metrics.MetricRegistry) Http(io.helidon.common.http.Http) Path(java.nio.file.Path) Collections(java.util.Collections) RegistryFactory(io.helidon.metrics.RegistryFactory) WebClientMetrics(io.helidon.webclient.metrics.WebClientMetrics) WebClientResponse(io.helidon.webclient.WebClientResponse) DataChunk(io.helidon.common.http.DataChunk) IOException(java.io.IOException)

Example 28 with Single

use of io.helidon.common.reactive.Single in project helidon by oracle.

the class ServerBuilderMain method startServer.

static Single<WebServer> startServer(int unsecured, int secured) {
    SocketConfiguration socketConf = SocketConfiguration.builder().name("secured").port(secured).tls(tlsConfig()).build();
    Single<WebServer> webServer = WebServer.builder().port(unsecured).routing(createPlainRouting()).addSocket(socketConf, createMtlsRouting()).build().start();
    webServer.thenAccept(ws -> {
        System.out.println("WebServer is up!");
        System.out.println("Unsecured: http://localhost:" + ws.port() + "/");
        System.out.println("Secured: https://localhost:" + ws.port("secured") + "/");
        ws.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!"));
    }).exceptionally(t -> {
        System.err.println("Startup failed: " + t.getMessage());
        t.printStackTrace(System.err);
        return null;
    });
    return webServer;
}
Also used : SocketConfiguration(io.helidon.webserver.SocketConfiguration) KeyConfig(io.helidon.common.pki.KeyConfig) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) ClientAuthentication(io.helidon.webserver.ClientAuthentication) Resource(io.helidon.common.configurable.Resource) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) WebServerTls(io.helidon.webserver.WebServerTls) WebServer(io.helidon.webserver.WebServer) SocketConfiguration(io.helidon.webserver.SocketConfiguration)

Example 29 with Single

use of io.helidon.common.reactive.Single in project helidon by oracle.

the class IdcsRoleMapperRxProvider method getGrantsFromServer.

/**
 * Retrieves grants from IDCS server.
 *
 * @param subject to get grants for
 * @return optional list of grants to be added
 */
protected Single<List<? extends Grant>> getGrantsFromServer(Subject subject) {
    String subjectName = subject.principal().getName();
    String subjectType = (String) subject.principal().abacAttribute("sub_type").orElse(defaultIdcsSubjectType());
    RoleMapTracing tracing = SecurityTracing.get().roleMapTracing("idcs");
    return Single.create(appToken.getToken(tracing)).flatMapSingle(maybeAppToken -> {
        if (maybeAppToken.isEmpty()) {
            return Single.error(new SecurityException("Application token not available"));
        }
        String appToken = maybeAppToken.get();
        JsonObjectBuilder requestBuilder = JSON.createObjectBuilder().add("mappingAttributeValue", subjectName).add("subjectType", subjectType).add("includeMemberships", true);
        JsonArrayBuilder arrayBuilder = JSON.createArrayBuilder();
        arrayBuilder.add("urn:ietf:params:scim:schemas:oracle:idcs:Asserter");
        requestBuilder.add("schemas", arrayBuilder);
        // use current span context as a parent for client outbound
        // using a custom child context, so we do not replace the parent in the current context
        Context parentContext = Contexts.context().orElseGet(Contexts::globalContext);
        Context childContext = Context.builder().parent(parentContext).build();
        tracing.findParent().ifPresent(childContext::register);
        WebClientRequestBuilder request = oidcConfig().generalWebClient().post().uri(asserterUri).context(childContext).headers(it -> {
            it.add(Http.Header.AUTHORIZATION, "Bearer " + appToken);
            return it;
        });
        return processRoleRequest(request, requestBuilder.build(), subjectName);
    }).peek(ignored -> tracing.finish()).onError(tracing::error);
}
Also used : Context(io.helidon.common.context.Context) ProviderRequest(io.helidon.security.ProviderRequest) Context(io.helidon.common.context.Context) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) SecurityException(io.helidon.security.SecurityException) OidcConfig(io.helidon.security.providers.oidc.common.OidcConfig) EvictableCache(io.helidon.security.providers.common.EvictableCache) Single(io.helidon.common.reactive.Single) Grant(io.helidon.security.Grant) Subject(io.helidon.security.Subject) URI(java.net.URI) LinkedList(java.util.LinkedList) Http(io.helidon.common.http.Http) SecurityTracing(io.helidon.security.integration.common.SecurityTracing) Config(io.helidon.config.Config) SubjectMappingProvider(io.helidon.security.spi.SubjectMappingProvider) SecurityProvider(io.helidon.security.spi.SecurityProvider) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Contexts(io.helidon.common.context.Contexts) Json(jakarta.json.Json) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) List(java.util.List) Optional(java.util.Optional) RoleMapTracing(io.helidon.security.integration.common.RoleMapTracing) Collections(java.util.Collections) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) RoleMapTracing(io.helidon.security.integration.common.RoleMapTracing) SecurityException(io.helidon.security.SecurityException) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) Contexts(io.helidon.common.context.Contexts) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder)

Example 30 with Single

use of io.helidon.common.reactive.Single in project helidon by oracle.

the class WebClientRequestBuilderImpl method invoke.

private Single<WebClientResponse> invoke(Flow.Publisher<DataChunk> requestEntity) {
    finalUri = prepareFinalURI();
    if (requestId == null) {
        requestId = REQUEST_NUMBER.incrementAndGet();
    }
    // LOGGER.finest(() -> "(client reqID: " + requestId + ") Request final URI: " + uri);
    CompletableFuture<WebClientServiceRequest> sent = new CompletableFuture<>();
    CompletableFuture<WebClientServiceResponse> responseReceived = new CompletableFuture<>();
    CompletableFuture<WebClientServiceResponse> complete = new CompletableFuture<>();
    WebClientServiceRequest completedRequest = new WebClientServiceRequestImpl(this, sent, responseReceived, complete);
    CompletionStage<WebClientServiceRequest> rcs = CompletableFuture.completedFuture(completedRequest);
    for (WebClientService service : services) {
        rcs = rcs.thenCompose(service::request).thenApply(servReq -> {
            finalUri = recreateURI(servReq);
            return servReq;
        });
    }
    Single<WebClientResponse> single = Single.create(rcs.thenCompose(serviceRequest -> {
        URI requestUri = relativizeNoProxy(finalUri, proxy, configuration.relativeUris());
        requestId = serviceRequest.requestId();
        HttpHeaders headers = toNettyHttpHeaders();
        DefaultHttpRequest request = new DefaultHttpRequest(toNettyHttpVersion(httpVersion), toNettyMethod(method), requestUri.toASCIIString(), headers);
        boolean keepAlive = HttpUtil.isKeepAlive(request);
        requestConfiguration = RequestConfiguration.builder(finalUri).update(configuration).followRedirects(followRedirects).clientServiceRequest(serviceRequest).readerContext(readerContext).writerContext(writerContext).connectTimeout(connectTimeout).readTimeout(readTimeout).services(services).context(context).proxy(proxy).keepAlive(keepAlive).requestId(requestId).build();
        WebClientRequestImpl clientRequest = new WebClientRequestImpl(this);
        CompletableFuture<WebClientResponse> result = new CompletableFuture<>();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventGroup).channel(NioSocketChannel.class).handler(new NettyClientInitializer(requestConfiguration)).option(ChannelOption.SO_KEEPALIVE, keepAlive).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis());
        ChannelFuture channelFuture = keepAlive ? obtainChannelFuture(requestConfiguration, bootstrap) : bootstrap.connect(finalUri.getHost(), finalUri.getPort());
        channelFuture.addListener((ChannelFutureListener) future -> {
            if (LOGGER.isLoggable(Level.FINEST)) {
                LOGGER.finest(() -> "(client reqID: " + requestId + ") " + "Channel hashcode -> " + channelFuture.channel().hashCode());
            }
            channelFuture.channel().attr(REQUEST).set(clientRequest);
            channelFuture.channel().attr(RESPONSE_RECEIVED).set(false);
            channelFuture.channel().attr(RECEIVED).set(responseReceived);
            channelFuture.channel().attr(COMPLETED).set(complete);
            channelFuture.channel().attr(WILL_CLOSE).set(!keepAlive);
            channelFuture.channel().attr(RESULT).set(result);
            channelFuture.channel().attr(REQUEST_ID).set(requestId);
            Throwable cause = future.cause();
            if (null == cause) {
                RequestContentSubscriber requestContentSubscriber = new RequestContentSubscriber(request, channelFuture.channel(), result, sent, allowChunkedEncoding);
                requestEntity.subscribe(requestContentSubscriber);
            } else {
                sent.completeExceptionally(cause);
                responseReceived.completeExceptionally(cause);
                complete.completeExceptionally(cause);
                result.completeExceptionally(new WebClientException(finalUri.toString(), cause));
            }
        });
        return result;
    }));
    return wrapWithContext(single);
}
Also used : AttributeKey(io.netty.util.AttributeKey) Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) DataChunk(io.helidon.common.http.DataChunk) MessageBodyReadableContent(io.helidon.media.common.MessageBodyReadableContent) AsciiString(io.netty.util.AsciiString) MessageBodyWriterContext(io.helidon.media.common.MessageBodyWriterContext) MediaType(io.helidon.common.http.MediaType) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Flow(java.util.concurrent.Flow) Duration(java.time.Duration) Map(java.util.Map) Parameters(io.helidon.common.http.Parameters) URI(java.net.URI) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Logger(java.util.logging.Logger) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Objects(java.util.Objects) MessageBodyReaderContext(io.helidon.media.common.MessageBodyReaderContext) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Optional(java.util.Optional) Headers(io.helidon.common.http.Headers) HttpRequest(io.helidon.common.http.HttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) Context(io.helidon.common.context.Context) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) StringTokenizer(java.util.StringTokenizer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Single(io.helidon.common.reactive.Single) Http(io.helidon.common.http.Http) WebClientService(io.helidon.webclient.spi.WebClientService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) GenericType(io.helidon.common.GenericType) Contexts(io.helidon.common.context.Contexts) ChannelFuture(io.netty.channel.ChannelFuture) TimeUnit(java.util.concurrent.TimeUnit) Channel(io.netty.channel.Channel) AtomicLong(java.util.concurrent.atomic.AtomicLong) Bootstrap(io.netty.bootstrap.Bootstrap) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) HttpUtil(io.netty.handler.codec.http.HttpUtil) ChannelFuture(io.netty.channel.ChannelFuture) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) WebClientService(io.helidon.webclient.spi.WebClientService) URI(java.net.URI) ChannelFutureListener(io.netty.channel.ChannelFutureListener) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap)

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