Search in sources :

Example 11 with WriteListener

use of javax.servlet.WriteListener in project java-chassis by ServiceComb.

the class TestStandardHttpServletResponseEx method flushBuffer.

@Test
public void flushBuffer() throws IOException {
    Buffer buffer = Buffer.buffer();
    ServletOutputStream output = new ServletOutputStream() {

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            buffer.appendByte((byte) b);
        }
    };
    response = new MockUp<HttpServletResponse>() {

        @Mock
        ServletOutputStream getOutputStream() {
            return output;
        }
    }.getMockInstance();
    responseEx = new StandardHttpServletResponseEx(response);
    // no body
    responseEx.flushBuffer();
    Assert.assertEquals(0, buffer.length());
    Buffer body = Buffer.buffer().appendString("body");
    responseEx.setBodyBuffer(body);
    responseEx.flushBuffer();
    Assert.assertEquals("body", buffer.toString());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ServletOutputStream(javax.servlet.ServletOutputStream) MockUp(mockit.MockUp) WriteListener(javax.servlet.WriteListener) Test(org.junit.Test)

Example 12 with WriteListener

use of javax.servlet.WriteListener in project jetty.project by eclipse.

the class StreamResetTest method testResetAfterAsyncRequestAsyncWriteStalledByFlowControl.

@Test
public void testResetAfterAsyncRequestAsyncWriteStalledByFlowControl() throws Exception {
    int windowSize = FlowControlStrategy.DEFAULT_WINDOW_SIZE;
    CountDownLatch writeLatch = new CountDownLatch(1);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = request.startAsync();
            ServletOutputStream output = response.getOutputStream();
            output.setWriteListener(new WriteListener() {

                private boolean written;

                @Override
                public void onWritePossible() throws IOException {
                    while (output.isReady()) {
                        if (written) {
                            asyncContext.complete();
                            break;
                        } else {
                            output.write(new byte[10 * windowSize]);
                            written = true;
                        }
                    }
                }

                @Override
                public void onError(Throwable t) {
                    writeLatch.countDown();
                }
            });
        }
    });
    Deque<Callback> dataQueue = new ArrayDeque<>();
    AtomicLong received = new AtomicLong();
    CountDownLatch latch = new CountDownLatch(1);
    Session client = newClient(new Session.Listener.Adapter());
    MetaData.Request request = newRequest("GET", new HttpFields());
    HeadersFrame frame = new HeadersFrame(request, null, true);
    FuturePromise<Stream> promise = new FuturePromise<>();
    client.newStream(frame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            dataQueue.offer(callback);
            // Do not consume the data yet.
            if (received.addAndGet(frame.getData().remaining()) == windowSize)
                latch.countDown();
        }
    });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    // Reset and consume.
    stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP);
    dataQueue.forEach(Callback::succeeded);
    Assert.assertTrue(writeLatch.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) WriteListener(javax.servlet.WriteListener) ServletOutputStream(javax.servlet.ServletOutputStream) AsyncContext(javax.servlet.AsyncContext) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) ServletOutputStream(javax.servlet.ServletOutputStream) IStream(org.eclipse.jetty.http2.IStream) WriteListener(javax.servlet.WriteListener) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ArrayDeque(java.util.ArrayDeque) AtomicLong(java.util.concurrent.atomic.AtomicLong) Callback(org.eclipse.jetty.util.Callback) FutureCallback(org.eclipse.jetty.util.FutureCallback) ResetFrame(org.eclipse.jetty.http2.frames.ResetFrame) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 13 with WriteListener

use of javax.servlet.WriteListener in project jetty.project by eclipse.

the class SSLAsyncIOServletTest method testAsyncIOWritesWithAggregation.

@Test
public void testAsyncIOWritesWithAggregation() throws Exception {
    Random random = new Random();
    String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    final byte[] content = new byte[50000];
    for (int i = 0; i < content.length; ++i) content[i] = (byte) chars.charAt(random.nextInt(chars.length()));
    prepare(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            final AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            final int bufferSize = 4096;
            response.setBufferSize(bufferSize);
            response.getOutputStream().setWriteListener(new WriteListener() {

                private int writes;

                private int written;

                @Override
                public void onWritePossible() throws IOException {
                    ServletOutputStream output = asyncContext.getResponse().getOutputStream();
                    do {
                        int toWrite = content.length - written;
                        if (toWrite == 0) {
                            asyncContext.complete();
                            return;
                        }
                        toWrite = Math.min(toWrite, bufferSize);
                        // trigger the condition where the bytes are aggregated.
                        if (writes == 1)
                            toWrite -= 16;
                        output.write(content, written, toWrite);
                        ++writes;
                        written += toWrite;
                    } while (output.isReady());
                }

                @Override
                public void onError(Throwable t) {
                    asyncContext.complete();
                }
            });
        }
    });
    try (Socket client = newClient()) {
        String request = "" + "GET " + contextPath + servletPath + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
        OutputStream output = client.getOutputStream();
        output.write(request.getBytes("UTF-8"));
        output.flush();
        InputStream inputStream = client.getInputStream();
        HttpTester.Response response = HttpTester.parseResponse(inputStream);
        Assert.assertEquals(200, response.getStatus());
        Assert.assertArrayEquals(content, response.getContent().getBytes("UTF-8"));
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HttpServlet(javax.servlet.http.HttpServlet) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Random(java.util.Random) WriteListener(javax.servlet.WriteListener) Socket(java.net.Socket) Test(org.junit.Test)

Example 14 with WriteListener

use of javax.servlet.WriteListener in project jetty.project by eclipse.

the class AsyncIOServletTest method testAsyncWriteLessThanContentLengthFlushed.

@Test
public void testAsyncWriteLessThanContentLengthFlushed() throws Exception {
    CountDownLatch complete = new CountDownLatch(1);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentLength(10);
            AsyncContext async = request.startAsync();
            ServletOutputStream out = response.getOutputStream();
            AtomicInteger state = new AtomicInteger(0);
            out.setWriteListener(new WriteListener() {

                @Override
                public void onWritePossible() throws IOException {
                    while (true) {
                        if (!out.isReady())
                            return;
                        switch(state.get()) {
                            case 0:
                                state.incrementAndGet();
                                WriteListener listener = this;
                                new Thread(() -> {
                                    try {
                                        Thread.sleep(50);
                                        listener.onWritePossible();
                                    } catch (Exception e) {
                                    }
                                }).start();
                                return;
                            case 1:
                                state.incrementAndGet();
                                out.flush();
                                break;
                            case 2:
                                state.incrementAndGet();
                                out.write("12345".getBytes());
                                break;
                            case 3:
                                async.complete();
                                complete.countDown();
                                return;
                        }
                    }
                }

                @Override
                public void onError(Throwable t) {
                }
            });
        }
    });
    AtomicBoolean failed = new AtomicBoolean(false);
    CountDownLatch clientLatch = new CountDownLatch(3);
    client.newRequest(newURI()).path(servletPath).onResponseHeaders(response -> {
        if (response.getStatus() == HttpStatus.OK_200)
            clientLatch.countDown();
    }).onResponseContent(new Response.ContentListener() {

        @Override
        public void onContent(Response response, ByteBuffer content) {
        // System.err.println("Content: "+BufferUtil.toDetailString(content));
        }
    }).onResponseFailure(new Response.FailureListener() {

        @Override
        public void onFailure(Response response, Throwable failure) {
            clientLatch.countDown();
        }
    }).send(result -> {
        failed.set(result.isFailed());
        clientLatch.countDown();
        clientLatch.countDown();
        clientLatch.countDown();
    });
    assertTrue(complete.await(10, TimeUnit.SECONDS));
    assertTrue(clientLatch.await(10, TimeUnit.SECONDS));
    assertTrue(failed.get());
}
Also used : Request(org.eclipse.jetty.server.Request) ServletException(javax.servlet.ServletException) Context(org.eclipse.jetty.server.handler.ContextHandler.Context) ByteBuffer(java.nio.ByteBuffer) Assert.assertThat(org.junit.Assert.assertThat) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) BufferUtil.toArray(org.eclipse.jetty.util.BufferUtil.toArray) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HttpStatus(org.eclipse.jetty.http.HttpStatus) HttpInput(org.eclipse.jetty.server.HttpInput) Response(org.eclipse.jetty.client.api.Response) HttpServlet(javax.servlet.http.HttpServlet) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) UncheckedIOException(java.io.UncheckedIOException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) Session(org.eclipse.jetty.http2.api.Session) FuturePromise(org.eclipse.jetty.util.FuturePromise) Content(org.eclipse.jetty.server.HttpInput.Content) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Matchers.is(org.hamcrest.Matchers.is) Queue(java.util.Queue) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) BufferUtil(org.eclipse.jetty.util.BufferUtil) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Result(org.eclipse.jetty.client.api.Result) Handler(org.eclipse.jetty.server.Handler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpChannel(org.eclipse.jetty.server.HttpChannel) ServletInputStream(javax.servlet.ServletInputStream) ByteBuffer.wrap(java.nio.ByteBuffer.wrap) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Deque(java.util.Deque) InterruptedIOException(java.io.InterruptedIOException) AsyncContext(javax.servlet.AsyncContext) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) WriteListener(javax.servlet.WriteListener) InputStreamContentProvider(org.eclipse.jetty.client.util.InputStreamContentProvider) HttpConnectionOverHTTP2(org.eclipse.jetty.http2.client.http.HttpConnectionOverHTTP2) Assume(org.junit.Assume) Executor(java.util.concurrent.Executor) HttpServletResponse(javax.servlet.http.HttpServletResponse) Matchers(org.hamcrest.Matchers) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) TimeUnit(java.util.concurrent.TimeUnit) HttpMethod(org.eclipse.jetty.http.HttpMethod) Connection(org.eclipse.jetty.io.Connection) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ReadListener(javax.servlet.ReadListener) DispatcherType(javax.servlet.DispatcherType) Destination(org.eclipse.jetty.client.api.Destination) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) ServletException(javax.servlet.ServletException) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteListener(javax.servlet.WriteListener) Test(org.junit.Test)

Example 15 with WriteListener

use of javax.servlet.WriteListener in project neo4j by neo4j.

the class BatchOperationService method batchProcessAndStream.

private Response batchProcessAndStream(final UriInfo uriInfo, final HttpHeaders httpHeaders, final HttpServletRequest req, final InputStream body) {
    try {
        final StreamingOutput stream = new StreamingOutput() {

            @Override
            public void write(final OutputStream output) throws IOException, WebApplicationException {
                try {
                    final ServletOutputStream servletOutputStream = new ServletOutputStream() {

                        @Override
                        public void write(int i) throws IOException {
                            output.write(i);
                        }

                        @Override
                        public boolean isReady() {
                            return true;
                        }

                        @Override
                        public void setWriteListener(WriteListener writeListener) {
                            try {
                                writeListener.onWritePossible();
                            } catch (IOException e) {
                            // Ignore
                            }
                        }
                    };
                    new StreamingBatchOperations(webServer).readAndExecuteOperations(uriInfo, httpHeaders, req, body, servletOutputStream);
                    representationWriteHandler.onRepresentationWritten();
                } catch (Exception e) {
                    LOGGER.warn("Error executing batch request ", e);
                } finally {
                    representationWriteHandler.onRepresentationFinal();
                }
            }
        };
        return Response.ok(stream).type(HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE)).build();
    } catch (Exception e) {
        return output.serverError(e);
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) IOException(java.io.IOException) NonStreamingBatchOperations(org.neo4j.server.rest.batch.NonStreamingBatchOperations) WriteListener(javax.servlet.WriteListener) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Aggregations

WriteListener (javax.servlet.WriteListener)31 ServletOutputStream (javax.servlet.ServletOutputStream)27 IOException (java.io.IOException)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 AsyncContext (javax.servlet.AsyncContext)12 Test (org.junit.Test)11 ServletException (javax.servlet.ServletException)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 HttpServlet (javax.servlet.http.HttpServlet)6 InterruptedIOException (java.io.InterruptedIOException)5 ByteBuffer (java.nio.ByteBuffer)5 ReadListener (javax.servlet.ReadListener)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Request (org.eclipse.jetty.server.Request)4 Before (org.junit.Before)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 UncheckedIOException (java.io.UncheckedIOException)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3