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);
});
}
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!"));
}
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;
}
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);
}
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);
}
Aggregations