Search in sources :

Example 16 with DataChunk

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

the class ContextLifeCycleTest method testContextReactive.

@Test
void testContextReactive() {
    Handler handler = (req, res) -> {
        String cid = req.context().id();
        req.content().subscribe(new Subscriber<>() {

            @Override
            public void onSubscribe(Subscription subscription) {
                subscription.request(Long.MAX_VALUE);
            }

            @Override
            public void onNext(DataChunk item) {
                item.release();
                if (!cid.equals(contextId())) {
                    throw new IllegalStateException("Context invalid");
                }
            }

            @Override
            public void onError(Throwable throwable) {
                res.send(throwable);
            }

            @Override
            public void onComplete() {
                if (!cid.equals(contextId())) {
                    res.send(new IllegalStateException("Context invalid"));
                } else {
                    res.send();
                }
            }
        });
    };
    WebServer webServer = WebServer.builder(Routing.builder().post(handler)).build().start().await(10, TimeUnit.SECONDS);
    ResponseStatus responseStatus = WebClient.builder().baseUri("http://localhost:" + webServer.port()).build().post().submit("some-payload").map(WebClientResponse::status).onTerminate(webServer::shutdown).await(10, TimeUnit.SECONDS);
    assertThat(responseStatus.code(), is(200));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) WebClient(io.helidon.webclient.WebClient) WebClientResponse(io.helidon.webclient.WebClientResponse) Subscription(java.util.concurrent.Flow.Subscription) DataChunk(io.helidon.common.http.DataChunk) Context(io.helidon.common.context.Context) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) Contexts(io.helidon.common.context.Contexts) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Subscriber(java.util.concurrent.Flow.Subscriber) ResponseStatus(io.helidon.common.http.Http.ResponseStatus) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) WebClientResponse(io.helidon.webclient.WebClientResponse) Subscriber(java.util.concurrent.Flow.Subscriber) ResponseStatus(io.helidon.common.http.Http.ResponseStatus) DataChunk(io.helidon.common.http.DataChunk) Subscription(java.util.concurrent.Flow.Subscription) Test(org.junit.jupiter.api.Test)

Example 17 with DataChunk

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

the class TyrusWriterPublisher method writeNext.

private void writeNext(ByteBuffer byteBuffer, CompletionHandler<ByteBuffer> handler) {
    DataChunk dataChunk = DataChunk.create(true, true, byteBuffer);
    if (handler != null) {
        dataChunk.writeFuture(fromCompletionHandler(handler));
    }
    subscriber.onNext(dataChunk);
}
Also used : DataChunk(io.helidon.common.http.DataChunk)

Example 18 with DataChunk

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

the class RequestContentTest method multiThreadingFilterAndReaderTest.

@SuppressWarnings("unchecked")
@Test
public void multiThreadingFilterAndReaderTest() throws Exception {
    CountDownLatch subscribedLatch = new CountDownLatch(1);
    SubmissionPublisher<DataChunk> publisher = new SubmissionPublisher<>(Runnable::run, 10);
    ForkJoinPool.commonPool().submit(() -> {
        try {
            if (!subscribedLatch.await(10, TimeUnit.SECONDS)) {
                fail("Subscriber didn't subscribe in timely manner!");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("Interrupted!", e);
        }
        publisher.submit(DataChunk.create("first".getBytes()));
        publisher.submit(DataChunk.create("second".getBytes()));
        publisher.submit(DataChunk.create("third".getBytes()));
        publisher.close();
    });
    Request request = requestTestStub(Multi.create(publisher));
    request.content().registerFilter(originalPublisher -> subscriberDelegate -> originalPublisher.subscribe(new Subscriber<DataChunk>() {

        @Override
        public void onSubscribe(Subscription subscription) {
            subscriberDelegate.onSubscribe(subscription);
            subscribedLatch.countDown();
        }

        @Override
        public void onNext(DataChunk item) {
            // mapping the on next call only
            subscriberDelegate.onNext(DataChunk.create(requestChunkAsString(item).toUpperCase().getBytes()));
        }

        @Override
        public void onError(Throwable throwable) {
            subscriberDelegate.onError(throwable);
        }

        @Override
        public void onComplete() {
            subscriberDelegate.onComplete();
        }
    }));
    request.content().registerReader(Iterable.class, (publisher1, clazz) -> {
        fail("Iterable reader should have not been used!");
        throw new IllegalStateException("unreachable code");
    });
    request.content().registerReader(ArrayList.class, (publisher1, clazz) -> {
        fail("ArrayList reader should have not been used!");
        throw new IllegalStateException("unreachable code");
    });
    request.content().registerReader(List.class, (publisher1, clazz) -> {
        CompletableFuture<List> future = new CompletableFuture<>();
        List<String> list = new CopyOnWriteArrayList<>();
        publisher1.subscribe(new Subscriber<DataChunk>() {

            @Override
            public void onSubscribe(Subscription subscription) {
                subscription.request(Long.MAX_VALUE);
                subscribedLatch.countDown();
            }

            @Override
            public void onNext(DataChunk item) {
                list.add(TestUtils.requestChunkAsString(item));
            }

            @Override
            public void onError(Throwable throwable) {
                fail("Received an exception: " + throwable.getMessage());
            }

            @Override
            public void onComplete() {
                future.complete(list);
            }
        });
        return future;
    });
    List<String> result = (List<String>) request.content().as(List.class).toCompletableFuture().get(10, TimeUnit.SECONDS);
    assertThat(result, hasItems(is("FIRST"), is("SECOND"), is("THIRD")));
}
Also used : SubmissionPublisher(java.util.concurrent.SubmissionPublisher) TestUtils.requestChunkAsString(io.helidon.webserver.utils.TestUtils.requestChunkAsString) StringContains.containsString(org.hamcrest.core.StringContains.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) CompletableFuture(java.util.concurrent.CompletableFuture) Subscriber(java.util.concurrent.Flow.Subscriber) DataChunk(io.helidon.common.http.DataChunk) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Subscription(java.util.concurrent.Flow.Subscription) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.jupiter.api.Test)

Example 19 with DataChunk

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

the class NettyWebServerTest method main.

/**
 * Start the test and then run:
 * <pre><code>
 *     seq 1000 | head -c 1000 | curl -X PUT -Ssf http://localhost:8080 --data-binary @- http://localhost:8080 --data ahoj
 * </code></pre>
 * <p>
 *
 * @throws InterruptedException if the main thread is interrupted
 */
static void main(String[] args) throws InterruptedException {
    WebServer webServer = WebServer.builder().port(8080).host("localhost").routing(routing((breq, bres) -> {
        SubmissionPublisher<DataChunk> responsePublisher = new SubmissionPublisher<>(ForkJoinPool.commonPool(), 1024);
        responsePublisher.subscribe(bres);
        final AtomicReference<Subscription> subscription = new AtomicReference<>();
        // Read request and immediately write to response
        Multi.create(breq.bodyPublisher()).subscribe((DataChunk chunk) -> {
            DataChunk responseChunk = DataChunk.create(true, chunk::release, chunk.data());
            responsePublisher.submit(responseChunk);
            ForkJoinPool.commonPool().submit(() -> {
                try {
                    Thread.sleep(1);
                    subscription.get().request(ThreadLocalRandom.current().nextLong(1, 3));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new IllegalStateException(e);
                }
            });
        }, (Throwable ex) -> {
            LOGGER.log(Level.WARNING, "An error occurred during the flow consumption!", ex);
        }, responsePublisher::close, (Subscription s) -> {
            subscription.set(s);
            s.request(1);
            bres.writeStatusAndHeaders(Http.Status.CREATED_201, Collections.emptyMap());
        });
    })).build();
    webServer.start();
    Thread.currentThread().join();
}
Also used : SubmissionPublisher(java.util.concurrent.SubmissionPublisher) DataChunk(io.helidon.common.http.DataChunk) AtomicReference(java.util.concurrent.atomic.AtomicReference) Subscription(java.util.concurrent.Flow.Subscription)

Example 20 with DataChunk

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

the class UnstableTempTest method cleanedTmpDuringRuntime.

@Test
void cleanedTmpDuringRuntime() throws IOException {
    List<String> contents = new ArrayList<>(2);
    Path jar = createJar();
    URL jarUrl = new URL("jar:file:" + jar.toUri().getPath() + "!/" + FILE_NAME);
    LOGGER.fine(() -> "Generated test jar url: " + jarUrl.toString());
    ClassPathContentHandler classPathContentHandler = new ClassPathContentHandler(null, new ContentTypeSelector(null), "/", tmpDir, Thread.currentThread().getContextClassLoader());
    // Empty headers
    RequestHeaders headers = mock(RequestHeaders.class);
    when(headers.isAccepted(any())).thenReturn(true);
    when(headers.acceptedTypes()).thenReturn(Collections.emptyList());
    ResponseHeaders responseHeaders = mock(ResponseHeaders.class);
    ServerRequest request = Mockito.mock(ServerRequest.class);
    Mockito.when(request.headers()).thenReturn(headers);
    ServerResponse response = Mockito.mock(ServerResponse.class);
    MessageBodyWriterContext ctx = MessageBodyWriterContext.create(HashParameters.create());
    ctx.registerFilter(dataChunkPub -> {
        String fileContent = new String(Single.create(dataChunkPub).await().bytes());
        contents.add(fileContent);
        return Single.just(DataChunk.create(ByteBuffer.wrap(fileContent.getBytes())));
    });
    Mockito.when(response.headers()).thenReturn(responseHeaders);
    @SuppressWarnings("unchecked") Function<MessageBodyWriterContext, Flow.Publisher<DataChunk>> anyFunction = (Function<MessageBodyWriterContext, Flow.Publisher<DataChunk>>) Mockito.any(Function.class);
    Mockito.when(response.send(anyFunction)).then(mock -> {
        Function<MessageBodyWriterContext, Flow.Publisher<DataChunk>> argument = mock.getArgument(0);
        return Single.create(argument.apply(ctx)).onError(throwable -> throwable.printStackTrace());
    });
    classPathContentHandler.sendJar(Http.Method.GET, FILE_NAME, jarUrl, request, response);
    deleteTmpFiles();
    classPathContentHandler.sendJar(Http.Method.GET, FILE_NAME, jarUrl, request, response);
    assertThat(contents, containsInAnyOrder(FILE_CONTENT, FILE_CONTENT));
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) URL(java.net.URL) Flow(java.util.concurrent.Flow) Function(java.util.function.Function) MessageBodyWriterContext(io.helidon.media.common.MessageBodyWriterContext) 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