Search in sources :

Example 51 with ServletInputStream

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

the class AsyncIOServletTest method testIsReadyAtEOF.

@Test
public void testIsReadyAtEOF() throws Exception {
    String text = "TEST\n";
    byte[] data = text.getBytes(StandardCharsets.UTF_8);
    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() {

                transient int _i = 0;

                transient boolean _minusOne = false;

                transient boolean _finished = false;

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    while (input.isReady() && !input.isFinished()) {
                        int b = input.read();
                        if (b == -1)
                            _minusOne = true;
                        else if (data[_i++] != b)
                            throw new IllegalStateException();
                    }
                    if (input.isFinished())
                        _finished = true;
                }

                @Override
                public void onAllDataRead() throws IOException {
                    assertScope();
                    output.write(String.format("i=%d eof=%b finished=%b", _i, _minusOne, _finished).getBytes(StandardCharsets.UTF_8));
                    async.complete();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    t.printStackTrace();
                    async.complete();
                }
            });
        }
    });
    ContentResponse response = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).header(HttpHeader.CONNECTION, "close").content(new StringContentProvider(text)).timeout(5, TimeUnit.SECONDS).send();
    String responseContent = response.getContentAsString();
    assertThat(responseContent, containsString("i=" + data.length + " eof=true finished=true"));
}
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) ServletInputStream(javax.servlet.ServletInputStream) Test(org.junit.Test)

Example 52 with ServletInputStream

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

the class HttpClientContinueTest method test_Expect100Continue_WithChunkedContent_Respond100Continue.

@Test
public void test_Expect100Continue_WithChunkedContent_Respond100Continue() throws Exception {
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            // Send 100-Continue and copy the content back
            ServletInputStream input = request.getInputStream();
            // Make sure we chunk the response too
            response.flushBuffer();
            IO.copy(input, response.getOutputStream());
        }
    });
    byte[] content1 = new byte[10240];
    byte[] content2 = new byte[16384];
    ContentResponse response = client.newRequest(newURI()).header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()).content(new BytesContentProvider(content1, content2) {

        @Override
        public long getLength() {
            return -1;
        }
    }).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
    int index = 0;
    byte[] responseContent = response.getContent();
    for (byte b : content1) Assert.assertEquals(b, responseContent[index++]);
    for (byte b : content2) Assert.assertEquals(b, responseContent[index++]);
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) Test(org.junit.Test)

Example 53 with ServletInputStream

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

the class Request method getReader.

/* ------------------------------------------------------------ */
/*
     * @see javax.servlet.ServletRequest#getReader()
     */
@Override
public BufferedReader getReader() throws IOException {
    if (_inputState != __NONE && _inputState != __READER)
        throw new IllegalStateException("STREAMED");
    if (_inputState == __READER)
        return _reader;
    String encoding = getCharacterEncoding();
    if (encoding == null)
        encoding = StringUtil.__ISO_8859_1;
    if (_reader == null || !encoding.equalsIgnoreCase(_readerEncoding)) {
        final ServletInputStream in = getInputStream();
        _readerEncoding = encoding;
        _reader = new BufferedReader(new InputStreamReader(in, encoding)) {

            @Override
            public void close() throws IOException {
                in.close();
            }
        };
    }
    _inputState = __READER;
    return _reader;
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 54 with ServletInputStream

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

the class AsyncIOTest method testLastContentAvailableBeforeService.

@Test
public void testLastContentAvailableBeforeService() throws Exception {
    start(new HttpServlet() {

        @Override
        protected void service(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Wait for the data to fully arrive.
            sleep(1000);
            final AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            request.getInputStream().setReadListener(new EmptyReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    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);
    stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), true), Callback.NOOP);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
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) 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 55 with ServletInputStream

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

the class AsyncIOTest method testLastContentAvailableAfterServiceReturns.

@Test
public void testLastContentAvailableAfterServiceReturns() throws Exception {
    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 {
                    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(16), true), Callback.NOOP);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
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) 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)

Aggregations

ServletInputStream (javax.servlet.ServletInputStream)79 IOException (java.io.IOException)51 HttpServletRequest (javax.servlet.http.HttpServletRequest)43 Test (org.junit.Test)43 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