Search in sources :

Example 11 with ServletInputStream

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

the class AsyncIOServletTest method testCompleteBeforeOnAllDataRead.

@Test
public void testCompleteBeforeOnAllDataRead() throws Exception {
    String success = "SUCCESS";
    AtomicBoolean allDataRead = new AtomicBoolean(false);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            response.flushBuffer();
            AsyncContext async = request.startAsync();
            ServletInputStream input = request.getInputStream();
            ServletOutputStream output = response.getOutputStream();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    while (input.isReady()) {
                        int b = input.read();
                        if (b < 0) {
                            output.write(success.getBytes(StandardCharsets.UTF_8));
                            async.complete();
                            return;
                        }
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                    assertScope();
                    output.write("FAILURE".getBytes(StandardCharsets.UTF_8));
                    allDataRead.set(true);
                    throw new IllegalStateException();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    t.printStackTrace();
                }
            });
        }
    });
    ContentResponse response = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).header(HttpHeader.CONNECTION, "close").content(new StringContentProvider("XYZ")).timeout(5, TimeUnit.SECONDS).send();
    assertThat(response.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
    assertThat(response.getContentAsString(), Matchers.equalTo(success));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServletInputStream(javax.servlet.ServletInputStream) Test(org.junit.Test)

Example 12 with ServletInputStream

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

the class ClientConnectionCloseTest method test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange.

@Test
public void test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange() throws Exception {
    byte[] data = new byte[128 * 1024];
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            ServletInputStream input = request.getInputStream();
            while (true) {
                int read = input.read();
                if (read < 0)
                    break;
            }
            response.setContentLength(data.length);
            response.getOutputStream().write(data);
            try {
                // Delay the server from sending the TCP FIN.
                Thread.sleep(1000);
            } catch (InterruptedException x) {
                throw new InterruptedIOException();
            }
        }
    });
    String host = "localhost";
    int port = connector.getLocalPort();
    HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP) client.getDestination(scheme, host, port);
    DuplexConnectionPool connectionPool = (DuplexConnectionPool) destination.getConnectionPool();
    ContentResponse response = client.newRequest(host, port).scheme(scheme).header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()).content(new StringContentProvider("0")).onRequestSuccess(request -> {
        HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP) connectionPool.getActiveConnections().iterator().next();
        Assert.assertFalse(connection.getEndPoint().isOutputShutdown());
    }).send();
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    Assert.assertArrayEquals(data, response.getContent());
    Assert.assertEquals(0, connectionPool.getConnectionCount());
}
Also used : Request(org.eclipse.jetty.server.Request) HttpHeaderValue(org.eclipse.jetty.http.HttpHeaderValue) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ServletInputStream(javax.servlet.ServletInputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) InterruptedIOException(java.io.InterruptedIOException) ByteBuffer(java.nio.ByteBuffer) TimeUnit(java.util.concurrent.TimeUnit) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HttpStatus(org.eclipse.jetty.http.HttpStatus) Assert(org.junit.Assert) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) InterruptedIOException(java.io.InterruptedIOException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) Test(org.junit.Test)

Example 13 with ServletInputStream

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

the class IdleTimeoutTest method testBufferedReadsResetStreamIdleTimeout.

@Test
public void testBufferedReadsResetStreamIdleTimeout() throws Exception {
    int bufferSize = 8192;
    long delay = 1000;
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletInputStream input = request.getInputStream();
            byte[] buffer = new byte[bufferSize];
            while (true) {
                int read = input.read(buffer);
                Log.getLogger(IdleTimeoutTest.class).info("Read {} bytes", read);
                if (read < 0)
                    break;
                sleep(delay);
            }
        }
    });
    connector.setIdleTimeout(2 * delay);
    Session session = newClient(new Session.Listener.Adapter());
    MetaData.Request metaData = newRequest("POST", new HttpFields());
    HeadersFrame requestFrame = new HeadersFrame(metaData, null, false);
    FuturePromise<Stream> promise = new FuturePromise<>();
    CountDownLatch latch = new CountDownLatch(1);
    session.newStream(requestFrame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                latch.countDown();
        }
    });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    // Send data larger than the flow control window.
    // The client will send bytes up to the flow control window immediately
    // and they will be buffered by the server; the Servlet will consume them slowly.
    // Servlet reads should reset the idle timeout.
    int contentLength = FlowControlStrategy.DEFAULT_WINDOW_SIZE + 1;
    ByteBuffer data = ByteBuffer.allocate(contentLength);
    stream.data(new DataFrame(stream.getId(), data, true), Callback.NOOP);
    Assert.assertTrue(latch.await(2 * (contentLength / bufferSize + 1) * delay, TimeUnit.MILLISECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) ByteBuffer(java.nio.ByteBuffer) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServletInputStream(javax.servlet.ServletInputStream) Stream(org.eclipse.jetty.http2.api.Stream) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 14 with ServletInputStream

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

the class AsyncIOTest method testSomeContentAvailableAfterServiceReturns.

@Test
public void testSomeContentAvailableAfterServiceReturns() throws Exception {
    final AtomicInteger count = new AtomicInteger();
    start(new HttpServlet() {

        @Override
        protected void service(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            final AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            request.getInputStream().setReadListener(new EmptyReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    count.incrementAndGet();
                    ServletInputStream input = request.getInputStream();
                    while (input.isReady()) {
                        int read = input.read();
                        if (read < 0)
                            break;
                    }
                    if (input.isFinished())
                        asyncContext.complete();
                }
            });
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, false);
    final CountDownLatch latch = new CountDownLatch(1);
    FuturePromise<Stream> promise = new FuturePromise<>();
    session.newStream(frame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                latch.countDown();
        }
    });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    // Wait until service() returns.
    Thread.sleep(1000);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(1), false), Callback.NOOP);
    // Wait until onDataAvailable() returns.
    Thread.sleep(1000);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(1), true), Callback.NOOP);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    // Make sure onDataAvailable() has been called twice
    Assert.assertEquals(2, count.get());
}
Also used : ReadListener(javax.servlet.ReadListener) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServletInputStream(javax.servlet.ServletInputStream) Stream(org.eclipse.jetty.http2.api.Stream) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 15 with ServletInputStream

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

the class MultiPartInputStreamTest method testBodyAlreadyConsumed.

@Test
public void testBodyAlreadyConsumed() throws Exception {
    ServletInputStream is = new ServletInputStream() {

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

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

        @Override
        public void setReadListener(ReadListener readListener) {
        }

        @Override
        public int read() throws IOException {
            return 0;
        }
    };
    MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50);
    MultiPartInputStreamParser mpis = new MultiPartInputStreamParser(is, _contentType, config, _tmpDir);
    mpis.setDeleteOnExit(true);
    Collection<Part> parts = mpis.getParts();
    assertEquals(0, parts.size());
}
Also used : MultipartConfigElement(javax.servlet.MultipartConfigElement) ServletInputStream(javax.servlet.ServletInputStream) MultiPart(org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart) Part(javax.servlet.http.Part) ReadListener(javax.servlet.ReadListener) Test(org.junit.Test)

Aggregations

ServletInputStream (javax.servlet.ServletInputStream)76 IOException (java.io.IOException)50 Test (org.junit.Test)43 HttpServletRequest (javax.servlet.http.HttpServletRequest)42 ServletException (javax.servlet.ServletException)41 HttpServletResponse (javax.servlet.http.HttpServletResponse)40 CountDownLatch (java.util.concurrent.CountDownLatch)26 HttpServlet (javax.servlet.http.HttpServlet)20 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)20 InterruptedIOException (java.io.InterruptedIOException)18 AsyncContext (javax.servlet.AsyncContext)17 ReadListener (javax.servlet.ReadListener)17 ServletOutputStream (javax.servlet.ServletOutputStream)16 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)16 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)15 Request (org.eclipse.jetty.server.Request)14 Response (org.eclipse.jetty.client.api.Response)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 PrintWriter (java.io.PrintWriter)8 Matchers.containsString (org.hamcrest.Matchers.containsString)8