Search in sources :

Example 21 with DataChunk

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

the class ClientMain method saveResponseToFile.

static Single<Void> saveResponseToFile(WebClient webClient) {
    // We have to create file subscriber first. This subscriber will save the content of the response to the file.
    Path file = Paths.get("test.txt");
    try {
        Files.deleteIfExists(file);
        Files.createFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Downloading server response to file: " + file);
    return webClient.get().request().map(WebClientResponse::content).flatMapSingle(content -> content.map(DataChunk::data).flatMapIterable(Arrays::asList).to(IoMulti.writeToFile(file).build())).peek(path -> System.out.println("Download complete!"));
}
Also used : Path(java.nio.file.Path) 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) WebClientResponse(io.helidon.webclient.WebClientResponse) DataChunk(io.helidon.common.http.DataChunk) IOException(java.io.IOException)

Example 22 with DataChunk

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

the class WebClientRequestBuilderImpl method invoke.

private Single<WebClientResponse> invoke(Flow.Publisher<DataChunk> requestEntity) {
    finalUri = prepareFinalURI();
    if (requestId == null) {
        requestId = REQUEST_NUMBER.incrementAndGet();
    }
    // LOGGER.finest(() -> "(client reqID: " + requestId + ") Request final URI: " + uri);
    CompletableFuture<WebClientServiceRequest> sent = new CompletableFuture<>();
    CompletableFuture<WebClientServiceResponse> responseReceived = new CompletableFuture<>();
    CompletableFuture<WebClientServiceResponse> complete = new CompletableFuture<>();
    WebClientServiceRequest completedRequest = new WebClientServiceRequestImpl(this, sent, responseReceived, complete);
    CompletionStage<WebClientServiceRequest> rcs = CompletableFuture.completedFuture(completedRequest);
    for (WebClientService service : services) {
        rcs = rcs.thenCompose(service::request).thenApply(servReq -> {
            finalUri = recreateURI(servReq);
            return servReq;
        });
    }
    Single<WebClientResponse> single = Single.create(rcs.thenCompose(serviceRequest -> {
        URI requestUri = relativizeNoProxy(finalUri, proxy, configuration.relativeUris());
        requestId = serviceRequest.requestId();
        HttpHeaders headers = toNettyHttpHeaders();
        DefaultHttpRequest request = new DefaultHttpRequest(toNettyHttpVersion(httpVersion), toNettyMethod(method), requestUri.toASCIIString(), headers);
        boolean keepAlive = HttpUtil.isKeepAlive(request);
        requestConfiguration = RequestConfiguration.builder(finalUri).update(configuration).followRedirects(followRedirects).clientServiceRequest(serviceRequest).readerContext(readerContext).writerContext(writerContext).connectTimeout(connectTimeout).readTimeout(readTimeout).services(services).context(context).proxy(proxy).keepAlive(keepAlive).requestId(requestId).build();
        WebClientRequestImpl clientRequest = new WebClientRequestImpl(this);
        CompletableFuture<WebClientResponse> result = new CompletableFuture<>();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventGroup).channel(NioSocketChannel.class).handler(new NettyClientInitializer(requestConfiguration)).option(ChannelOption.SO_KEEPALIVE, keepAlive).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis());
        ChannelFuture channelFuture = keepAlive ? obtainChannelFuture(requestConfiguration, bootstrap) : bootstrap.connect(finalUri.getHost(), finalUri.getPort());
        channelFuture.addListener((ChannelFutureListener) future -> {
            if (LOGGER.isLoggable(Level.FINEST)) {
                LOGGER.finest(() -> "(client reqID: " + requestId + ") " + "Channel hashcode -> " + channelFuture.channel().hashCode());
            }
            channelFuture.channel().attr(REQUEST).set(clientRequest);
            channelFuture.channel().attr(RESPONSE_RECEIVED).set(false);
            channelFuture.channel().attr(RECEIVED).set(responseReceived);
            channelFuture.channel().attr(COMPLETED).set(complete);
            channelFuture.channel().attr(WILL_CLOSE).set(!keepAlive);
            channelFuture.channel().attr(RESULT).set(result);
            channelFuture.channel().attr(REQUEST_ID).set(requestId);
            Throwable cause = future.cause();
            if (null == cause) {
                RequestContentSubscriber requestContentSubscriber = new RequestContentSubscriber(request, channelFuture.channel(), result, sent, allowChunkedEncoding);
                requestEntity.subscribe(requestContentSubscriber);
            } else {
                sent.completeExceptionally(cause);
                responseReceived.completeExceptionally(cause);
                complete.completeExceptionally(cause);
                result.completeExceptionally(new WebClientException(finalUri.toString(), cause));
            }
        });
        return result;
    }));
    return wrapWithContext(single);
}
Also used : AttributeKey(io.netty.util.AttributeKey) Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) DataChunk(io.helidon.common.http.DataChunk) MessageBodyReadableContent(io.helidon.media.common.MessageBodyReadableContent) AsciiString(io.netty.util.AsciiString) MessageBodyWriterContext(io.helidon.media.common.MessageBodyWriterContext) MediaType(io.helidon.common.http.MediaType) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Flow(java.util.concurrent.Flow) Duration(java.time.Duration) Map(java.util.Map) Parameters(io.helidon.common.http.Parameters) URI(java.net.URI) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Logger(java.util.logging.Logger) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Objects(java.util.Objects) MessageBodyReaderContext(io.helidon.media.common.MessageBodyReaderContext) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Optional(java.util.Optional) Headers(io.helidon.common.http.Headers) HttpRequest(io.helidon.common.http.HttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) Context(io.helidon.common.context.Context) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) StringTokenizer(java.util.StringTokenizer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Single(io.helidon.common.reactive.Single) Http(io.helidon.common.http.Http) WebClientService(io.helidon.webclient.spi.WebClientService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) GenericType(io.helidon.common.GenericType) Contexts(io.helidon.common.context.Contexts) ChannelFuture(io.netty.channel.ChannelFuture) TimeUnit(java.util.concurrent.TimeUnit) Channel(io.netty.channel.Channel) AtomicLong(java.util.concurrent.atomic.AtomicLong) Bootstrap(io.netty.bootstrap.Bootstrap) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) HttpUtil(io.netty.handler.codec.http.HttpUtil) ChannelFuture(io.netty.channel.ChannelFuture) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) WebClientService(io.helidon.webclient.spi.WebClientService) URI(java.net.URI) ChannelFutureListener(io.netty.channel.ChannelFutureListener) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 23 with DataChunk

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

the class JsonContentReaderTest method simpleJsonArray.

@Test
public void simpleJsonArray() throws Exception {
    Publisher<DataChunk> chunks = Multi.singleton("[ \"val\" ]").map(s -> DataChunk.create(s.getBytes()));
    CompletionStage<? extends JsonArray> stage = JsonpSupport.reader().read(chunks, GenericType.create(JsonArray.class), CONTEXT).toStage();
    JsonArray array = stage.toCompletableFuture().get(10, TimeUnit.SECONDS);
    assertThat(array.getString(0), Is.is("val"));
}
Also used : JsonArray(jakarta.json.JsonArray) DataChunk(io.helidon.common.http.DataChunk) Test(org.junit.jupiter.api.Test)

Example 24 with DataChunk

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

the class JsonContentReaderTest method incompatibleTypes.

@Test
public void incompatibleTypes() throws Exception {
    Publisher<DataChunk> chunks = Multi.singleton("{ \"p\" : \"val\" }").map(s -> DataChunk.create(s.getBytes()));
    CompletionStage<? extends JsonArray> stage = JsonpSupport.reader().read(chunks, GenericType.create(JsonArray.class), CONTEXT).toStage();
    try {
        JsonArray array = stage.thenApply(o -> {
            fail("Shouldn't occur because of JSON exception!");
            return o;
        }).toCompletableFuture().get(10, TimeUnit.SECONDS);
        fail("Should have failed because an expected array is actually an object: " + array);
    } catch (ExecutionException e) {
        assertThat(e.getCause(), IsInstanceOf.instanceOf(JsonException.class));
    }
}
Also used : JsonArray(jakarta.json.JsonArray) DataChunk(io.helidon.common.http.DataChunk) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test)

Example 25 with DataChunk

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

the class JsonContentReaderTest method simpleJsonObject.

@Test
public void simpleJsonObject() throws Exception {
    Publisher<DataChunk> chunks = Multi.singleton("{ \"p\" : \"val\" }").map(s -> DataChunk.create(s.getBytes()));
    CompletionStage<? extends JsonObject> stage = JsonpSupport.reader().read(chunks, GenericType.create(JsonObject.class), CONTEXT).toStage();
    JsonObject jsonObject = stage.toCompletableFuture().get(10, TimeUnit.SECONDS);
    assertThat(jsonObject.getJsonString("p").getString(), Is.is("val"));
}
Also used : JsonObject(jakarta.json.JsonObject) DataChunk(io.helidon.common.http.DataChunk) Test(org.junit.jupiter.api.Test)

Aggregations

DataChunk (io.helidon.common.http.DataChunk)43 Test (org.junit.jupiter.api.Test)18 Multi (io.helidon.common.reactive.Multi)12 Flow (java.util.concurrent.Flow)11 GenericType (io.helidon.common.GenericType)9 CompletableFuture (java.util.concurrent.CompletableFuture)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 Http (io.helidon.common.http.Http)8 Single (io.helidon.common.reactive.Single)8 ByteBuffer (java.nio.ByteBuffer)8 MediaType (io.helidon.common.http.MediaType)7 MessageBodyWriterContext (io.helidon.media.common.MessageBodyWriterContext)7 WebClient (io.helidon.webclient.WebClient)7 WebClientResponse (io.helidon.webclient.WebClientResponse)7 IOException (java.io.IOException)7 List (java.util.List)7 Optional (java.util.Optional)7 TimeUnit (java.util.concurrent.TimeUnit)7 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)7 Logger (java.util.logging.Logger)6