Search in sources :

Example 16 with Single

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

the class Main method main.

/**
 * Main method to start Helidon LRA coordinator.
 *
 * @param args are not used
 */
public static void main(String[] args) {
    LogConfig.configureRuntime();
    Config config = Config.create();
    CoordinatorService coordinatorService = CoordinatorService.builder().build();
    WebServer server = WebServer.builder(createRouting(config, coordinatorService)).config(config.get("helidon.lra.coordinator.server")).build();
    String context = config.get("helidon.lra.coordinator.context.path").asString().orElse("/lra-coordinator");
    Single<WebServer> webserver = server.start();
    webserver.thenAccept(ws -> {
        System.out.println("Helidon LRA Coordinator is up! http://localhost:" + ws.port() + context);
        ws.whenShutdown().thenRun(() -> {
            System.out.println("Helidon LRA Coordinator is DOWN. Good bye!");
        });
    }).exceptionallyAccept(t -> {
        System.err.println("Startup failed: " + t.getMessage());
        t.printStackTrace(System.err);
    });
}
Also used : Config(io.helidon.config.Config) WebServer(io.helidon.webserver.WebServer) Single(io.helidon.common.reactive.Single) MetricsSupport(io.helidon.metrics.MetricsSupport) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) HealthSupport(io.helidon.health.HealthSupport) HealthChecks(io.helidon.health.checks.HealthChecks) WebServer(io.helidon.webserver.WebServer) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig)

Example 17 with Single

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

the class FormParamsBodyReader method read.

@Override
@SuppressWarnings("unchecked")
public <U extends FormParams> Single<U> read(Flow.Publisher<DataChunk> publisher, GenericType<U> type, MessageBodyReaderContext context) {
    MediaType mediaType = context.contentType().orElseThrow();
    Charset charset = mediaType.charset().map(Charset::forName).orElse(StandardCharsets.UTF_8);
    Function<String, String> decoder = decoder(mediaType, charset);
    return (Single<U>) ContentReaders.readString(publisher, charset).map(formStr -> create(formStr, mediaType, decoder));
}
Also used : URLDecoder(java.net.URLDecoder) DataChunk(io.helidon.common.http.DataChunk) GenericType(io.helidon.common.GenericType) Function(java.util.function.Function) StandardCharsets(java.nio.charset.StandardCharsets) MediaType(io.helidon.common.http.MediaType) Matcher(java.util.regex.Matcher) Charset(java.nio.charset.Charset) Flow(java.util.concurrent.Flow) Map(java.util.Map) FormParams(io.helidon.common.http.FormParams) Single(io.helidon.common.reactive.Single) Pattern(java.util.regex.Pattern) Single(io.helidon.common.reactive.Single) MediaType(io.helidon.common.http.MediaType) Charset(java.nio.charset.Charset)

Example 18 with Single

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

the class NonJaxRsResource method createNonJaxRsParticipantResource.

Service createNonJaxRsParticipantResource() {
    return rules -> rules.any("/{type}/{fqdn}/{methodName}", (req, res) -> {
        LOGGER.log(Level.FINE, () -> "Non JAX-RS LRA resource " + req.method().name() + " " + req.absoluteUri());
        RequestHeaders headers = req.headers();
        HttpRequest.Path path = req.path();
        URI lraId = headers.first(LRA_HTTP_CONTEXT_HEADER).or(() -> headers.first(LRA_HTTP_ENDED_CONTEXT_HEADER)).map(URI::create).orElse(null);
        URI parentId = headers.first(LRA_HTTP_PARENT_CONTEXT_HEADER).map(URI::create).orElse(null);
        PropagatedHeaders propagatedHeaders = participantService.prepareCustomHeaderPropagation(headers.toMap());
        String fqdn = path.param("fqdn");
        String method = path.param("methodName");
        String type = path.param("type");
        switch(type) {
            case "compensate":
            case "complete":
                Single.<Optional<?>>empty().observeOn(exec).onCompleteResumeWithSingle(o -> participantService.invoke(fqdn, method, lraId, parentId, propagatedHeaders)).forSingle(result -> result.ifPresentOrElse(r -> sendResult(res, r), res::send)).exceptionallyAccept(t -> sendError(lraId, req, res, t));
                break;
            case "afterlra":
                req.content().as(String.class).map(LRAStatus::valueOf).observeOn(exec).flatMapSingle(s -> Single.defer(() -> participantService.invoke(fqdn, method, lraId, s, propagatedHeaders))).onComplete(res::send).onError(t -> sendError(lraId, req, res, t)).ignoreElement();
                break;
            case "status":
                Single.<Optional<?>>empty().observeOn(exec).onCompleteResumeWithSingle(o -> participantService.invoke(fqdn, method, lraId, null, propagatedHeaders)).forSingle(result -> result.ifPresentOrElse(r -> sendResult(res, r), // or in the case of non-JAX-RS method returning ParticipantStatus null.
                () -> res.status(Response.Status.GONE.getStatusCode()).send())).exceptionallyAccept(t -> sendError(lraId, req, res, t));
                break;
            case "forget":
                Single.<Optional<?>>empty().observeOn(exec).onCompleteResumeWithSingle(o -> participantService.invoke(fqdn, method, lraId, parentId, propagatedHeaders)).onComplete(res::send).onError(t -> sendError(lraId, req, res, t)).ignoreElement();
                break;
            default:
                LOGGER.severe(() -> "Unexpected non Jax-Rs LRA compensation type " + type + ": " + req.absoluteUri());
                res.status(404).send();
                break;
        }
    });
}
Also used : LRAResponse(org.eclipse.microprofile.lra.LRAResponse) LRA_HTTP_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) LRA_HTTP_ENDED_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) Supplier(java.util.function.Supplier) Level(java.util.logging.Level) Response(jakarta.ws.rs.core.Response) Map(java.util.Map) ServerResponse(io.helidon.webserver.ServerResponse) Single(io.helidon.common.reactive.Single) URI(java.net.URI) Service(io.helidon.webserver.Service) Reflected(io.helidon.common.Reflected) ExecutorService(java.util.concurrent.ExecutorService) LRA_HTTP_PARENT_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_PARENT_CONTEXT_HEADER) ParticipantStatus(org.eclipse.microprofile.lra.annotation.ParticipantStatus) Config(io.helidon.config.Config) PreDestroy(jakarta.annotation.PreDestroy) Logger(java.util.logging.Logger) RequestHeaders(io.helidon.webserver.RequestHeaders) Collectors(java.util.stream.Collectors) ServerRequest(io.helidon.webserver.ServerRequest) TimeUnit(java.util.concurrent.TimeUnit) LRAStatus(org.eclipse.microprofile.lra.annotation.LRAStatus) Optional(java.util.Optional) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) Inject(jakarta.inject.Inject) ThreadPoolSupplier(io.helidon.common.configurable.ThreadPoolSupplier) HttpRequest(io.helidon.common.http.HttpRequest) HttpRequest(io.helidon.common.http.HttpRequest) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) Optional(java.util.Optional) RequestHeaders(io.helidon.webserver.RequestHeaders) URI(java.net.URI)

Example 19 with Single

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

the class IdcsMtRoleMapperRxProvider method getGrantsFromServer.

/**
 * Get grants from IDCS server. The result is cached.
 *
 * @param idcsTenantId ID of the IDCS tenant
 * @param idcsAppName  Name of IDCS application
 * @param subject      subject to get grants for
 * @return optional list of grants from server
 */
protected Single<List<? extends Grant>> getGrantsFromServer(String idcsTenantId, String idcsAppName, 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(getAppToken(idcsTenantId, tracing)).flatMapSingle(maybeAppToken -> {
        if (maybeAppToken.isEmpty()) {
            return Single.error(new SecurityException("Application token not available"));
        }
        return Single.just(maybeAppToken.get());
    }).flatMapSingle(appToken -> {
        JsonObjectBuilder requestBuilder = JSON.createObjectBuilder().add("mappingAttributeValue", subjectName).add("subjectType", subjectType).add("appName", idcsAppName).add("includeMemberships", true);
        JsonArrayBuilder arrayBuilder = JSON.createArrayBuilder();
        arrayBuilder.add("urn:ietf:params:scim:schemas:oracle:idcs:Asserter");
        requestBuilder.add("schemas", arrayBuilder);
        Context parentContext = Contexts.context().orElseGet(Contexts::globalContext);
        Context childContext = Context.builder().parent(parentContext).build();
        tracing.findParent().ifPresent(childContext::register);
        WebClientRequestBuilder post = oidcConfig().generalWebClient().post().context(childContext).uri(multitenantEndpoints.assertEndpoint(idcsTenantId)).headers(it -> {
            it.add(Http.Header.AUTHORIZATION, "Bearer " + appToken);
            return it;
        });
        return processRoleRequest(post, requestBuilder.build(), subjectName);
    });
}
Also used : ProviderRequest(io.helidon.security.ProviderRequest) WebClient(io.helidon.webclient.WebClient) 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) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SecurityProvider(io.helidon.security.spi.SecurityProvider) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) TokenHandler(io.helidon.security.util.TokenHandler) Logger(java.util.logging.Logger) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Contexts(io.helidon.common.context.Contexts) Json(jakarta.json.Json) Objects(java.util.Objects) 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) Context(io.helidon.common.context.Context) 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 20 with Single

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

the class Main method startServer.

static Single<WebServer> startServer() {
    LogConfig.configureRuntime();
    Config config = Config.create();
    WebServer server = WebServer.builder(createRouting(config)).config(config.get("server")).addMediaSupport(JsonpSupport.create()).build();
    Single<WebServer> webserver = server.start();
    webserver.thenAccept(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!"));
    }).exceptionallyAccept(t -> {
        System.err.println("Startup failed: " + t.getMessage());
        t.printStackTrace(System.err);
    });
    return webserver;
}
Also used : JsonpSupport(io.helidon.media.jsonp.JsonpSupport) 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)

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