Search in sources :

Example 21 with AsyncListener

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

the class HttpSession method createConnection.

/**
 * Creates a new connection on this session.
 *
 * @param body the body element that was sent containing the request for a new session.
 * @param context the context of the asynchronous servlet call leading up to this method call.
 * @return the created {@link org.jivesoftware.openfire.http.HttpConnection} which represents
 *         the connection.
 */
@Nonnull
synchronized HttpConnection createConnection(@Nonnull final HttpBindBody body, @Nonnull final AsyncContext context) {
    final HttpConnection connection = new HttpConnection(body, context);
    final StreamID streamID = getStreamID();
    final long rid = body.getRid();
    if (Log.isDebugEnabled()) {
        Log.debug("Creating connection for rid: {} in session {}", rid, streamID);
    }
    connection.setSession(this);
    context.setTimeout(getWait().toMillis());
    context.addListener(new AsyncListener() {

        @Override
        public void onComplete(AsyncEvent asyncEvent) {
            if (Log.isTraceEnabled()) {
                Log.trace("Session {} Request ID {}, event complete: {}", streamID, rid, asyncEvent);
            }
            synchronized (connectionQueue) {
                connectionQueue.remove(connection);
                lastActivity = Instant.now();
            }
            SessionEventDispatcher.dispatchEvent(HttpSession.this, SessionEventDispatcher.EventType.connection_closed, connection, context);
        }

        @Override
        public void onTimeout(AsyncEvent asyncEvent) throws IOException {
            if (Log.isTraceEnabled()) {
                Log.trace("Session {} Request ID {}, event timeout: {}. Returning an empty response.", streamID, rid, asyncEvent);
            }
            try {
                // This is why this body is to be delivered in a non-async fashion.
                synchronized (connectionQueue) {
                    deliver(connection, Collections.singletonList(new Deliverable("")), false);
                    setLastResponseEmpty(true);
                }
            } catch (HttpConnectionClosedException e) {
                Log.warn("Unexpected exception while processing connection timeout.", e);
            }
        // Note that 'onComplete' will be invoked.
        }

        @Override
        public void onError(AsyncEvent asyncEvent) {
            if (Log.isTraceEnabled()) {
                Log.trace("Session {} Request ID {}, event error: {}", streamID, rid, asyncEvent);
            }
            Log.warn("For session {} an unhandled AsyncListener error occurred: ", streamID, asyncEvent.getThrowable());
            synchronized (connectionQueue) {
                connectionQueue.remove(connection);
            }
            SessionEventDispatcher.dispatchEvent(HttpSession.this, SessionEventDispatcher.EventType.connection_closed, connection, context);
        }

        @Override
        public void onStartAsync(AsyncEvent asyncEvent) {
            if (Log.isTraceEnabled()) {
                Log.trace("Session {} Request ID {}, event start: {}", streamID, rid, asyncEvent);
            }
        }
    });
    return connection;
}
Also used : StreamID(org.jivesoftware.openfire.StreamID) AsyncListener(javax.servlet.AsyncListener) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) Nonnull(javax.annotation.Nonnull)

Example 22 with AsyncListener

use of javax.servlet.AsyncListener in project ddf by codice.

the class ServletMetricsTest method asyncDoFilterTimeout.

@Test
public void asyncDoFilterTimeout() throws Exception {
    when(mockRequest.isAsyncStarted()).thenReturn(true);
    AsyncContext asyncContext = mock(AsyncContext.class);
    when(mockRequest.getAsyncContext()).thenReturn(asyncContext);
    AsyncEvent event = mock(AsyncEvent.class);
    when(event.getSuppliedRequest()).thenReturn(mockRequest);
    when(event.getSuppliedResponse()).thenReturn(mockResponse);
    underTest.doFilter(mockRequest, mockResponse, mockFilterChain);
    ArgumentCaptor<AsyncListener> arg = ArgumentCaptor.forClass(AsyncListener.class);
    verify(asyncContext).addListener(arg.capture());
    AsyncListener listener = arg.getValue();
    listener.onStartAsync(event);
    listener.onTimeout(event);
    listener.onComplete(event);
    assertThat(meterRegistry.summary(LATENCY, getTags(DEFAULT_METHOD, 408)).count(), is(1L));
}
Also used : AsyncListener(javax.servlet.AsyncListener) AsyncContext(javax.servlet.AsyncContext) AsyncEvent(javax.servlet.AsyncEvent) Test(org.junit.Test)

Example 23 with AsyncListener

use of javax.servlet.AsyncListener in project ddf by codice.

the class ServletMetricsTest method asyncDoFilter.

@Test
public void asyncDoFilter() throws Exception {
    when(mockRequest.isAsyncStarted()).thenReturn(true);
    AsyncContext asyncContext = mock(AsyncContext.class);
    when(mockRequest.getAsyncContext()).thenReturn(asyncContext);
    AsyncEvent event = mock(AsyncEvent.class);
    when(event.getSuppliedRequest()).thenReturn(mockRequest);
    when(event.getSuppliedResponse()).thenReturn(mockResponse);
    underTest.doFilter(mockRequest, mockResponse, mockFilterChain);
    ArgumentCaptor<AsyncListener> arg = ArgumentCaptor.forClass(AsyncListener.class);
    verify(asyncContext).addListener(arg.capture());
    AsyncListener listener = arg.getValue();
    assertThat(meterRegistry.summary(LATENCY, tags).count(), is(0L));
    listener.onStartAsync(event);
    listener.onComplete(event);
    assertThat(meterRegistry.summary(LATENCY, tags).count(), is(1L));
}
Also used : AsyncListener(javax.servlet.AsyncListener) AsyncContext(javax.servlet.AsyncContext) AsyncEvent(javax.servlet.AsyncEvent) Test(org.junit.Test)

Example 24 with AsyncListener

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

the class IdleTimeoutHandler method handle.

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    final HttpChannel channel = baseRequest.getHttpChannel();
    final long idle_timeout = baseRequest.getHttpChannel().getIdleTimeout();
    channel.setIdleTimeout(_idleTimeoutMs);
    try {
        super.handle(target, baseRequest, request, response);
    } finally {
        if (_applyToAsync && request.isAsyncStarted()) {
            request.getAsyncContext().addListener(new AsyncListener() {

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

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

                @Override
                public void onError(AsyncEvent event) throws IOException {
                    channel.setIdleTimeout(idle_timeout);
                }

                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    channel.setIdleTimeout(idle_timeout);
                }
            });
        } else
            channel.setIdleTimeout(idle_timeout);
    }
}
Also used : AsyncListener(javax.servlet.AsyncListener) HttpChannel(org.eclipse.jetty.server.HttpChannel) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent)

Example 25 with AsyncListener

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

the class StatisticsHandlerTest method testSuspendExpire.

@Test
public void testSuspendExpire() throws Exception {
    final long dispatchTime = 10;
    final long timeout = 100;
    final AtomicReference<AsyncContext> asyncHolder = new AtomicReference<>();
    final CyclicBarrier[] barrier = { new CyclicBarrier(2), new CyclicBarrier(2), new CyclicBarrier(2) };
    _statsHandler.setHandler(new AbstractHandler() {

        @Override
        public void handle(String path, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
            request.setHandled(true);
            try {
                barrier[0].await();
                Thread.sleep(dispatchTime);
                if (asyncHolder.get() == null) {
                    AsyncContext async = request.startAsync();
                    asyncHolder.set(async);
                    async.setTimeout(timeout);
                }
            } catch (Exception x) {
                throw new ServletException(x);
            } finally {
                try {
                    barrier[1].await();
                } catch (Exception ignored) {
                }
            }
        }
    });
    _server.start();
    String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
    _connector.executeRequest(request);
    barrier[0].await();
    assertEquals(1, _statistics.getConnections());
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(1, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(1, _statsHandler.getDispatchedActive());
    barrier[1].await();
    assertTrue(_latchHandler.await());
    assertNotNull(asyncHolder.get());
    asyncHolder.get().addListener(new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            event.getAsyncContext().complete();
        }

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

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

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            try {
                barrier[2].await();
            } catch (Exception ignored) {
            }
        }
    });
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(1, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(0, _statsHandler.getDispatchedActive());
    barrier[2].await();
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(0, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(0, _statsHandler.getDispatchedActive());
    assertEquals(1, _statsHandler.getAsyncRequests());
    assertEquals(0, _statsHandler.getAsyncDispatches());
    assertEquals(1, _statsHandler.getExpires());
    assertEquals(1, _statsHandler.getResponses2xx());
    assertTrue(_statsHandler.getRequestTimeTotal() >= (timeout + dispatchTime) * 3 / 4);
    assertEquals(_statsHandler.getRequestTimeTotal(), _statsHandler.getRequestTimeMax());
    assertEquals(_statsHandler.getRequestTimeTotal(), _statsHandler.getRequestTimeMean(), 0.01);
    assertThat(_statsHandler.getDispatchedTimeTotal(), greaterThanOrEqualTo(dispatchTime * 3 / 4));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) CyclicBarrier(java.util.concurrent.CyclicBarrier) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AsyncListener(javax.servlet.AsyncListener) Test(org.junit.Test)

Aggregations

AsyncListener (javax.servlet.AsyncListener)45 AsyncContext (javax.servlet.AsyncContext)32 AsyncEvent (javax.servlet.AsyncEvent)30 IOException (java.io.IOException)28 HttpServletResponse (javax.servlet.http.HttpServletResponse)16 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ServletException (javax.servlet.ServletException)12 Test (org.junit.Test)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 CountDownLatch (java.util.concurrent.CountDownLatch)5 HttpServlet (javax.servlet.http.HttpServlet)5 OutputStream (java.io.OutputStream)4 Socket (java.net.Socket)3 URISyntaxException (java.net.URISyntaxException)3 CyclicBarrier (java.util.concurrent.CyclicBarrier)3 Request (org.eclipse.jetty.server.Request)3 Locker (org.eclipse.jetty.util.thread.Locker)3 RequestContext (com.linkedin.r2.message.RequestContext)2 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)2 TransportResponse (com.linkedin.r2.transport.common.bridge.common.TransportResponse)2