Search in sources :

Example 1 with RequestHeaders

use of io.helidon.webserver.RequestHeaders in project metro-jax-ws by eclipse-ee4j.

the class WSUtils method getBaseAddress.

static String getBaseAddress(ServerRequest req) {
    /* Computes the Endpoint's address from the request.
         * Uses "X-Forwarded-Proto", "X-Forwarded-Host" and "Host" headers
         * so that it has correct address(IP address or someother hostname)
         * through which the application reached the endpoint.
         */
    StringBuilder buf = new StringBuilder();
    RequestHeaders headers = req.headers();
    String protocol = headers.first("X-Forwarded-Proto").orElse(req.isSecure() ? "https" : "http");
    // An X-Forwarded-Host header would mean we are behind a reverse
    // proxy. Use it as host address if found, or the Host header
    // otherwise.
    String host = headers.first("X-Forwarded-Host").orElse(headers.first("Host").orElse(req.localAddress() + ":" + req.localPort()));
    buf.append(protocol);
    buf.append("://");
    buf.append(host);
    buf.append(basePath(req.path()));
    return buf.toString();
}
Also used : RequestHeaders(io.helidon.webserver.RequestHeaders)

Example 2 with RequestHeaders

use of io.helidon.webserver.RequestHeaders 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 3 with RequestHeaders

use of io.helidon.webserver.RequestHeaders in project helidon by oracle.

the class FileBasedContentHandler method detectType.

private MediaType detectType(String fileName, RequestHeaders requestHeaders) {
    Objects.requireNonNull(fileName);
    Objects.requireNonNull(requestHeaders);
    // then check the type is accepted by the request
    return findCustomMediaType(fileName).or(() -> MediaTypes.detectType(fileName).map(MediaType::parse)).map(it -> {
        if (requestHeaders.isAccepted(it)) {
            return it;
        }
        throw new HttpException("Media type " + it + " is not accepted by request", Http.Status.UNSUPPORTED_MEDIA_TYPE_415);
    }).orElseGet(() -> {
        List<MediaType> acceptedTypes = requestHeaders.acceptedTypes();
        if (acceptedTypes.isEmpty()) {
            return MediaType.APPLICATION_OCTET_STREAM;
        } else {
            return acceptedTypes.iterator().next();
        }
    });
}
Also used : MessageBodyWriter(io.helidon.media.common.MessageBodyWriter) DefaultMediaSupport(io.helidon.media.common.DefaultMediaSupport) Files(java.nio.file.Files) MediaTypes(io.helidon.common.media.type.MediaTypes) IOException(java.io.IOException) Instant(java.time.Instant) Logger(java.util.logging.Logger) RequestHeaders(io.helidon.webserver.RequestHeaders) MediaType(io.helidon.common.http.MediaType) ServerRequest(io.helidon.webserver.ServerRequest) Objects(java.util.Objects) List(java.util.List) ResponseHeaders(io.helidon.webserver.ResponseHeaders) Map(java.util.Map) HttpException(io.helidon.webserver.HttpException) ServerResponse(io.helidon.webserver.ServerResponse) Optional(java.util.Optional) Http(io.helidon.common.http.Http) Path(java.nio.file.Path) MediaType(io.helidon.common.http.MediaType) HttpException(io.helidon.webserver.HttpException)

Example 4 with RequestHeaders

use of io.helidon.webserver.RequestHeaders in project helidon by oracle.

the class StaticContentHandlerTest method etag_InNonMatch_Accept.

@Test
void etag_InNonMatch_Accept() {
    RequestHeaders req = mock(RequestHeaders.class);
    when(req.values(Http.Header.IF_NONE_MATCH)).thenReturn(List.of("\"ccc\"", "W/\"aaa\""));
    when(req.values(Http.Header.IF_MATCH)).thenReturn(Collections.emptyList());
    ResponseHeaders res = mock(ResponseHeaders.class);
    assertHttpException(() -> StaticContentHandler.processEtag("aaa", req, res), Http.Status.NOT_MODIFIED_304);
    verify(res).put(Http.Header.ETAG, "\"aaa\"");
}
Also used : RequestHeaders(io.helidon.webserver.RequestHeaders) ResponseHeaders(io.helidon.webserver.ResponseHeaders) Test(org.junit.jupiter.api.Test)

Example 5 with RequestHeaders

use of io.helidon.webserver.RequestHeaders in project helidon by oracle.

the class StaticContentHandlerTest method ifUnmodifySince_NotAccept.

@Test
void ifUnmodifySince_NotAccept() {
    ZonedDateTime modified = ZonedDateTime.now();
    RequestHeaders req = mock(RequestHeaders.class);
    Mockito.doReturn(Optional.of(modified.minusSeconds(60))).when(req).ifUnmodifiedSince();
    Mockito.doReturn(Optional.empty()).when(req).ifModifiedSince();
    ResponseHeaders res = mock(ResponseHeaders.class);
    assertHttpException(() -> StaticContentHandler.processModifyHeaders(modified.toInstant(), req, res), Http.Status.PRECONDITION_FAILED_412);
}
Also used : ZonedDateTime(java.time.ZonedDateTime) RequestHeaders(io.helidon.webserver.RequestHeaders) ResponseHeaders(io.helidon.webserver.ResponseHeaders) Test(org.junit.jupiter.api.Test)

Aggregations

RequestHeaders (io.helidon.webserver.RequestHeaders)12 ResponseHeaders (io.helidon.webserver.ResponseHeaders)9 Test (org.junit.jupiter.api.Test)9 ZonedDateTime (java.time.ZonedDateTime)4 ServerRequest (io.helidon.webserver.ServerRequest)3 ServerResponse (io.helidon.webserver.ServerResponse)3 HttpRequest (io.helidon.common.http.HttpRequest)2 Map (java.util.Map)2 Optional (java.util.Optional)2 Logger (java.util.logging.Logger)2 Reflected (io.helidon.common.Reflected)1 ThreadPoolSupplier (io.helidon.common.configurable.ThreadPoolSupplier)1 Context (io.helidon.common.context.Context)1 Http (io.helidon.common.http.Http)1 MediaType (io.helidon.common.http.MediaType)1 MediaTypes (io.helidon.common.media.type.MediaTypes)1 Single (io.helidon.common.reactive.Single)1 Config (io.helidon.config.Config)1 PropagatedHeaders (io.helidon.lra.coordinator.client.PropagatedHeaders)1 DefaultMediaSupport (io.helidon.media.common.DefaultMediaSupport)1