Search in sources :

Example 76 with AsyncContext

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

the class QoSFilter method doFilter.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    boolean accepted = false;
    try {
        Boolean suspended = (Boolean) request.getAttribute(_suspended);
        if (suspended == null) {
            accepted = _passes.tryAcquire(getWaitMs(), TimeUnit.MILLISECONDS);
            if (accepted) {
                request.setAttribute(_suspended, Boolean.FALSE);
                if (LOG.isDebugEnabled())
                    LOG.debug("Accepted {}", request);
            } else {
                request.setAttribute(_suspended, Boolean.TRUE);
                int priority = getPriority(request);
                AsyncContext asyncContext = request.startAsync();
                long suspendMs = getSuspendMs();
                if (suspendMs > 0)
                    asyncContext.setTimeout(suspendMs);
                asyncContext.addListener(_listeners[priority]);
                _queues[priority].add(asyncContext);
                if (LOG.isDebugEnabled())
                    LOG.debug("Suspended {}", request);
                return;
            }
        } else {
            if (suspended) {
                request.setAttribute(_suspended, Boolean.FALSE);
                Boolean resumed = (Boolean) request.getAttribute(_resumed);
                if (resumed == Boolean.TRUE) {
                    _passes.acquire();
                    accepted = true;
                    if (LOG.isDebugEnabled())
                        LOG.debug("Resumed {}", request);
                } else {
                    // Timeout! try 1 more time.
                    accepted = _passes.tryAcquire(getWaitMs(), TimeUnit.MILLISECONDS);
                    if (LOG.isDebugEnabled())
                        LOG.debug("Timeout {}", request);
                }
            } else {
                // Pass through resume of previously accepted request.
                _passes.acquire();
                accepted = true;
                if (LOG.isDebugEnabled())
                    LOG.debug("Passthrough {}", request);
            }
        }
        if (accepted) {
            chain.doFilter(request, response);
        } else {
            if (LOG.isDebugEnabled())
                LOG.debug("Rejected {}", request);
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (InterruptedException e) {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } finally {
        if (accepted) {
            for (int p = _queues.length - 1; p >= 0; --p) {
                AsyncContext asyncContext = _queues[p].poll();
                if (asyncContext != null) {
                    ServletRequest candidate = asyncContext.getRequest();
                    Boolean suspended = (Boolean) candidate.getAttribute(_suspended);
                    if (suspended == Boolean.TRUE) {
                        candidate.setAttribute(_resumed, Boolean.TRUE);
                        asyncContext.dispatch();
                        break;
                    }
                }
            }
            _passes.release();
        }
    }
}
Also used : ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext)

Example 77 with AsyncContext

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

the class AsyncScheduledDispatchWrite method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Boolean suspended = (Boolean) request.getAttribute("SUSPENDED");
    if (suspended == null || !suspended) {
        request.setAttribute("SUSPENDED", Boolean.TRUE);
        AsyncContext ctx;
        if (originalReqResp) {
            // Use Original Request & Response
            ctx = request.startAsync();
        } else {
            // Pass Request & Response
            ctx = request.startAsync(request, response);
        }
        ctx.setTimeout(0);
        scheduler.schedule(new DispatchBack(ctx), 500, TimeUnit.MILLISECONDS);
    } else {
        String fileName = request.getServletPath();
        byte[] dataBytes = loadContentFileBytes(fileName);
        response.setContentLength(dataBytes.length);
        ServletOutputStream out = response.getOutputStream();
        if (fileName.endsWith("txt"))
            response.setContentType("text/plain");
        else if (fileName.endsWith("mp3"))
            response.setContentType("audio/mpeg");
        response.setHeader("ETag", "W/etag-" + fileName);
        out.write(dataBytes);
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) AsyncContext(javax.servlet.AsyncContext)

Example 78 with AsyncContext

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

the class AsyncTimeoutDispatchWrite method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    AsyncContext ctx = (AsyncContext) request.getAttribute(AsyncContext.class.getName());
    if (ctx == null) {
        // First pass through
        if (originalReqResp) {
            // Use Original Request & Response
            ctx = request.startAsync();
        } else {
            // Pass Request & Response
            ctx = request.startAsync(request, response);
        }
        ctx.addListener(this);
        ctx.setTimeout(200);
        request.setAttribute(AsyncContext.class.getName(), ctx);
    } else {
        // second pass through, as result of timeout -> dispatch
        String fileName = request.getServletPath();
        byte[] dataBytes = loadContentFileBytes(fileName);
        response.setContentLength(dataBytes.length);
        ServletOutputStream out = response.getOutputStream();
        if (fileName.endsWith("txt"))
            response.setContentType("text/plain");
        else if (fileName.endsWith("mp3"))
            response.setContentType("audio/mpeg");
        response.setHeader("ETag", "W/etag-" + fileName);
        out.write(dataBytes);
    // no need to call AsyncContext.complete() from here
    // in fact, it will cause an IllegalStateException if we do
    // ctx.complete();
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) AsyncContext(javax.servlet.AsyncContext)

Example 79 with AsyncContext

use of javax.servlet.AsyncContext 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 80 with AsyncContext

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

Aggregations

AsyncContext (javax.servlet.AsyncContext)120 IOException (java.io.IOException)61 HttpServletRequest (javax.servlet.http.HttpServletRequest)53 ServletException (javax.servlet.ServletException)52 HttpServletResponse (javax.servlet.http.HttpServletResponse)50 Test (org.junit.Test)43 CountDownLatch (java.util.concurrent.CountDownLatch)33 HttpServlet (javax.servlet.http.HttpServlet)32 InterruptedIOException (java.io.InterruptedIOException)24 ServletOutputStream (javax.servlet.ServletOutputStream)20 ReadListener (javax.servlet.ReadListener)19 ServletInputStream (javax.servlet.ServletInputStream)19 AsyncEvent (javax.servlet.AsyncEvent)18 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)18 AsyncListener (javax.servlet.AsyncListener)15 UncheckedIOException (java.io.UncheckedIOException)14 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)14 Request (org.eclipse.jetty.server.Request)13 Matchers.containsString (org.hamcrest.Matchers.containsString)13 WriteListener (javax.servlet.WriteListener)11