Search in sources :

Example 1 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class ClientMain method main.

/**
 * Executes WebClient examples.
 *
 * If no argument provided it will take server port from configuration server.port.
 *
 * User can override port from configuration by main method parameter with the specific port.
 *
 * @param args main method
 */
public static void main(String[] args) {
    Config config = Config.create();
    String url;
    if (args.length == 0) {
        ConfigValue<Integer> port = config.get("server.port").asInt();
        if (!port.isPresent() || port.get() == -1) {
            throw new IllegalStateException("Unknown port! Please specify port as a main method parameter " + "or directly to config server.port");
        }
        url = "http://localhost:" + port.get() + "/greet";
    } else {
        url = "http://localhost:" + Integer.parseInt(args[0]) + "/greet";
    }
    WebClient webClient = WebClient.builder().baseUri(url).config(config.get("client")).addMediaSupport(JsonpSupport.create()).build();
    performPutMethod(webClient).flatMapSingle(it -> performGetMethod(webClient)).flatMapSingle(it -> followRedirects(webClient)).flatMapSingle(it -> getResponseAsAnJsonObject(webClient)).flatMapSingle(it -> saveResponseToFile(webClient)).flatMapSingle(it -> clientMetricsExample(url, config)).await();
}
Also used : Arrays(java.util.Arrays) WebClient(io.helidon.webclient.WebClient) WebClientService(io.helidon.webclient.spi.WebClientService) Files(java.nio.file.Files) IoMulti(io.helidon.common.reactive.IoMulti) Config(io.helidon.config.Config) WebClientResponse(io.helidon.webclient.WebClientResponse) DataChunk(io.helidon.common.http.DataChunk) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) IOException(java.io.IOException) ConfigValue(io.helidon.config.ConfigValue) Json(jakarta.json.Json) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Counter(org.eclipse.microprofile.metrics.Counter) Paths(java.nio.file.Paths) JsonObject(jakarta.json.JsonObject) Single(io.helidon.common.reactive.Single) MetricRegistry(org.eclipse.microprofile.metrics.MetricRegistry) Http(io.helidon.common.http.Http) Path(java.nio.file.Path) Collections(java.util.Collections) RegistryFactory(io.helidon.metrics.RegistryFactory) WebClientMetrics(io.helidon.webclient.metrics.WebClientMetrics) Config(io.helidon.config.Config) WebClient(io.helidon.webclient.WebClient)

Example 2 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class Main method routingAsFilter.

/**
 * All routing rules (routes) are evaluated in a definition order. The {@link Handler} assigned with the first valid route
 * for given request is called. It is a responsibility of each handler to process in one of the following ways:
 * <ul>
 *     <li>Respond using one of {@link io.helidon.webserver.ServerResponse#send() ServerResponse.send(...)} method.</li>
 *     <li>Continue to next valid route using {@link io.helidon.webserver.ServerRequest#next() ServerRequest.next()} method.
 *     <i>It is possible to define filtering handlers.</i></li>
 * </ul>
 * <p>
 * If no valid {@link Handler} is found then routing respond by {@code HTTP 404} code.
 * <p>
 * If selected {@link Handler} doesn't process request than the request <b>stacks</b>!
 * <p>
 * <b>Blocking operations:</b><br>
 * For performance reason, {@link Handler} can be called directly by a selector thread. It is not good idea to block
 * such thread. If request must be processed by a blocking operation then such processing should be deferred to another
 * thread.
 */
public void routingAsFilter() {
    Routing routing = Routing.builder().any((req, res) -> {
        System.out.println(req.method() + " " + req.path());
        // Filters are just routing handlers which calls next()
        req.next();
    }).post("/post-endpoint", (req, res) -> res.status(Http.Status.CREATED_201).send()).get("/get-endpoint", (req, res) -> res.status(Http.Status.NO_CONTENT_204).send("Hello World!")).build();
    startServer(routing);
}
Also used : JerseySupport(io.helidon.webserver.jersey.JerseySupport) DataChunk(io.helidon.common.http.DataChunk) RequestPredicate(io.helidon.webserver.RequestPredicate) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) MediaContext(io.helidon.media.common.MediaContext) MessageBodyReader(io.helidon.media.common.MessageBodyReader) InvocationTargetException(java.lang.reflect.InvocationTargetException) MediaType(io.helidon.common.http.MediaType) Json(jakarta.json.Json) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Handler(io.helidon.webserver.Handler) StaticContentSupport(io.helidon.webserver.staticcontent.StaticContentSupport) Modifier(java.lang.reflect.Modifier) Parameters(io.helidon.common.http.Parameters) HttpException(io.helidon.webserver.HttpException) WebServer(io.helidon.webserver.WebServer) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) Method(java.lang.reflect.Method) Collections(java.util.Collections) Routing(io.helidon.webserver.Routing)

Example 3 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class Main method errorHandling.

/**
 * Request processing can cause error represented by {@link Throwable}. It is possible to register custom
 * {@link io.helidon.webserver.ErrorHandler ErrorHandlers} for specific processing.
 * <p>
 * If error is not processed by a custom {@link io.helidon.webserver.ErrorHandler ErrorHandler} than default one is used.
 * It respond with <i>HTTP 500 code</i> unless error is not represented
 * by {@link HttpException HttpException}. In such case it reflects its content.
 */
public void errorHandling() {
    Routing routing = Routing.builder().post("/compute", Handler.create(String.class, (req, res, str) -> {
        int result = 100 / Integer.parseInt(str);
        res.send(String.valueOf("100 / " + str + " = " + result));
    })).error(Throwable.class, (req, res, ex) -> {
        ex.printStackTrace(System.out);
        req.next();
    }).error(NumberFormatException.class, (req, res, ex) -> res.status(Http.Status.BAD_REQUEST_400).send()).error(ArithmeticException.class, (req, res, ex) -> res.status(Http.Status.PRECONDITION_FAILED_412).send()).build();
    startServer(routing);
}
Also used : JerseySupport(io.helidon.webserver.jersey.JerseySupport) DataChunk(io.helidon.common.http.DataChunk) RequestPredicate(io.helidon.webserver.RequestPredicate) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) MediaContext(io.helidon.media.common.MediaContext) MessageBodyReader(io.helidon.media.common.MessageBodyReader) InvocationTargetException(java.lang.reflect.InvocationTargetException) MediaType(io.helidon.common.http.MediaType) Json(jakarta.json.Json) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Handler(io.helidon.webserver.Handler) StaticContentSupport(io.helidon.webserver.staticcontent.StaticContentSupport) Modifier(java.lang.reflect.Modifier) Parameters(io.helidon.common.http.Parameters) HttpException(io.helidon.webserver.HttpException) WebServer(io.helidon.webserver.WebServer) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) Method(java.lang.reflect.Method) Collections(java.util.Collections) Routing(io.helidon.webserver.Routing)

Example 4 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class RestApiBase method requestJsonPayload.

/**
 * Create a supplier for a response with JSON request.
 * Defaults to "{@code () -> clientRequest.submit(jsonObject)}".
 * Also configures content type and accept headers.
 *
 * @param path path requested
 * @param request API request
 * @param method HTTP method
 * @param requestId ID of this request
 * @param requestBuilder {@link io.helidon.webclient.WebClient} request builder
 * @param jsonObject JSON object that should be sent as a request entity
 *
 * @return supplier of a web client response
 */
protected Supplier<Single<WebClientResponse>> requestJsonPayload(String path, ApiRequest<?> request, Http.RequestMethod method, String requestId, WebClientRequestBuilder requestBuilder, JsonObject jsonObject) {
    requestBuilder.accept(request.responseMediaType().orElse(MediaType.APPLICATION_JSON));
    requestBuilder.contentType(request.requestMediaType().orElse(MediaType.APPLICATION_JSON));
    AtomicBoolean updated = new AtomicBoolean();
    return () -> {
        // we should only update request builder once - if a retry is done, it should not be reset
        if (updated.compareAndSet(false, true)) {
            Single<WebClientRequestBuilder> res = updateRequestBuilder(requestBuilder, path, request, method, requestId, jsonObject);
            return res.flatMapSingle(it -> it.submit(jsonObject));
        } else {
            return requestBuilder.submit(jsonObject);
        }
    };
}
Also used : JsonWriterFactory(jakarta.json.JsonWriterFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) JsonReaderFactory(jakarta.json.JsonReaderFactory) DataChunk(io.helidon.common.http.DataChunk) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Supplier(java.util.function.Supplier) MediaType(io.helidon.common.http.MediaType) Flow(java.util.concurrent.Flow) JsonObject(jakarta.json.JsonObject) Single(io.helidon.common.reactive.Single) Http(io.helidon.common.http.Http) Multi(io.helidon.common.reactive.Multi) FtHandler(io.helidon.faulttolerance.FtHandler) Collector(io.helidon.common.reactive.Collector) UUID(java.util.UUID) Logger(java.util.logging.Logger) WebClientRequestHeaders(io.helidon.webclient.WebClientRequestHeaders) Contexts(io.helidon.common.context.Contexts) SpanContext(io.opentracing.SpanContext) StringReader(java.io.StringReader) Optional(java.util.Optional) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Single(io.helidon.common.reactive.Single)

Example 5 with Http

use of io.helidon.common.http.Http in project helidon by oracle.

the class RestApiBase method requestBytesPayload.

/**
 * Create a supplier for a response with publisher request.
 * Defaults to "{@code () -> clientRequest.submit(publisher)}".
 * Also configures content type and accept headers.
 *
 * @param path path requested
 * @param request API request
 * @param method HTTP method
 * @param requestId ID of this request
 * @param requestBuilder {@link io.helidon.webclient.WebClient} request builder
 * @param publisher publisher to be used as request entity
 *
 * @return supplier of a web client response
 */
protected Supplier<Single<WebClientResponse>> requestBytesPayload(String path, ApiRequest<?> request, Http.RequestMethod method, String requestId, WebClientRequestBuilder requestBuilder, Flow.Publisher<DataChunk> publisher) {
    requestBuilder.accept(request.responseMediaType().orElse(MediaType.APPLICATION_JSON));
    requestBuilder.contentType(request.requestMediaType().orElse(MediaType.APPLICATION_OCTET_STREAM));
    AtomicBoolean updated = new AtomicBoolean();
    return () -> {
        if (updated.compareAndSet(false, true)) {
            return updateRequestBuilderBytesPayload(requestBuilder, path, request, method, requestId).flatMapSingle(it -> it.submit(publisher));
        } else {
            return requestBuilder.submit(publisher);
        }
    };
}
Also used : JsonWriterFactory(jakarta.json.JsonWriterFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) JsonReaderFactory(jakarta.json.JsonReaderFactory) DataChunk(io.helidon.common.http.DataChunk) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Supplier(java.util.function.Supplier) MediaType(io.helidon.common.http.MediaType) Flow(java.util.concurrent.Flow) JsonObject(jakarta.json.JsonObject) Single(io.helidon.common.reactive.Single) Http(io.helidon.common.http.Http) Multi(io.helidon.common.reactive.Multi) FtHandler(io.helidon.faulttolerance.FtHandler) Collector(io.helidon.common.reactive.Collector) UUID(java.util.UUID) Logger(java.util.logging.Logger) WebClientRequestHeaders(io.helidon.webclient.WebClientRequestHeaders) Contexts(io.helidon.common.context.Contexts) SpanContext(io.opentracing.SpanContext) StringReader(java.io.StringReader) Optional(java.util.Optional) WebClientRequestBuilder(io.helidon.webclient.WebClientRequestBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Aggregations

Http (io.helidon.common.http.Http)27 WebClient (io.helidon.webclient.WebClient)16 DataChunk (io.helidon.common.http.DataChunk)12 Config (io.helidon.config.Config)12 WebClientResponse (io.helidon.webclient.WebClientResponse)12 Routing (io.helidon.webserver.Routing)11 WebServer (io.helidon.webserver.WebServer)10 Test (org.junit.jupiter.api.Test)10 MediaType (io.helidon.common.http.MediaType)9 Optional (java.util.Optional)9 Single (io.helidon.common.reactive.Single)8 WebClientRequestBuilder (io.helidon.webclient.WebClientRequestBuilder)8 Logger (java.util.logging.Logger)8 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)8 Json (jakarta.json.Json)7 JsonBuilderFactory (jakarta.json.JsonBuilderFactory)7 Collections (java.util.Collections)7 JsonpSupport (io.helidon.media.jsonp.JsonpSupport)6 SecurityContext (io.helidon.security.SecurityContext)6 JsonObject (jakarta.json.JsonObject)5