Search in sources :

Example 6 with Context

use of io.helidon.common.context.Context in project helidon by oracle.

the class Slf4jMdcTest method testThreadPropagationWithEmptyMdc.

@Test
public void testThreadPropagationWithEmptyMdc() {
    Context context = Context.create();
    ExecutorService executor = Contexts.wrap(Executors.newFixedThreadPool(1));
    Contexts.runInContext(context, () -> {
        try {
            Boolean value = executor.submit(new TestEmptyMdc()).get();
            assertThat(value, is(true));
        } catch (Exception e) {
            throw new ExecutorException("failed to execute", e);
        }
    });
}
Also used : Context(io.helidon.common.context.Context) ExecutorException(io.helidon.common.context.ExecutorException) ExecutorService(java.util.concurrent.ExecutorService) ExecutorException(io.helidon.common.context.ExecutorException) Test(org.junit.jupiter.api.Test)

Example 7 with Context

use of io.helidon.common.context.Context in project helidon by oracle.

the class MpTracingInterceptor method locateParent.

private Optional<SpanContext> locateParent() {
    // first check if we are in an active span
    Span active = tracer.activeSpan();
    if (null != active) {
        // in case there is an active span (such as from JAX-RS resource or from another bean), use it as a parent
        return Optional.of(active.context());
    }
    Optional<Context> context = Contexts.context();
    return context.flatMap(ctx -> ctx.get(SpanContext.class)).or(() -> context.flatMap(ctx -> ctx.get(ClientTracingFilter.class, SpanContext.class)));
}
Also used : Context(io.helidon.common.context.Context) InvocationContext(jakarta.interceptor.InvocationContext) SpanContext(io.opentracing.SpanContext) Traced(org.eclipse.microprofile.opentracing.Traced) Tracer(io.opentracing.Tracer) Member(java.lang.reflect.Member) Context(io.helidon.common.context.Context) GlobalTracer(io.opentracing.util.GlobalTracer) InvocationContext(jakarta.interceptor.InvocationContext) Contexts(io.helidon.common.context.Contexts) SpanContext(io.opentracing.SpanContext) Path(jakarta.ws.rs.Path) Map(java.util.Map) Optional(java.util.Optional) Span(io.opentracing.Span) AroundInvoke(jakarta.interceptor.AroundInvoke) Interceptor(jakarta.interceptor.Interceptor) Priority(jakarta.annotation.Priority) Scope(io.opentracing.Scope) Inject(jakarta.inject.Inject) Method(java.lang.reflect.Method) AnnotatedElement(java.lang.reflect.AnnotatedElement) ClientTracingFilter(io.helidon.tracing.jersey.client.ClientTracingFilter) Span(io.opentracing.Span)

Example 8 with Context

use of io.helidon.common.context.Context in project helidon by oracle.

the class ClientSecurityFilter method doFilter.

private void doFilter(ClientRequestContext requestContext) {
    // find the context - if not cannot propagate
    Optional<SecurityContext> securityContext = findContext(requestContext);
    if (securityContext.isPresent()) {
        outboundSecurity(requestContext, securityContext.get());
    } else {
        LOGGER.finest("Security context not available, using empty one. You can define it using " + "property \"" + ClientSecurity.PROPERTY_CONTEXT + "\" on request");
        // use current context, or create a new one if we run outside of Helidon context
        Context context = Contexts.context().orElseGet(() -> Context.builder().id("security-" + CONTEXT_COUNTER.incrementAndGet()).build());
        // create a new security context for current request (not authenticated)
        Optional<SecurityContext> newSecurityContext = context.get(Security.class).map(it -> it.createContext(context.id()));
        if (newSecurityContext.isPresent()) {
            // run in the context we obtained above with the new security context
            // we may still propagate security information (such as when we explicitly configure outbound
            // security in outbound target of a provider
            Contexts.runInContext(context, () -> outboundSecurity(requestContext, newSecurityContext.get()));
        } else {
            // we cannot do anything - security is not available in global or current context, cannot propagate
            LOGGER.finest("Security is not available in global or current context, cannot propagate identity.");
        }
    }
}
Also used : Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) ClientRequestContext(jakarta.ws.rs.client.ClientRequestContext) SecurityContext(io.helidon.security.SecurityContext) Security(io.helidon.security.Security)

Example 9 with Context

use of io.helidon.common.context.Context 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 10 with Context

use of io.helidon.common.context.Context in project helidon by oracle.

the class HelloBean method getHello.

/**
 * Runs in Jersey/Helidon thread.
 *
 * @return Hello string.
 */
public String getHello() {
    Context context = Contexts.context().orElse(null);
    Objects.requireNonNull(context);
    // application scoped context
    Objects.requireNonNull(context.get(RegistryFactory.class).orElse(null));
    // request scoped context
    Objects.requireNonNull(context.get(MyMessage.class).orElse(null));
    return "Hello World";
}
Also used : Context(io.helidon.common.context.Context)

Aggregations

Context (io.helidon.common.context.Context)32 Test (org.junit.jupiter.api.Test)14 Contexts (io.helidon.common.context.Contexts)8 WebClient (io.helidon.webclient.WebClient)8 Optional (java.util.Optional)7 Http (io.helidon.common.http.Http)6 Single (io.helidon.common.reactive.Single)6 Config (io.helidon.config.Config)6 ServerRequest (io.helidon.webserver.ServerRequest)6 SpanContext (io.opentracing.SpanContext)6 Logger (java.util.logging.Logger)6 HttpRequest (io.helidon.common.http.HttpRequest)5 SecurityContext (io.helidon.security.SecurityContext)5 ServerResponse (io.helidon.webserver.ServerResponse)5 List (java.util.List)5 Map (java.util.Map)5 WebClientResponse (io.helidon.webclient.WebClientResponse)4 Span (io.opentracing.Span)4 Tracer (io.opentracing.Tracer)4 Collections (java.util.Collections)4