Search in sources :

Example 31 with AsyncEvent

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

the class AsyncContextListenersTest method testAsyncDispatchAsyncCompletePreservesListener.

@Test
public void testAsyncDispatchAsyncCompletePreservesListener() throws Exception {
    final AtomicReference<CountDownLatch> completes = new AtomicReference<>(new CountDownLatch(1));
    final String path = "/path";
    prepare(path + "/*", new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String requestURI = request.getRequestURI();
            if (requestURI.endsWith("/one")) {
                AsyncContext asyncContext = request.startAsync(request, response);
                asyncContext.addListener(new AsyncListener() {

                    @Override
                    public void onStartAsync(AsyncEvent event) throws IOException {
                        event.getAsyncContext().addListener(this);
                    }

                    @Override
                    public void onComplete(AsyncEvent event) throws IOException {
                        completes.get().countDown();
                    }

                    @Override
                    public void onTimeout(AsyncEvent event) throws IOException {
                    }

                    @Override
                    public void onError(AsyncEvent event) throws IOException {
                    }
                });
                // This dispatch() will call startAsync() again which will
                // clear the previous listeners (as per the specification)
                // but add a new listener from onStartAsync().
                asyncContext.dispatch(path + "/two");
            } else if (requestURI.endsWith("/two")) {
                AsyncContext asyncContext = request.startAsync(request, response);
                asyncContext.complete();
            }
        }
    });
    try (Socket socket = new Socket("localhost", _connector.getLocalPort())) {
        OutputStream output = socket.getOutputStream();
        String request = "" + "GET " + path + "/one HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        HttpTester.Input input = HttpTester.from(socket.getInputStream());
        HttpTester.Response response = HttpTester.parseResponse(input);
        Assert.assertEquals(200, response.getStatus());
        completes.get().await(10, TimeUnit.SECONDS);
        // Send a second request
        completes.set(new CountDownLatch(1));
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        response = HttpTester.parseResponse(input);
        Assert.assertEquals(200, response.getStatus());
        completes.get().await(10, TimeUnit.SECONDS);
    }
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncEvent(javax.servlet.AsyncEvent) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AsyncListener(javax.servlet.AsyncListener) Socket(java.net.Socket) Test(org.junit.Test)

Example 32 with AsyncEvent

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

the class AsyncListenerTest method test_StartAsync_OnComplete_Throw.

@Test
public void test_StartAsync_OnComplete_Throw() throws Exception {
    ServletContextHandler context = new ServletContextHandler();
    context.addServlet(new ServletHolder(new HttpServlet() {

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

                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    throw new TestRuntimeException();
                }
            });
            response.getOutputStream().print("DATA");
            asyncContext.complete();
        }
    }), "/*");
    startServer(context);
    String httpResponse = connector.getResponse("" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n");
    assertThat(httpResponse, containsString("HTTP/1.1 200 "));
    assertThat(httpResponse, containsString("DATA"));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) Matchers.containsString(org.hamcrest.Matchers.containsString) AsyncEvent(javax.servlet.AsyncEvent) Test(org.junit.Test)

Example 33 with AsyncEvent

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

the class AsyncListenerTest method test_StartAsync_OnTimeout_CalledBy_PooledThread.

@Test
public void test_StartAsync_OnTimeout_CalledBy_PooledThread() throws Exception {
    String threadNamePrefix = "async_listener";
    threadPool = new QueuedThreadPool();
    threadPool.setName(threadNamePrefix);
    ServletContextHandler context = new ServletContextHandler();
    context.addServlet(new ServletHolder(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(1000);
            asyncContext.addListener(new AsyncListenerAdapter() {

                @Override
                public void onTimeout(AsyncEvent event) throws IOException {
                    if (Thread.currentThread().getName().startsWith(threadNamePrefix))
                        response.setStatus(HttpStatus.OK_200);
                    else
                        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
                    asyncContext.complete();
                }
            });
        }
    }), "/*");
    startServer(context);
    HttpTester.Response response = HttpTester.parseResponse(connector.getResponse("" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n"));
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Test(org.junit.Test)

Example 34 with AsyncEvent

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

the class ProxyServletTest method testProxyLongPoll.

@Test
public void testProxyLongPoll() throws Exception {
    final long timeout = 1000;
    startServer(new HttpServlet() {

        @Override
        protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
            if (!request.isAsyncStarted()) {
                final AsyncContext asyncContext = request.startAsync();
                asyncContext.setTimeout(timeout);
                asyncContext.addListener(new AsyncListener() {

                    @Override
                    public void onComplete(AsyncEvent event) throws IOException {
                    }

                    @Override
                    public void onTimeout(AsyncEvent event) throws IOException {
                        if (request.getHeader("Via") != null)
                            response.addHeader(PROXIED_HEADER, "true");
                        asyncContext.complete();
                    }

                    @Override
                    public void onError(AsyncEvent event) throws IOException {
                    }

                    @Override
                    public void onStartAsync(AsyncEvent event) throws IOException {
                    }
                });
            }
        }
    });
    startProxy();
    startClient();
    Response response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(2 * timeout, TimeUnit.MILLISECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServlet(javax.servlet.http.HttpServlet) AsyncListener(javax.servlet.AsyncListener) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) Test(org.junit.Test)

Example 35 with AsyncEvent

use of javax.servlet.AsyncEvent in project Openfire by igniterealtime.

the class HttpSession method createConnection.

/**
     * Creates a new connection on this session. If a response is currently available for this
     * session the connection is responded to immediately, otherwise it is queued awaiting a
     * response.
     *
     * @param rid the request id related to the connection.
     * @param isSecure true if the connection was secured using HTTPS.
     * @return the created {@link org.jivesoftware.openfire.http.HttpConnection} which represents
     *         the connection.
     *
     * @throws HttpConnectionClosedException if the connection was closed before a response could be
     * delivered.
     * @throws HttpBindException if the connection has violated a facet of the HTTP binding
     * protocol.
     */
synchronized HttpConnection createConnection(long rid, boolean isSecure, boolean isPoll, AsyncContext context) throws HttpConnectionClosedException, HttpBindException, IOException {
    final HttpConnection connection = new HttpConnection(rid, isSecure, sslCertificates, context);
    connection.setSession(this);
    context.setTimeout(getWait() * JiveConstants.SECOND);
    context.addListener(new AsyncListener() {

        @Override
        public void onComplete(AsyncEvent asyncEvent) throws IOException {
            Log.debug("complete event " + asyncEvent);
            connectionQueue.remove(connection);
            fireConnectionClosed(connection);
        }

        @Override
        public void onTimeout(AsyncEvent asyncEvent) throws IOException {
            Log.debug("timeout event " + asyncEvent);
            try {
                // If onTimeout does not result in a complete(), the container falls back to default behavior.
                // This is why this body is to be delivered in a non-async fashion.
                connection.deliverBody(createEmptyBody(false), false);
                setLastResponseEmpty(true);
                // This connection timed out we need to increment the request count
                if (connection.getRequestId() != lastRequestID + 1) {
                    throw new IOException("Unexpected RID error.");
                }
                lastRequestID = connection.getRequestId();
            } catch (HttpConnectionClosedException e) {
                Log.warn("Unexpected exception while processing connection timeout.", e);
            }
        // Note that 'onComplete' will be invoked.
        }

        @Override
        public void onError(AsyncEvent asyncEvent) throws IOException {
            Log.debug("error event " + asyncEvent);
            Log.warn("Unhandled AsyncListener error: " + asyncEvent.getThrowable());
            connectionQueue.remove(connection);
            fireConnectionClosed(connection);
        }

        @Override
        public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
        }
    });
    if (rid <= lastRequestID) {
        Delivered deliverable = retrieveDeliverable(rid);
        if (deliverable == null) {
            Log.warn("Deliverable unavailable for " + rid);
            throw new HttpBindException("Unexpected RID error.", BoshBindingError.itemNotFound);
        }
        connection.deliverBody(createDeliverable(deliverable.deliverables), true);
        addConnection(connection, isPoll);
        return connection;
    } else if (rid > (lastRequestID + maxRequests)) {
        Log.warn("Request " + rid + " > " + (lastRequestID + maxRequests) + ", ending session.");
        throw new HttpBindException("Unexpected RID error.", BoshBindingError.itemNotFound);
    }
    addConnection(connection, isPoll);
    return connection;
}
Also used : AsyncListener(javax.servlet.AsyncListener) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent)

Aggregations

AsyncEvent (javax.servlet.AsyncEvent)39 IOException (java.io.IOException)27 Test (org.junit.Test)21 AsyncListener (javax.servlet.AsyncListener)20 AsyncContext (javax.servlet.AsyncContext)19 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 HttpServletRequest (javax.servlet.http.HttpServletRequest)16 ServletException (javax.servlet.ServletException)12 HttpServlet (javax.servlet.http.HttpServlet)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 OutputStream (java.io.OutputStream)4 Request (org.eclipse.jetty.server.Request)4 Socket (java.net.Socket)3 URISyntaxException (java.net.URISyntaxException)3 CyclicBarrier (java.util.concurrent.CyclicBarrier)3 ServletResponse (javax.servlet.ServletResponse)3 HttpTester (org.eclipse.jetty.http.HttpTester)3 MockAsyncContext (org.springframework.mock.web.test.MockAsyncContext)3 RequestContext (com.linkedin.r2.message.RequestContext)2