Search in sources :

Example 91 with Result

use of org.eclipse.jetty.client.api.Result in project druid by druid-io.

the class AsyncQueryForwardingServlet method service.

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(request.getContentType()) || APPLICATION_SMILE.equals(request.getContentType());
    final ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;
    request.setAttribute(OBJECTMAPPER_ATTRIBUTE, objectMapper);
    final String defaultHost = hostFinder.getDefaultHost();
    request.setAttribute(HOST_ATTRIBUTE, defaultHost);
    final boolean isQueryEndpoint = request.getRequestURI().startsWith("/druid/v2");
    if (isQueryEndpoint && HttpMethod.DELETE.is(request.getMethod())) {
        // query cancellation request
        for (final String host : hostFinder.getAllHosts()) {
            // to keep the code simple, the proxy servlet will also send a request to one of the default brokers
            if (!host.equals(defaultHost)) {
                // issue async requests
                broadcastClient.newRequest(rewriteURI(request, host)).method(HttpMethod.DELETE).timeout(CANCELLATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).send(new Response.CompleteListener() {

                    @Override
                    public void onComplete(Result result) {
                        if (result.isFailed()) {
                            log.warn(result.getFailure(), "Failed to forward cancellation request to [%s]", host);
                        }
                    }
                });
            }
            interruptedQueryCount.incrementAndGet();
        }
    } else if (isQueryEndpoint && HttpMethod.POST.is(request.getMethod())) {
        // query request
        try {
            Query inputQuery = objectMapper.readValue(request.getInputStream(), Query.class);
            if (inputQuery != null) {
                request.setAttribute(HOST_ATTRIBUTE, hostFinder.getHost(inputQuery));
                if (inputQuery.getId() == null) {
                    inputQuery = inputQuery.withId(UUID.randomUUID().toString());
                }
            }
            request.setAttribute(QUERY_ATTRIBUTE, inputQuery);
        } catch (IOException e) {
            log.warn(e, "Exception parsing query");
            final String errorMessage = e.getMessage() == null ? "no error message" : e.getMessage();
            requestLogger.log(new RequestLogLine(new DateTime(), request.getRemoteAddr(), null, new QueryStats(ImmutableMap.<String, Object>of("success", false, "exception", errorMessage))));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType(MediaType.APPLICATION_JSON);
            objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
            return;
        } catch (Exception e) {
            handleException(response, objectMapper, e);
            return;
        }
    }
    super.service(request, response);
}
Also used : Query(io.druid.query.Query) IOException(java.io.IOException) DateTime(org.joda.time.DateTime) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Result(org.eclipse.jetty.client.api.Result) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 92 with Result

use of org.eclipse.jetty.client.api.Result in project jetty.project by eclipse.

the class HttpClientTest method testSmallAsyncContent.

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

        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            ServletOutputStream output = response.getOutputStream();
            output.write(65);
            output.flush();
            output.write(66);
        }
    });
    final AtomicInteger contentCount = new AtomicInteger();
    final AtomicReference<Callback> callbackRef = new AtomicReference<>();
    final AtomicReference<CountDownLatch> contentLatch = new AtomicReference<>(new CountDownLatch(1));
    final CountDownLatch completeLatch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onResponseContentAsync(new Response.AsyncContentListener() {

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            contentCount.incrementAndGet();
            callbackRef.set(callback);
            contentLatch.get().countDown();
        }
    }).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            completeLatch.countDown();
        }
    });
    Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
    Callback callback = callbackRef.get();
    // Wait a while to be sure that the parsing does not proceed.
    TimeUnit.MILLISECONDS.sleep(1000);
    Assert.assertEquals(1, contentCount.get());
    // Succeed the content callback to proceed with parsing.
    callbackRef.set(null);
    contentLatch.set(new CountDownLatch(1));
    callback.succeeded();
    Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
    callback = callbackRef.get();
    // Wait a while to be sure that the parsing does not proceed.
    TimeUnit.MILLISECONDS.sleep(1000);
    Assert.assertEquals(2, contentCount.get());
    Assert.assertEquals(1, completeLatch.getCount());
    // Succeed the content callback to proceed with parsing.
    callbackRef.set(null);
    contentLatch.set(new CountDownLatch(1));
    callback.succeeded();
    Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(2, contentCount.get());
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) Result(org.eclipse.jetty.client.api.Result) 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) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 93 with Result

use of org.eclipse.jetty.client.api.Result in project jetty.project by eclipse.

the class HttpClientTest method testLongPollIsAbortedWhenClientIsStopped.

@Test
public void testLongPollIsAbortedWhenClientIsStopped() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    start(new AbstractHandler() {

        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            request.startAsync();
            latch.countDown();
        }
    });
    final CountDownLatch completeLatch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isFailed())
                completeLatch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    // Stop the client, the complete listener must be invoked.
    client.stop();
    Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) Result(org.eclipse.jetty.client.api.Result) 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) Test(org.junit.Test)

Example 94 with Result

use of org.eclipse.jetty.client.api.Result in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testClientRequestReadFailsOnFirstRead.

@Test
public void testClientRequestReadFailsOnFirstRead() throws Exception {
    startServer(new EchoHttpServlet());
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected int readClientRequestContent(ServletInputStream input, byte[] buffer) throws IOException {
            throw new IOException("explicitly_thrown_by_test");
        }
    });
    startClient();
    final CountDownLatch latch = new CountDownLatch(1);
    DeferredContentProvider content = new DeferredContentProvider();
    client.newRequest("localhost", serverConnector.getLocalPort()).content(content).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            System.err.println(result);
            if (result.getResponse().getStatus() == 500)
                latch.countDown();
        }
    });
    content.offer(ByteBuffer.allocate(512));
    sleep(1000);
    content.offer(ByteBuffer.allocate(512));
    content.close();
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Result(org.eclipse.jetty.client.api.Result) Test(org.junit.Test)

Example 95 with Result

use of org.eclipse.jetty.client.api.Result in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testUpstreamTransformationThrowsAfterCommittingProxyRequest.

@Test
public void testUpstreamTransformationThrowsAfterCommittingProxyRequest() throws Exception {
    try (StacklessLogging scope = new StacklessLogging(HttpChannel.class)) {
        startServer(new EchoHttpServlet());
        startProxy(new AsyncMiddleManServlet() {

            @Override
            protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
                return new ContentTransformer() {

                    private int count;

                    @Override
                    public void transform(ByteBuffer input, boolean finished, List<ByteBuffer> output) throws IOException {
                        if (++count < 2)
                            output.add(input);
                        else
                            throw new NullPointerException("explicitly_thrown_by_test");
                    }
                };
            }
        });
        startClient();
        final CountDownLatch latch = new CountDownLatch(1);
        DeferredContentProvider content = new DeferredContentProvider();
        client.newRequest("localhost", serverConnector.getLocalPort()).content(content).send(new Response.CompleteListener() {

            @Override
            public void onComplete(Result result) {
                if (result.isSucceeded() && result.getResponse().getStatus() == 502)
                    latch.countDown();
            }
        });
        content.offer(ByteBuffer.allocate(512));
        sleep(1000);
        content.offer(ByteBuffer.allocate(512));
        content.close();
        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    }
}
Also used : Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Test(org.junit.Test)

Aggregations

Result (org.eclipse.jetty.client.api.Result)100 Test (org.junit.Test)80 CountDownLatch (java.util.concurrent.CountDownLatch)79 HttpServletResponse (javax.servlet.http.HttpServletResponse)74 HttpServletRequest (javax.servlet.http.HttpServletRequest)66 Response (org.eclipse.jetty.client.api.Response)62 IOException (java.io.IOException)60 ServletException (javax.servlet.ServletException)56 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)44 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)41 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)39 Request (org.eclipse.jetty.client.api.Request)31 ByteBuffer (java.nio.ByteBuffer)29 Request (org.eclipse.jetty.server.Request)27 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)24 InterruptedIOException (java.io.InterruptedIOException)21 ServletOutputStream (javax.servlet.ServletOutputStream)20 Slow (org.eclipse.jetty.toolchain.test.annotation.Slow)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)16 BytesContentProvider (org.eclipse.jetty.client.util.BytesContentProvider)16