Search in sources :

Example 21 with Context

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

the class AccessLogSupportTest method testCustomFormat.

@Test
void testCustomFormat() {
    AccessLogSupport accessLog = AccessLogSupport.builder().add(TimestampLogEntry.builder().formatter(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")).build()).add(HeaderLogEntry.create("Referer")).build();
    ServerRequest request = mock(ServerRequest.class);
    Context context = Context.create();
    when(request.remoteAddress()).thenReturn(REMOTE_IP);
    when(request.context()).thenReturn(context);
    when(request.method()).thenReturn(Http.Method.PUT);
    HttpRequest.Path path = mock(HttpRequest.Path.class);
    when(path.toRawString()).thenReturn(PATH);
    when(request.path()).thenReturn(path);
    when(request.version()).thenReturn(Http.Version.V1_1);
    RequestHeaders headers = mock(RequestHeaders.class);
    when(headers.all("Referer")).thenReturn(Arrays.asList("first", "second"));
    when(request.headers()).thenReturn(headers);
    ServerResponse response = mock(ServerResponse.class);
    when(response.status()).thenReturn(Http.Status.I_AM_A_TEAPOT);
    String logRecord = accessLog.createLogRecord(request, response, BEGIN_TIME, 0L, END_TIME, TIME_TAKEN_MICROS * 1000);
    String expected = "20071203101530 \"first,second\"";
    assertThat(logRecord, is(expected));
}
Also used : Context(io.helidon.common.context.Context) HttpRequest(io.helidon.common.http.HttpRequest) ServerResponse(io.helidon.webserver.ServerResponse) ServerRequest(io.helidon.webserver.ServerRequest) RequestHeaders(io.helidon.webserver.RequestHeaders) Test(org.junit.jupiter.api.Test)

Example 22 with Context

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

the class AccessLogSupportTest method testCommonFormat.

@Test
void testCommonFormat() {
    AccessLogSupport accessLog = AccessLogSupport.builder().commonLogFormat().build();
    ServerRequest request = mock(ServerRequest.class);
    Context context = Context.create();
    when(request.remoteAddress()).thenReturn(REMOTE_IP);
    when(request.context()).thenReturn(context);
    when(request.method()).thenReturn(Http.Method.PUT);
    HttpRequest.Path path = mock(HttpRequest.Path.class);
    when(path.toRawString()).thenReturn(PATH);
    when(request.path()).thenReturn(path);
    when(request.version()).thenReturn(Http.Version.V1_1);
    ServerResponse response = mock(ServerResponse.class);
    when(response.status()).thenReturn(Http.Status.I_AM_A_TEAPOT);
    AccessLogContext accessLogContext = mock(AccessLogContext.class);
    when(accessLogContext.requestDateTime()).thenReturn(BEGIN_TIME);
    String expectedTimestamp = TimestampLogEntry.create().doApply(accessLogContext);
    String logRecord = accessLog.createLogRecord(request, response, BEGIN_TIME, 0L, END_TIME, TIME_TAKEN_MICROS * 1000);
    // 192.168.0.104 - [18/Jun/2019:23:10:44 +0200] "GET /greet/test HTTP/1.1" 200 55 2248
    String expected = REMOTE_IP + " - - " + expectedTimestamp + " \"" + METHOD + " " + PATH + " " + HTTP_VERSION + "\" " + STATUS_CODE + " " + CONTENT_LENGTH;
    assertThat(logRecord, is(expected));
}
Also used : Context(io.helidon.common.context.Context) HttpRequest(io.helidon.common.http.HttpRequest) ServerResponse(io.helidon.webserver.ServerResponse) ServerRequest(io.helidon.webserver.ServerRequest) Test(org.junit.jupiter.api.Test)

Example 23 with Context

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

the class SecurityHandler method processSecurity.

private void processSecurity(SecurityContext securityContext, ServerRequest req, ServerResponse res) {
    // authentication and authorization
    // start security span
    SecurityTracing tracing = SecurityTracing.get();
    tracing.securityContext(securityContext);
    // extract headers
    extractQueryParams(securityContext, req);
    securityContext.endpointConfig(securityContext.endpointConfig().derive().configMap(configMap).customObjects(customObjects.orElse(new ClassToInstanceStore<>())).build());
    Optional<Context> context = Contexts.context();
    processAuthentication(res, securityContext, tracing.atnTracing()).thenCompose(atnResult -> {
        if (atnResult.proceed) {
            // authentication was OK or disabled, we should continue
            return processAuthorization(req, res, securityContext, tracing.atzTracing());
        } else {
            // authentication told us to stop processing
            return CompletableFuture.completedFuture(AtxResult.STOP);
        }
    }).thenAccept(atzResult -> {
        if (atzResult.proceed) {
            // authorization was OK, we can continue processing
            tracing.logProceed();
            tracing.finish();
            // propagate context information in call to next
            context.ifPresentOrElse(c -> Contexts.runInContext(c, (Runnable) req::next), req::next);
        } else {
            tracing.logDeny();
            tracing.finish();
        }
    }).exceptionally(throwable -> {
        tracing.error(throwable);
        LOGGER.log(Level.SEVERE, "Unexpected exception during security processing", throwable);
        abortRequest(res, null, Http.Status.INTERNAL_SERVER_ERROR_500.code(), Map.of());
        return null;
    });
    // auditing
    res.whenSent().thenAccept(sr -> processAudit(req, sr, securityContext));
}
Also used : Context(io.helidon.common.context.Context) SecurityContext(io.helidon.security.SecurityContext) SpanContext(io.opentracing.SpanContext) Arrays(java.util.Arrays) Security(io.helidon.security.Security) AtnTracing(io.helidon.security.integration.common.AtnTracing) Context(io.helidon.common.context.Context) SecurityRequestBuilder(io.helidon.security.SecurityRequestBuilder) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Level(java.util.logging.Level) AuditParam.plain(io.helidon.security.AuditEvent.AuditParam.plain) HashSet(java.util.HashSet) ClassToInstanceStore(io.helidon.security.ClassToInstanceStore) SecurityRequest(io.helidon.security.SecurityRequest) AuditEvent(io.helidon.security.AuditEvent) Map(java.util.Map) ServerResponse(io.helidon.webserver.ServerResponse) Subject(io.helidon.security.Subject) AtzTracing(io.helidon.security.integration.common.AtzTracing) LinkedList(java.util.LinkedList) Http(io.helidon.common.http.Http) SecurityTracing(io.helidon.security.integration.common.SecurityTracing) AuthorizationResponse(io.helidon.security.AuthorizationResponse) Config(io.helidon.config.Config) Collection(java.util.Collection) Set(java.util.Set) SecurityContext(io.helidon.security.SecurityContext) TokenHandler(io.helidon.security.util.TokenHandler) Logger(java.util.logging.Logger) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Contexts(io.helidon.common.context.Contexts) ServerRequest(io.helidon.webserver.ServerRequest) SpanContext(io.opentracing.SpanContext) Consumer(java.util.function.Consumer) SecurityResponse(io.helidon.security.SecurityResponse) List(java.util.List) ResponseHeaders(io.helidon.webserver.ResponseHeaders) CompletionStage(java.util.concurrent.CompletionStage) SecurityClientBuilder(io.helidon.security.SecurityClientBuilder) Handler(io.helidon.webserver.Handler) Optional(java.util.Optional) Collections(java.util.Collections) QueryParamMapping(io.helidon.security.QueryParamMapping) SecurityAuditEvent(io.helidon.security.internal.SecurityAuditEvent) HttpRequest(io.helidon.common.http.HttpRequest) SecurityTracing(io.helidon.security.integration.common.SecurityTracing) ClassToInstanceStore(io.helidon.security.ClassToInstanceStore)

Example 24 with Context

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

the class AbstractTracingFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    if (!tracingEnabled(requestContext)) {
        return;
    }
    Context context = Contexts.context().orElseThrow(() -> new IllegalStateException("Context must be available in Jersey"));
    String spanName = spanName(requestContext);
    SpanTracingConfig spanConfig = TracingConfigUtil.spanConfig(ClientTracingFilter.JAX_RS_TRACING_COMPONENT, spanName, context);
    if (spanConfig.enabled()) {
        spanName = spanConfig.newName().orElse(spanName);
        Tracer tracer = context.get(Tracer.class).orElseGet(GlobalTracer::get);
        SpanContext parentSpan = context.get(ServerRequest.class, SpanContext.class).orElseGet(() -> context.get(SpanContext.class).orElse(null));
        Tracer.SpanBuilder spanBuilder = tracer.buildSpan(spanName).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).withTag(Tags.HTTP_METHOD.getKey(), requestContext.getMethod()).withTag(Tags.HTTP_URL.getKey(), url(requestContext)).withTag(Tags.COMPONENT.getKey(), "jaxrs");
        if (null != parentSpan) {
            spanBuilder.asChildOf(parentSpan);
        }
        configureSpan(spanBuilder);
        Span span = spanBuilder.start();
        Scope spanScope = tracer.scopeManager().activate(span);
        context.register(span);
        context.register(spanScope);
        context.register(ClientTracingFilter.class, span.context());
        requestContext.setProperty(SPAN_PROPERTY, span);
        requestContext.setProperty(SPAN_SCOPE_PROPERTY, spanScope);
        if (context.get(TracingContext.class).isEmpty()) {
            context.register(TracingContext.create(tracer, requestContext.getHeaders()));
        }
        context.get(TracingContext.class).ifPresent(tctx -> tctx.parentSpan(span.context()));
        if (null == parentSpan) {
            // register current span as the parent span for other (unless already exists)
            context.register(span.context());
        }
    }
}
Also used : Context(io.helidon.common.context.Context) TracingContext(io.helidon.tracing.jersey.client.internal.TracingContext) SpanContext(io.opentracing.SpanContext) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) ContainerResponseContext(jakarta.ws.rs.container.ContainerResponseContext) TracingContext(io.helidon.tracing.jersey.client.internal.TracingContext) SpanContext(io.opentracing.SpanContext) Scope(io.opentracing.Scope) Tracer(io.opentracing.Tracer) GlobalTracer(io.opentracing.util.GlobalTracer) GlobalTracer(io.opentracing.util.GlobalTracer) ServerRequest(io.helidon.webserver.ServerRequest) Span(io.opentracing.Span) SpanTracingConfig(io.helidon.tracing.config.SpanTracingConfig)

Example 25 with Context

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

the class HelloBean method getHelloAsync.

/**
 * Runs via FT async thread.
 *
 * @return Hello string.
 */
@Asynchronous
public CompletionStage<String> getHelloAsync() {
    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 CompletableFuture.completedFuture("Hello World");
}
Also used : Context(io.helidon.common.context.Context) Asynchronous(org.eclipse.microprofile.faulttolerance.Asynchronous)

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