Search in sources :

Example 26 with DataChunk

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

the class MultiPartEncoderTest method testPartContentPublisherError.

@Test
public void testPartContentPublisherError() {
    MultiPartEncoder encoder = MultiPartEncoder.create("boundary", MEDIA_CONTEXT.writerContext());
    DataChunkSubscriber subscriber = new DataChunkSubscriber();
    encoder.subscribe(subscriber);
    Multi.just(WriteableBodyPart.builder().publisher(Multi.<DataChunk>error(new IllegalStateException("oops"))).build()).subscribe(encoder);
    CompletableFuture<String> future = subscriber.content().toCompletableFuture();
    assertThat(future.isCompletedExceptionally(), is(equalTo(true)));
    try {
        future.getNow(null);
        fail("exception should be thrown");
    } catch (CompletionException ex) {
        assertThat(ex.getCause(), is(instanceOf(IllegalStateException.class)));
        assertThat(ex.getCause().getMessage(), is(equalTo("oops")));
    }
}
Also used : DataChunkSubscriber(io.helidon.media.multipart.MultiPartDecoderTest.DataChunkSubscriber) CompletionException(java.util.concurrent.CompletionException) DataChunk(io.helidon.common.http.DataChunk) Test(org.junit.jupiter.api.Test)

Example 27 with DataChunk

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

the class MultiPartEncoderTest method testRequests.

@Test
public void testRequests() throws Exception {
    MultiPartEncoder enc = MultiPartEncoder.create("boundary", MEDIA_CONTEXT.writerContext());
    Multi.create(LongStream.range(1, 500).mapToObj(i -> WriteableBodyPart.builder().entity("part" + i).build())).subscribe(enc);
    final CountDownLatch latch = new CountDownLatch(3);
    Subscriber<DataChunk> subscriber = new Subscriber<DataChunk>() {

        @Override
        public void onSubscribe(final Flow.Subscription subscription) {
            subscription.request(3L);
        }

        @Override
        public void onNext(final DataChunk item) {
            latch.countDown();
        }

        @Override
        public void onComplete() {
        }

        @Override
        public void onError(Throwable throwable) {
        }
    };
    enc.subscribe(subscriber);
    waitOnLatch(latch);
}
Also used : DataChunkSubscriber(io.helidon.media.multipart.MultiPartDecoderTest.DataChunkSubscriber) Subscriber(java.util.concurrent.Flow.Subscriber) DataChunk(io.helidon.common.http.DataChunk) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 28 with DataChunk

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

the class ConnectionCloseTest method testCutConnection.

@Test
void testCutConnection() throws ExecutionException, InterruptedException, TimeoutException {
    WebClient webClient = createNewClient();
    CompletableFuture<Throwable> actualErrorCf = new CompletableFuture<>();
    // Expecting WebClientException: Connection reset by the host
    webClient.get().path("/connectionClose").request().flatMap(WebClientResponse::content).map(DataChunk::bytes).map(String::new).log().onError(actualErrorCf::complete).ignoreElements();
    Throwable actual = actualErrorCf.get(10, TimeUnit.SECONDS);
    assertThat(actual, Matchers.instanceOf(WebClientException.class));
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) DataChunk(io.helidon.common.http.DataChunk) WebClient(io.helidon.webclient.WebClient) WebClientException(io.helidon.webclient.WebClientException) Test(org.junit.jupiter.api.Test)

Example 29 with DataChunk

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

the class MockZipkinService method mockZipkin.

private void mockZipkin(final ServerRequest request, final ServerResponse response) {
    request.queryParams().all("serviceName").forEach(s -> System.out.println(">>>" + s));
    request.content().registerReader(new MessageBodyStreamReader<JsonValue>() {

        @Override
        public PredicateResult accept(final GenericType<?> type, final MessageBodyReaderContext context) {
            return PredicateResult.COMPATIBLE;
        }

        @Override
        @SuppressWarnings("unchecked")
        public <U extends JsonValue> Flow.Publisher<U> read(final Flow.Publisher<DataChunk> publisher, final GenericType<U> type, final MessageBodyReaderContext context) {
            return (Flow.Publisher<U>) Multi.create(publisher).map(d -> ByteBuffer.wrap(d.bytes())).reduce((buf, buf2) -> ByteBuffer.allocate(buf.capacity() + buf2.capacity()).put(buf.array()).put(buf2.array())).flatMap(b -> {
                try (ByteArrayInputStream bais = new ByteArrayInputStream(b.array());
                    GZIPInputStream gzipInputStream = new GZIPInputStream(bais)) {
                    return Single.just(Json.createReader(new StringReader(new String(gzipInputStream.readAllBytes()))).readArray());
                } catch (EOFException e) {
                    // ignore
                    return Multi.empty();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).flatMap(a -> Multi.create(a.stream()));
        }
    }).asStream(JsonValue.class).map(JsonValue::asJsonObject).filter(json -> TAGS_POINTER.containsValue(json) && COMPONENT_POINTER.containsValue(json) && filteredComponents.stream().anyMatch(s -> s.equals(((JsonString) COMPONENT_POINTER.getValue(json)).getString()))).onError(Throwable::printStackTrace).onError(t -> response.status(500).send(t)).onComplete(response::send).peek(json -> LOGGER.info(json.toString())).forEach(e -> next.getAndSet(new CompletableFuture<>()).complete(e));
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) JsonValue(jakarta.json.JsonValue) DataChunk(io.helidon.common.http.DataChunk) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) ByteArrayInputStream(java.io.ByteArrayInputStream) Flow(java.util.concurrent.Flow) MessageBodyStreamReader(io.helidon.media.common.MessageBodyStreamReader) ServerResponse(io.helidon.webserver.ServerResponse) Single(io.helidon.common.reactive.Single) Service(io.helidon.webserver.Service) Multi(io.helidon.common.reactive.Multi) JsonPointer(jakarta.json.JsonPointer) Set(java.util.Set) IOException(java.io.IOException) Logger(java.util.logging.Logger) GenericType(io.helidon.common.GenericType) EOFException(java.io.EOFException) Json(jakarta.json.Json) ServerRequest(io.helidon.webserver.ServerRequest) MessageBodyReaderContext(io.helidon.media.common.MessageBodyReaderContext) CompletionStage(java.util.concurrent.CompletionStage) StringReader(java.io.StringReader) Routing(io.helidon.webserver.Routing) JsonString(jakarta.json.JsonString) JsonValue(jakarta.json.JsonValue) JsonString(jakarta.json.JsonString) IOException(java.io.IOException) Flow(java.util.concurrent.Flow) GZIPInputStream(java.util.zip.GZIPInputStream) MessageBodyReaderContext(io.helidon.media.common.MessageBodyReaderContext) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) EOFException(java.io.EOFException) DataChunk(io.helidon.common.http.DataChunk)

Example 30 with DataChunk

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

the class KeepAliveTest method setUp.

@BeforeAll
static void setUp() {
    LogConfig.configureRuntime();
    server = WebServer.builder().routing(Routing.builder().register("/close", rules -> rules.any((req, res) -> {
        req.content().forEach(dataChunk -> {
            // consume only first from two chunks
            dataChunk.release();
            throw new RuntimeException("BOOM!");
        }).exceptionally(res::send);
    })).register("/plain", rules -> rules.any((req, res) -> {
        req.content().forEach(DataChunk::release).onComplete(res::send).ignoreElement();
    })).build()).build();
    server.start().await();
    String serverUrl = "http://localhost:" + server.port();
    webClient = WebClient.builder().baseUri(serverUrl).keepAlive(true).build();
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) RepeatedTest(org.junit.jupiter.api.RepeatedTest) WebClient(io.helidon.webclient.WebClient) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) WebClientResponse(io.helidon.webclient.WebClientResponse) DataChunk(io.helidon.common.http.DataChunk) Matchers.not(org.hamcrest.Matchers.not) AsciiString(io.netty.util.AsciiString) CompletionException(java.util.concurrent.CompletionException) ByteBuffer(java.nio.ByteBuffer) Executors(java.util.concurrent.Executors) Matchers.hasKey(org.hamcrest.Matchers.hasKey) TimeUnit(java.util.concurrent.TimeUnit) AfterAll(org.junit.jupiter.api.AfterAll) List(java.util.List) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) Optional(java.util.Optional) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LogConfig(io.helidon.common.LogConfig) Multi(io.helidon.common.reactive.Multi) AsciiString(io.netty.util.AsciiString) BeforeAll(org.junit.jupiter.api.BeforeAll)

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