Refine search
@Override public void preHandle(WebRequest request) throws DataAccessException { String key = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) { return; } EntityManagerFactory emf = obtainEntityManagerFactory(); if (TransactionSynchronizationManager.hasResource(emf)) { // Do not modify the EntityManager: just mark the request accordingly. Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor"); try { EntityManager em = createEntityManager(); EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(emf, emHolder); AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder); asyncManager.registerCallableInterceptor(key, interceptor); asyncManager.registerDeferredResultInterceptor(key, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); } } }
@Override public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } DeferredResult<?> result; if (returnValue instanceof DeferredResult) { result = (DeferredResult<?>) returnValue; } else if (returnValue instanceof ListenableFuture) { result = adaptListenableFuture((ListenableFuture<?>) returnValue); } else if (returnValue instanceof CompletionStage) { result = adaptCompletionStage((CompletionStage<?>) returnValue); } else { // Should not happen... throw new IllegalStateException("Unexpected return value type: " + returnValue); } WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(result, mavContainer); }
mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect); AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response); asyncWebRequest.setTimeout(this.asyncRequestTimeout); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.setTaskExecutor(this.taskExecutor); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.registerCallableInterceptors(this.callableInterceptors); asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors); if (asyncManager.hasConcurrentResult()) { Object result = asyncManager.getConcurrentResult(); mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0]; asyncManager.clearConcurrentResult(); LogFormatUtils.traceDebug(logger, traceOn -> { String formatted = LogFormatUtils.formatValue(result, !traceOn); if (asyncManager.isConcurrentHandlingStarted()) { return null;
private void registerAsyncResultInterceptors(final HttpServletRequest request) { WebAsyncUtils.getAsyncManager(request).registerCallableInterceptor(KEY, new CallableProcessingInterceptor() { @Override public <T> void postProcess(NativeWebRequest r, Callable<T> task, Object value) { // We got the result, must also wait for the dispatch getMvcResult(request).setAsyncResult(value); } }); WebAsyncUtils.getAsyncManager(request).registerDeferredResultInterceptor(KEY, new DeferredResultProcessingInterceptor() { @Override public <T> void postProcess(NativeWebRequest r, DeferredResult<T> result, Object value) { getMvcResult(request).setAsyncResult(value); } }); }
@Test public void startCallableProcessingPreProcessException() throws Exception { Callable<Object> task = new StubCallable(21); Exception exception = new Exception(); CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); willThrow(exception).given(interceptor).preProcess(this.asyncWebRequest, task); setupDefaultAsyncScenario(); this.asyncManager.registerCallableInterceptor("interceptor", interceptor); this.asyncManager.startCallableProcessing(task); assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(exception, this.asyncManager.getConcurrentResult()); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); }
/** * Whether request processing is in asynchronous mode meaning that the * response will not be committed after the current thread is exited. * @param request the current request * @since 3.2 * @see WebAsyncManager#isConcurrentHandlingStarted() */ protected boolean isAsyncStarted(HttpServletRequest request) { return WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted(); }
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { @Override public String call() throws Exception {
@Test public void startDeferredResultProcessingAfterTimeoutException() throws Exception { DeferredResult<Integer> deferredResult = new DeferredResult<>(); final Exception exception = new Exception(); DeferredResultProcessingInterceptor interceptor = new DeferredResultProcessingInterceptor() { @Override public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> result) throws Exception { throw exception; } }; this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); this.asyncManager.startDeferredResultProcessing(deferredResult); AsyncEvent event = null; this.asyncWebRequest.onTimeout(event); assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(exception, this.asyncManager.getConcurrentResult()); assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); }
@SuppressWarnings("unchecked") @Test public void responseBodyEmitterWithErrorValue() throws Exception { AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); WebAsyncUtils.getAsyncManager(this.request).setAsyncWebRequest(asyncWebRequest); ResponseBodyEmitter emitter = new ResponseBodyEmitter(19000L); emitter.onError(mock(Consumer.class)); emitter.onCompletion(mock(Runnable.class)); MethodParameter type = on(TestController.class).resolveReturnType(ResponseBodyEmitter.class); this.handler.handleReturnValue(emitter, type, this.mavContainer, this.webRequest); verify(asyncWebRequest).addErrorHandler(any(Consumer.class)); verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); verify(asyncWebRequest).startAsync(); }
@Before public void setup() { this.servletRequest = new MockHttpServletRequest("GET", "/test"); this.servletRequest.setAsyncSupported(true); this.servletResponse = new MockHttpServletResponse(); this.asyncWebRequest = new StandardServletAsyncWebRequest(servletRequest, servletResponse); AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class); this.asyncManager = WebAsyncUtils.getAsyncManager(servletRequest); this.asyncManager.setTaskExecutor(executor); this.asyncManager.setAsyncWebRequest(this.asyncWebRequest); }
private void testDeferredResultSubscriber(Object returnValue, Class<?> asyncType, ResolvableType elementType, Runnable produceTask, Object expected) throws Exception { ResponseBodyEmitter emitter = handleValue(returnValue, asyncType, elementType); assertNull(emitter); assertTrue(this.servletRequest.isAsyncStarted()); assertFalse(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()); produceTask.run(); assertTrue(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()); assertEquals(expected, WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult()); resetRequest(); }
@Test public void startDeferredResultProcessingTimeoutAndResumeWithDefaultResult() throws Exception { DeferredResult<Integer> deferredResult = new DeferredResult<>(null, 23); this.asyncManager.startDeferredResultProcessing(deferredResult); AsyncEvent event = null; this.asyncWebRequest.onTimeout(event); assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(23, this.asyncManager.getConcurrentResult()); assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); }
/** * The dispatcher type {@code javax.servlet.DispatcherType.ASYNC} introduced * in Servlet 3.0 means a filter can be invoked in more than one thread over * the course of a single request. This method returns {@code true} if the * filter is currently executing within an asynchronous dispatch. * @param request the current request * @since 3.2 * @see WebAsyncManager#hasConcurrentResult() */ protected boolean isAsyncDispatch(HttpServletRequest request) { return WebAsyncUtils.getAsyncManager(request).hasConcurrentResult(); }
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor()); if (asyncManager.isConcurrentHandlingStarted()) { logger.debug("Leaving response open for concurrent processing");
@Override public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } Callable<?> callable = (Callable<?>) returnValue; WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer); }
@Test public void startAsyncProcessingWithoutAsyncWebRequest() throws Exception { WebAsyncManager manager = WebAsyncUtils.getAsyncManager(new MockHttpServletRequest()); try { manager.startCallableProcessing(new StubCallable(1)); fail("Expected exception"); } catch (IllegalStateException ex) { assertEquals("AsyncWebRequest must not be null", ex.getMessage()); } try { manager.startDeferredResultProcessing(new DeferredResult<String>()); fail("Expected exception"); } catch (IllegalStateException ex) { assertEquals("AsyncWebRequest must not be null", ex.getMessage()); } }
@Test public void startDeferredResultProcessingPreProcessException() throws Exception { DeferredResult<Integer> deferredResult = new DeferredResult<>(); Exception exception = new Exception(); DeferredResultProcessingInterceptor interceptor = mock(DeferredResultProcessingInterceptor.class); willThrow(exception).given(interceptor).preProcess(this.asyncWebRequest, deferredResult); setupDefaultAsyncScenario(); this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); this.asyncManager.startDeferredResultProcessing(deferredResult); deferredResult.setResult(25); assertEquals(exception, this.asyncManager.getConcurrentResult()); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); }
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
@Test public void startCallableProcessingTimeoutAndResumeThroughCallback() throws Exception { StubCallable callable = new StubCallable(); WebAsyncTask<Object> webAsyncTask = new WebAsyncTask<>(callable); webAsyncTask.onTimeout(new Callable<Object>() { @Override public Object call() throws Exception { return 7; } }); this.asyncManager.startCallableProcessing(webAsyncTask); this.asyncWebRequest.onTimeout(ASYNC_EVENT); assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(7, this.asyncManager.getConcurrentResult()); assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); }
@SuppressWarnings("unchecked") @Test public void startCallableProcessingBeforeConcurrentHandlingException() throws Exception { Callable<Object> task = new StubCallable(21); Exception exception = new Exception(); CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); willThrow(exception).given(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); this.asyncManager.registerCallableInterceptor("interceptor", interceptor); try { this.asyncManager.startCallableProcessing(task); fail("Expected Exception"); } catch (Exception ex) { assertEquals(exception, ex); } assertFalse(this.asyncManager.hasConcurrentResult()); verify(this.asyncWebRequest).addTimeoutHandler(notNull()); verify(this.asyncWebRequest).addErrorHandler(notNull()); verify(this.asyncWebRequest).addCompletionHandler(notNull()); }