use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.
the class ResponseBodyEmitterReturnValueHandlerTests method responseBodyFluxWithError.
// gh-21972
@Test
public void responseBodyFluxWithError() throws Exception {
this.request.addHeader("Accept", "text/event-stream");
MethodParameter type = on(TestController.class).resolveReturnType(Flux.class, String.class);
Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();
this.handler.handleReturnValue(sink.asFlux(), type, this.mavContainer, this.webRequest);
assertThat(this.request.isAsyncStarted()).isTrue();
IllegalStateException ex = new IllegalStateException("wah wah");
sink.tryEmitError(ex);
sink.tryEmitComplete();
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.webRequest);
assertThat(asyncManager.getConcurrentResult()).isSameAs(ex);
assertThat(this.response.getContentType()).isNull();
}
use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.
the class OpenEntityManagerInViewInterceptor method preHandle.
@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);
}
}
}
use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.
the class OpenSessionInViewInterceptor method preHandle.
/**
* Open a new Hibernate {@code Session} according and bind it to the thread via the
* {@link TransactionSynchronizationManager}.
*/
@Override
public void preHandle(WebRequest request) throws DataAccessException {
String key = getParticipateAttributeName();
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) {
return;
}
if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
// Do not modify the Session: 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 Hibernate Session in OpenSessionInViewInterceptor");
Session session = openSession();
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);
AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder);
asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor);
asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor);
}
}
use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.
the class OpenEntityManagerInViewFilter method doFilterInternal.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
EntityManagerFactory emf = lookupEntityManagerFactory(request);
boolean participate = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
String key = getAlreadyFilteredAttributeName();
if (TransactionSynchronizationManager.hasResource(emf)) {
// Do not modify the EntityManager: just set the participate flag.
participate = true;
} else {
boolean isFirstRequest = !isAsyncDispatch(request);
if (isFirstRequest || !applyEntityManagerBindingInterceptor(asyncManager, key)) {
logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewFilter");
try {
EntityManager em = createEntityManager(emf);
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);
}
}
}
try {
filterChain.doFilter(request, response);
} finally {
if (!participate) {
EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(emf);
if (!isAsyncStarted(request)) {
logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewFilter");
EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
}
}
}
}
use of org.springframework.web.context.request.async.WebAsyncManager in project spring-framework by spring-projects.
the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewFilterAsyncScenario.
@Test
public void testOpenEntityManagerInViewFilterAsyncScenario() throws Exception {
given(manager.isOpen()).willReturn(true);
final EntityManagerFactory factory2 = mock(EntityManagerFactory.class);
final EntityManager manager2 = mock(EntityManager.class);
given(factory2.createEntityManager()).willReturn(manager2);
given(manager2.isOpen()).willReturn(true);
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", factory);
wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
filterConfig2.addInitParameter("entityManagerFactoryBeanName", "myEntityManagerFactory");
final OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter();
filter.init(filterConfig);
final OpenEntityManagerInViewFilter filter2 = new OpenEntityManagerInViewFilter();
filter2.init(filterConfig2);
final AtomicInteger count = new AtomicInteger();
final FilterChain filterChain = (servletRequest, servletResponse) -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
servletRequest.setAttribute("invoked", Boolean.TRUE);
count.incrementAndGet();
};
final AtomicInteger count2 = new AtomicInteger();
final FilterChain filterChain2 = (servletRequest, servletResponse) -> {
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue();
filter.doFilter(servletRequest, servletResponse, filterChain);
count2.incrementAndGet();
};
FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
given(asyncWebRequest.isAsyncStarted()).willReturn(true);
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request);
asyncManager.setTaskExecutor(this.taskExecutor);
asyncManager.setAsyncWebRequest(asyncWebRequest);
asyncManager.startCallableProcessing((Callable<String>) () -> "anything");
this.taskExecutor.await();
assertThat(asyncManager.getConcurrentResult()).as("Concurrent result ").isEqualTo("anything");
assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
filter2.doFilter(this.request, this.response, filterChain3);
assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
assertThat(count.get()).isEqualTo(1);
assertThat(count2.get()).isEqualTo(1);
assertThat(request.getAttribute("invoked")).isNotNull();
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
verify(asyncWebRequest).startAsync();
// Async dispatch after concurrent handling produces result ...
reset(asyncWebRequest);
given(asyncWebRequest.isAsyncStarted()).willReturn(false);
assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
filter.doFilter(this.request, this.response, filterChain3);
assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
assertThat(count.get()).isEqualTo(2);
assertThat(count2.get()).isEqualTo(2);
verify(this.manager).close();
verify(manager2).close();
wac.close();
}
Aggregations