javax.servlet.AsyncListener Java Examples

The following examples show how to use javax.servlet.AsyncListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenEJBAsyncContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void complete() {
    for (final AsyncListener listener : listeners) {
        try {
            listener.onComplete(event);
        } catch (final IOException t) {
            throw new OpenEJBRuntimeException(t);
        }
    }

    try {
        commit();
    } finally {
        INITIALIZED.remove(this);
    }
}
 
Example #2
Source File: OpenEJBAsyncContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static void destroy() {
    if (es == null) {
        return;
    }
    es.shutdownNow();
    for (final OpenEJBAsyncContext ctx : new ArrayList<>(INITIALIZED)) {
        if (ctx.lastTouch + ctx.getTimeout() < System.currentTimeMillis()) {
            for (final AsyncListener listener : ctx.listeners) {
                try {
                    listener.onTimeout(ctx.event);
                } catch (final IOException t) {
                    throw new OpenEJBRuntimeException(t);
                }
            }
            ctx.complete();
        }
    }
    INITIALIZED.clear();
}
 
Example #3
Source File: NettyAsyncContext.java    From Jinx with Apache License 2.0 6 votes vote down vote up
@Override
public void dispatch(ServletContext context, String path) {
    final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    httpRequest.setAttribute(ASYNC_CONTEXT_PATH, httpRequest.getContextPath());
    httpRequest.setAttribute(ASYNC_PATH_INFO, httpRequest.getPathInfo());
    httpRequest.setAttribute(ASYNC_QUERY_STRING, httpRequest.getQueryString());
    httpRequest.setAttribute(ASYNC_REQUEST_URI, httpRequest.getRequestURI());
    httpRequest.setAttribute(ASYNC_SERVLET_PATH, httpRequest.getServletPath());
    final NettyRequestDispatcher dispatcher = (NettyRequestDispatcher) context.getRequestDispatcher(path);
    ctx.executor().submit(() -> {
        try {
            dispatcher.dispatch(httpRequest, servletResponse);
            // TODO is this right?
            for (AsyncListener listener : ImmutableList.copyOf(listeners)) {
                listener.onComplete(new AsyncEvent(NettyAsyncContext.this));
            }
        } catch (ServletException | IOException e) {
            // TODO notify listeners
            e.printStackTrace();
        }
    });
}
 
Example #4
Source File: AsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void addListener(AsyncListener listener) {
    check();
    AsyncListenerWrapper wrapper = new AsyncListenerWrapper();
    wrapper.setListener(listener);
    listeners.add(wrapper);
}
 
Example #5
Source File: RequestTracingFilterTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
private void setupAsyncContextWorkflow() {
    listenerCapturingAsyncContext = mock(AsyncContext.class);
    capturedAsyncListeners = new ArrayList<>();

    doReturn(listenerCapturingAsyncContext).when(requestMock).getAsyncContext();
    doReturn(true).when(requestMock).isAsyncStarted();

    doAnswer(invocation -> {
        capturedAsyncListeners.add((AsyncListener) invocation.getArguments()[0]);
        return null;
    }).when(listenerCapturingAsyncContext).addListener(
        any(AsyncListener.class), any(ServletRequest.class), any(ServletResponse.class)
    );
}
 
Example #6
Source File: AsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void addListener(AsyncListener listener) {
    check();
    AsyncListenerWrapper wrapper = new AsyncListenerWrapper();
    wrapper.setListener(listener);
    listeners.add(wrapper);
}
 
Example #7
Source File: AsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void addListener(AsyncListener listener, ServletRequest servletRequest,
        ServletResponse servletResponse) {
    check();
    AsyncListenerWrapper wrapper = new AsyncListenerWrapper();
    wrapper.setListener(listener);
    wrapper.setServletRequest(servletRequest);
    wrapper.setServletResponse(servletResponse);
    listeners.add(wrapper);
}
 
Example #8
Source File: MockAsyncContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void complete() {
	MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(this.request, MockHttpServletRequest.class);
	if (mockRequest != null) {
		mockRequest.setAsyncStarted(false);
	}
	for (AsyncListener listener : this.listeners) {
		try {
			listener.onComplete(new AsyncEvent(this, this.request, this.response));
		}
		catch (IOException ex) {
			throw new IllegalStateException("AsyncListener failure", ex);
		}
	}
}
 
Example #9
Source File: HttpServletRequestImplInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
    if (validate(target, result, throwable)) {
        final AsyncContext asyncContext = (AsyncContext) result;
        final AsyncListener asyncListener = new ResinAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
        asyncContext.addListener(asyncListener);
        if (isDebug) {
            logger.debug("Add async listener {}", asyncListener);
        }
    }
    recorder.recordServiceType(ResinConstants.RESIN_METHOD);
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);
}
 
Example #10
Source File: MockAsyncContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void complete() {
	MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(this.request, MockHttpServletRequest.class);
	if (mockRequest != null) {
		mockRequest.setAsyncStarted(false);
	}
	for (AsyncListener listener : this.listeners) {
		try {
			listener.onComplete(new AsyncEvent(this, this.request, this.response));
		}
		catch (IOException ex) {
			throw new IllegalStateException("AsyncListener failure", ex);
		}
	}
}
 
Example #11
Source File: AsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void addListener(AsyncListener listener) {
    check();
    AsyncListenerWrapper wrapper = new AsyncListenerWrapper();
    wrapper.setListener(listener);
    listeners.add(wrapper);
}
 
Example #12
Source File: WCCRequestImplStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
    if (validate(target, result, throwable)) {
        final AsyncContext asyncContext = (AsyncContext) result;
        final AsyncListener asyncListener = new WebsphereAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
        asyncContext.addListener(asyncListener);
        if (isDebug) {
            logger.debug("Add async listener {}", asyncListener);
        }
    }
    recorder.recordServiceType(WebsphereConstants.WEBSPHERE_METHOD);
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);
}
 
Example #13
Source File: ServletRuntimeTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Test
public void setupTracingCompletionWhenAsyncRequestCompletes_should_add_WingtipsRequestSpanCompletionAsyncListener(
) {
    // given
    AsyncContext asyncContextMock = mock(AsyncContext.class);
    doReturn(asyncContextMock).when(requestMock).getAsyncContext();
    TracingState tracingStateMock = mock(TracingState.class);
    HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> tagStrategyMock =
        mock(HttpTagAndSpanNamingStrategy.class);
    HttpTagAndSpanNamingAdapter<HttpServletRequest,HttpServletResponse> tagAdapterMock =
        mock(HttpTagAndSpanNamingAdapter.class);

    ArgumentCaptor<AsyncListener> listenerCaptor = ArgumentCaptor.forClass(AsyncListener.class);

    // when
    servlet3Runtime.setupTracingCompletionWhenAsyncRequestCompletes(
        requestMock, responseMock, tracingStateMock, tagStrategyMock, tagAdapterMock
    );

    // then
    verify(asyncContextMock).addListener(listenerCaptor.capture(), eq(requestMock), eq(responseMock));
    List<AsyncListener> addedListeners = listenerCaptor.getAllValues();
    assertThat(addedListeners).hasSize(1);
    assertThat(addedListeners.get(0)).isInstanceOf(WingtipsRequestSpanCompletionAsyncListener.class);
    WingtipsRequestSpanCompletionAsyncListener listener =
        (WingtipsRequestSpanCompletionAsyncListener)addedListeners.get(0);
    assertThat(listener.originalRequestTracingState).isSameAs(tracingStateMock);
    assertThat(listener.tagAndNamingStrategy).isSameAs(tagStrategyMock);
    assertThat(listener.tagAndNamingAdapter).isSameAs(tagAdapterMock);
}
 
Example #14
Source File: MockAsyncContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void complete() {
	MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(this.request, MockHttpServletRequest.class);
	if (mockRequest != null) {
		mockRequest.setAsyncStarted(false);
	}
	for (AsyncListener listener : this.listeners) {
		try {
			listener.onComplete(new AsyncEvent(this, this.request, this.response));
		}
		catch (IOException ex) {
			throw new IllegalStateException("AsyncListener failure", ex);
		}
	}
}
 
Example #15
Source File: ServletRuntimeTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true   |   true    |   true",
    "true   |   false   |   false",
    "false  |   true    |   false",
    "false  |   false   |   false"
}, splitBy = "\\|")
@Test
public void determineServletRuntime_returns_ServletRuntime_based_on_arguments(
    boolean classHasServlet3Method, boolean useAsyncListenerClassThatExists, boolean expectServlet3Runtime
) {
    // given
    Class<?> servletRequestClass = (classHasServlet3Method)
                                   ? GoodFakeServletRequest.class
                                   : BadFakeServletRequest.class;

    String asyncListenerClassname = (useAsyncListenerClassThatExists)
                                    ? AsyncListener.class.getName()
                                    : "does.not.exist.AsyncListener" + UUID.randomUUID().toString();

    // when
    ServletRuntime result = ServletRuntime.determineServletRuntime(servletRequestClass, asyncListenerClassname);

    // then
    if (expectServlet3Runtime) {
        assertThat(result).isInstanceOf(Servlet3Runtime.class);
    }
    else {
        assertThat(result).isInstanceOf(Servlet2Runtime.class);
    }
}
 
Example #16
Source File: MockAsyncContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void complete() {
	MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(this.request, MockHttpServletRequest.class);
	if (mockRequest != null) {
		mockRequest.setAsyncStarted(false);
	}
	for (AsyncListener listener : this.listeners) {
		try {
			listener.onComplete(new AsyncEvent(this, this.request, this.response));
		}
		catch (IOException ex) {
			throw new IllegalStateException("AsyncListener failure", ex);
		}
	}
}
 
Example #17
Source File: MockAsyncContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void complete() {
	MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(request, MockHttpServletRequest.class);
	if (mockRequest != null) {
		mockRequest.setAsyncStarted(false);
	}
	for (AsyncListener listener : this.listeners) {
		try {
			listener.onComplete(new AsyncEvent(this, this.request, this.response));
		}
		catch (IOException e) {
			throw new IllegalStateException("AsyncListener failure", e);
		}
	}
}
 
Example #18
Source File: RequestStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }

    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }

    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        if (validate(target, result, throwable)) {
            // Add async listener. Servlet 3.0
            final AsyncContext asyncContext = (AsyncContext) result;
            final AsyncListener asyncListener = new JettyAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
            asyncContext.addListener(asyncListener);
            if (isDebug) {
                logger.debug("Add async listener {}", asyncListener);
            }
        }
        recorder.recordServiceType(JettyConstants.JETTY_METHOD);
        recorder.recordApi(descriptor);
        recorder.recordException(throwable);
    } catch (Throwable t) {
        logger.warn("Failed to AFTER process. {}", t.getMessage(), t);
    } finally {
        trace.traceBlockEnd();
    }
}
 
Example #19
Source File: MockAsyncContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void complete() {
	MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(request, MockHttpServletRequest.class);
	if (mockRequest != null) {
		mockRequest.setAsyncStarted(false);
	}
	for (AsyncListener listener : this.listeners) {
		try {
			listener.onComplete(new AsyncEvent(this, this.request, this.response));
		}
		catch (IOException e) {
			throw new IllegalStateException("AsyncListener failure", e);
		}
	}
}
 
Example #20
Source File: OpenEJBAsyncContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void internalStartAsync() {
    started = true;
    for (final AsyncListener listener : listeners) {
        try {
            listener.onStartAsync(event);
        } catch (final IOException t) {
            throw new OpenEJBRuntimeException(t);
        }
    }
}
 
Example #21
Source File: PortletAsyncContextImpl.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public void addListener(AsyncListener l) {
   if (!isContextActive) {
      throw new IllegalStateException("Listener can only be added when the asynchronous context is active.");
   }
   pal.addListener(l);
}
 
Example #22
Source File: DefaultAsyncContext.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create the listener.
 *
 * @param <T> the class.
 * @param type the type.
 * @return the listener.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public <T extends AsyncListener> T createListener(Class<T> type) throws ServletException {
    try {
        return type.getConstructor().newInstance();
    } catch (Throwable t) {
        LOGGER.log(WARNING, t, () -> "Unable to create AsyncListener: " + type.getName());
        throw new ServletException("Unable to create listener", t);
    }
}
 
Example #23
Source File: AsyncContextImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private void executeOnListeners(final UnsafeConsumer<AsyncListener> fn, final Runnable afterCopy) {
    final List<AsyncListener> listenersCopy;
    synchronized (listeners) {
        listenersCopy = new ArrayList<>(listeners.size());
        ofNullable(afterCopy).ifPresent(Runnable::run);
    }
    listenersCopy.forEach(listener -> {
        try {
            fn.accept(listener);
        } catch (final Throwable t) {
            log.warn("callback failed for listener of type [" + listener.getClass().getName() + "]", t);
        }
    });
}
 
Example #24
Source File: OpenEJBAsyncContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends AsyncListener> T createListener(final Class<T> clazz)
        throws ServletException {
    try {
        return (T) context.inject(clazz.newInstance());
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}
 
Example #25
Source File: AsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void addListener(AsyncListener listener, ServletRequest servletRequest,
        ServletResponse servletResponse) {
    check();
    AsyncListenerWrapper wrapper = new AsyncListenerWrapper();
    wrapper.setListener(listener);
    listeners.add(wrapper);
}
 
Example #26
Source File: HttpServletRequestImplStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
    if (validate(target, result, throwable)) {
        final AsyncContext asyncContext = (AsyncContext) result;
        final AsyncListener asyncListener = new UndertowAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
        asyncContext.addListener(asyncListener);
        if (isDebug) {
            logger.debug("Add async listener {}", asyncListener);
        }
    }
    recorder.recordServiceType(UndertowServletConstants.UNDERTOW_SERVLET_METHOD);
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);
}
 
Example #27
Source File: AsyncContextImpl.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public void addListener(final AsyncListener listener, final ServletRequest request,
        final ServletResponse response) {
    listeners.add(new AsyncListenerWrapper(listener, request, response));
}
 
Example #28
Source File: JDiscFilterInvokerFilter.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public void addListener(AsyncListener asyncListener) {
    delegate.addListener(asyncListener);
}
 
Example #29
Source File: LoggingAsyncContextImpl.java    From cf-java-logging-support with Apache License 2.0 4 votes vote down vote up
@Override
public void addListener(AsyncListener listener, ServletRequest servletRequest, ServletResponse servletResponse) {
	asyncContext.addListener(listener, servletRequest, servletResponse);
}
 
Example #30
Source File: AsyncContextImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private BoundAsyncListener(final AsyncListener asyncListener, final ServletRequest servletRequest, final ServletResponse servletResponse) {
    this.asyncListener = asyncListener;
    this.servletRequest = servletRequest;
    this.servletResponse = servletResponse;
}