Search in sources :

Example 16 with ReadListener

use of javax.servlet.ReadListener in project druid by druid-io.

the class AsyncQueryForwardingServletTest method verifyServletCallsForQuery.

/**
 * Verifies that the Servlet calls the right methods the right number of times.
 */
private void verifyServletCallsForQuery(Object query, boolean isSql, QueryHostFinder hostFinder, Properties properties) throws Exception {
    final ObjectMapper jsonMapper = TestHelper.makeJsonMapper();
    final HttpServletRequest requestMock = EasyMock.createMock(HttpServletRequest.class);
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonMapper.writeValueAsBytes(query));
    final ServletInputStream servletInputStream = new ServletInputStream() {

        private boolean finished;

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

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

        @Override
        public void setReadListener(final ReadListener readListener) {
        // do nothing
        }

        @Override
        public int read() {
            final int b = inputStream.read();
            if (b < 0) {
                finished = true;
            }
            return b;
        }
    };
    EasyMock.expect(requestMock.getContentType()).andReturn("application/json").times(2);
    requestMock.setAttribute("org.apache.druid.proxy.objectMapper", jsonMapper);
    EasyMock.expectLastCall();
    EasyMock.expect(requestMock.getRequestURI()).andReturn(isSql ? "/druid/v2/sql" : "/druid/v2/");
    EasyMock.expect(requestMock.getMethod()).andReturn("POST");
    EasyMock.expect(requestMock.getInputStream()).andReturn(servletInputStream);
    requestMock.setAttribute(isSql ? "org.apache.druid.proxy.sqlQuery" : "org.apache.druid.proxy.query", query);
    requestMock.setAttribute("org.apache.druid.proxy.to.host", "1.2.3.4:9999");
    requestMock.setAttribute("org.apache.druid.proxy.to.host.scheme", "http");
    EasyMock.expectLastCall();
    EasyMock.replay(requestMock);
    final AtomicLong didService = new AtomicLong();
    final AsyncQueryForwardingServlet servlet = new AsyncQueryForwardingServlet(new MapQueryToolChestWarehouse(ImmutableMap.of()), jsonMapper, TestHelper.makeSmileMapper(), hostFinder, null, null, new NoopServiceEmitter(), new NoopRequestLogger(), new DefaultGenericQueryMetricsFactory(), new AuthenticatorMapper(ImmutableMap.of()), properties, new ServerConfig()) {

        @Override
        protected void doService(final HttpServletRequest request, final HttpServletResponse response) {
            didService.incrementAndGet();
        }
    };
    servlet.service(requestMock, null);
    // This test is mostly about verifying that the servlet calls the right methods the right number of times.
    EasyMock.verify(hostFinder, requestMock);
    Assert.assertEquals(1, didService.get());
}
Also used : NoopRequestLogger(org.apache.druid.server.log.NoopRequestLogger) HttpServletResponse(javax.servlet.http.HttpServletResponse) NoopServiceEmitter(org.apache.druid.server.metrics.NoopServiceEmitter) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticatorMapper(org.apache.druid.server.security.AuthenticatorMapper) ServerConfig(org.apache.druid.server.initialization.ServerConfig) AtomicLong(java.util.concurrent.atomic.AtomicLong) ServletInputStream(javax.servlet.ServletInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) MapQueryToolChestWarehouse(org.apache.druid.query.MapQueryToolChestWarehouse) DefaultGenericQueryMetricsFactory(org.apache.druid.query.DefaultGenericQueryMetricsFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 17 with ReadListener

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

the class ServerTimeoutsTest method testAsyncReadIdleTimeoutFires.

@Test
public void testAsyncReadIdleTimeoutFires() throws Exception {
    CountDownLatch handlerLatch = new CountDownLatch(1);
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            ServletInputStream input = request.getInputStream();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    Assert.assertEquals(0, input.read());
                    Assert.assertFalse(input.isReady());
                }

                @Override
                public void onAllDataRead() throws IOException {
                }

                @Override
                public void onError(Throwable failure) {
                    if (failure instanceof TimeoutException) {
                        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
                        asyncContext.complete();
                        handlerLatch.countDown();
                    }
                }
            });
        }
    });
    long idleTimeout = 2500;
    setServerIdleTimeout(idleTimeout);
    DeferredContentProvider contentProvider = new DeferredContentProvider(ByteBuffer.allocate(1));
    CountDownLatch resultLatch = new CountDownLatch(1);
    client.POST(newURI()).content(contentProvider).send(result -> {
        if (result.getResponse().getStatus() == HttpStatus.INTERNAL_SERVER_ERROR_500)
            resultLatch.countDown();
    });
    // Async read should timeout.
    Assert.assertTrue(handlerLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
    // Complete the request.
    contentProvider.close();
    Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ReadListener(javax.servlet.ReadListener) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 18 with ReadListener

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

the class AsyncIOServletTest method testAsyncReadThrows.

private void testAsyncReadThrows(Throwable throwable) throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    start(new HttpServlet() {

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

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    if (throwable instanceof RuntimeException)
                        throw (RuntimeException) throwable;
                    if (throwable instanceof Error)
                        throw (Error) throwable;
                    throw new IOException(throwable);
                }

                @Override
                public void onAllDataRead() throws IOException {
                    assertScope();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    Assert.assertThat("onError type", t, instanceOf(throwable.getClass()));
                    Assert.assertThat("onError message", t.getMessage(), is(throwable.getMessage()));
                    latch.countDown();
                    response.setStatus(500);
                    asyncContext.complete();
                }
            });
        }
    });
    ContentResponse response = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(new StringContentProvider("0123456789")).timeout(5, TimeUnit.SECONDS).send();
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR_500, response.getStatus());
}
Also used : 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) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException)

Example 19 with ReadListener

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

the class AsyncIOServletTest method testOnErrorThrows.

@Test
public void testOnErrorThrows() throws Exception {
    AtomicInteger errors = new AtomicInteger();
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            if (request.getDispatcherType() == DispatcherType.ERROR) {
                response.flushBuffer();
                return;
            }
            request.startAsync(request, response);
            request.getInputStream().setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    throw new NullPointerException("explicitly_thrown_by_test_1");
                }

                @Override
                public void onAllDataRead() throws IOException {
                    assertScope();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    errors.incrementAndGet();
                    throw new NullPointerException("explicitly_thrown_by_test_2") {

                        {
                            this.initCause(t);
                        }
                    };
                }
            });
        }
    });
    try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class)) {
        ContentResponse response = client.newRequest(newURI()).path(servletPath).content(new StringContentProvider("0123456789")).timeout(5, TimeUnit.SECONDS).send();
        assertEquals(HttpStatus.INTERNAL_SERVER_ERROR_500, response.getStatus());
        Assert.assertEquals(1, errors.get());
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) 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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Test(org.junit.Test)

Example 20 with ReadListener

use of javax.servlet.ReadListener 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)

Aggregations

ReadListener (javax.servlet.ReadListener)27 ServletInputStream (javax.servlet.ServletInputStream)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)19 IOException (java.io.IOException)18 HttpServletResponse (javax.servlet.http.HttpServletResponse)18 ServletException (javax.servlet.ServletException)14 Test (org.junit.Test)14 AsyncContext (javax.servlet.AsyncContext)13 HttpServlet (javax.servlet.http.HttpServlet)12 InterruptedIOException (java.io.InterruptedIOException)11 UncheckedIOException (java.io.UncheckedIOException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)9 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)7 Matchers.containsString (org.hamcrest.Matchers.containsString)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ServletOutputStream (javax.servlet.ServletOutputStream)5 Response (org.eclipse.jetty.client.api.Response)4 Result (org.eclipse.jetty.client.api.Result)4 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)4