org.springframework.web.context.request.async.WebAsyncUtils Java Examples

The following examples show how to use org.springframework.web.context.request.async.WebAsyncUtils. 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: ResponseBodyEmitterReturnValueHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void responseBodyEmitterWithTimeoutValue() throws Exception {

	AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
	WebAsyncUtils.getAsyncManager(this.request).setAsyncWebRequest(asyncWebRequest);

	ResponseBodyEmitter emitter = new ResponseBodyEmitter(19000L);
	emitter.onTimeout(mock(Runnable.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).setTimeout(19000L);
	verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
	verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
	verify(asyncWebRequest).startAsync();
}
 
Example #2
Source File: AsyncResponseEntityReturnHandler.java    From microservices-sample-project with Apache License 2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final AsyncResponseEntity<?> asyncResponseEntity = AsyncResponseEntity.class.cast(returnValue);
    
    Observable<?> observable = asyncResponseEntity.getObservable();
    Single<?> single = asyncResponseEntity.getSingle();
    MultiValueMap<String, String> headers =  asyncResponseEntity.getHeaders();
    HttpStatus status = asyncResponseEntity.getStatus();
    
    if(observable != null)
    	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new ObservableDeferredResult<>(observable, headers, status), mavContainer);
    else if(single != null)
    	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new SingleDeferredResult<>(single, headers, status), mavContainer);
    
}
 
Example #3
Source File: ListenableFutureReturnValueHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	ListenableFuture<?> future = (ListenableFuture<?>) returnValue;
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			deferredResult.setResult(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			deferredResult.setErrorResult(ex);
		}
	});
}
 
Example #4
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void responseBodyEmitterWithTimeoutValue() throws Exception {

	AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
	WebAsyncUtils.getAsyncManager(this.request).setAsyncWebRequest(asyncWebRequest);

	ResponseBodyEmitter emitter = new ResponseBodyEmitter(19000L);
	emitter.onTimeout(mock(Runnable.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).setTimeout(19000L);
	verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
	verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
	verify(asyncWebRequest).startAsync();
}
 
Example #5
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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();
}
 
Example #6
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // gh-21972
public void responseBodyFluxWithError() throws Exception {

	this.request.addHeader("Accept", "text/event-stream");

	MethodParameter type = on(TestController.class).resolveReturnType(Flux.class, String.class);
	EmitterProcessor<String> processor = EmitterProcessor.create();
	this.handler.handleReturnValue(processor, type, this.mavContainer, this.webRequest);

	assertTrue(this.request.isAsyncStarted());

	IllegalStateException ex = new IllegalStateException("wah wah");
	processor.onError(ex);
	processor.onComplete();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.webRequest);
	assertSame(ex, asyncManager.getConcurrentResult());
	assertNull(this.response.getContentType());
}
 
Example #7
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void timeoutValueAndCallback() throws Exception {

	AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class);
	WebAsyncUtils.getAsyncManager(this.request).setAsyncWebRequest(asyncWebRequest);

	ResponseBodyEmitter emitter = new ResponseBodyEmitter(19000L);
	emitter.onTimeout(mock(Runnable.class));
	emitter.onCompletion(mock(Runnable.class));

	MethodParameter returnType = returnType(TestController.class, "handle");
	this.handler.handleReturnValue(emitter, returnType, this.mavContainer, this.webRequest);

	verify(asyncWebRequest).setTimeout(19000L);
	verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class));
	verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class));
	verify(asyncWebRequest).startAsync();
}
 
Example #8
Source File: ListenableFutureReturnValueHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	ListenableFuture<?> future = (ListenableFuture<?>) returnValue;
	future.addCallback(new ListenableFutureCallback<Object>() {
		@Override
		public void onSuccess(Object result) {
			deferredResult.setResult(result);
		}
		@Override
		public void onFailure(Throwable ex) {
			deferredResult.setErrorResult(ex);
		}
	});
}
 
Example #9
Source File: DeferredResultMethodReturnValueHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	DeferredResultAdapter adapter = getAdapterFor(returnValue.getClass());
	if (adapter == null) {
		throw new IllegalStateException(
				"Could not find DeferredResultAdapter for return value type: " + returnValue.getClass());
	}
	DeferredResult<?> result = adapter.adaptToDeferredResult(returnValue);
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(result, mavContainer);
}
 
Example #10
Source File: AsyncResponseEntityReturnHandler.java    From searchbox-core with Apache License 2.0 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final AsyncResponseEntity<?> asyncResponseEntity = AsyncResponseEntity.class.cast(returnValue);
    
    Observable<?> observable = asyncResponseEntity.getObservable();
    Single<?> single = asyncResponseEntity.getSingle();
    MultiValueMap<String, String> headers =  asyncResponseEntity.getHeaders();
    HttpStatus status = asyncResponseEntity.getStatus();
    
    if(observable != null)
    	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new ObservableDeferredResult<>(observable, headers, status), mavContainer);
    else if(single != null)
    	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(new SingleDeferredResult<>(single, headers, status), mavContainer);
    
}
 
Example #11
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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();
}
 
Example #12
Source File: OpenEntityManagerInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, 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(getEntityManagerFactory(), emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example #13
Source File: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according to the settings of this
 * {@code HibernateAccessor} and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if ((isSingleSession() && TransactionSynchronizationManager.hasResource(getSessionFactory())) ||
		SessionFactoryUtils.isDeferredCloseActive(getSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		if (isSingleSession()) {
			// single session mode
			logger.debug("Opening single Hibernate Session in OpenSessionInViewInterceptor");
			Session session = SessionFactoryUtils.getSession(
					getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
			applyFlushMode(session, false);
			SessionHolder sessionHolder = new SessionHolder(session);
			TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

			AsyncRequestInterceptor asyncRequestInterceptor =
					new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
		}
		else {
			// deferred close mode
			SessionFactoryUtils.initDeferredClose(getSessionFactory());
		}
	}
}
 
Example #14
Source File: StreamingResponseBodyReturnValueHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

	this.handler = new StreamingResponseBodyReturnValueHandler();
	this.mavContainer = new ModelAndViewContainer();

	this.request = new MockHttpServletRequest("GET", "/path");
	this.response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(this.request, this.response);

	AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
	WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
	this.request.setAsyncSupported(true);
}
 
Example #15
Source File: StreamingResponseBodyReturnValueHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
	ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);

	if (ResponseEntity.class.isAssignableFrom(returnValue.getClass())) {
		ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue;
		outputMessage.setStatusCode(responseEntity.getStatusCode());
		outputMessage.getHeaders().putAll(responseEntity.getHeaders());

		returnValue = responseEntity.getBody();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			return;
		}
	}

	ServletRequest request = webRequest.getNativeRequest(ServletRequest.class);
	ShallowEtagHeaderFilter.disableContentCaching(request);

	Assert.isInstanceOf(StreamingResponseBody.class, returnValue);
	StreamingResponseBody streamingBody = (StreamingResponseBody) returnValue;

	Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
}
 
Example #16
Source File: OpenEntityManagerInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, 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(getEntityManagerFactory(), emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example #17
Source File: SingleReturnValueHandler.java    From rxjava-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final Single<?> single = Single.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
            .startDeferredResultProcessing(new SingleDeferredResult(single), mavContainer);
}
 
Example #18
Source File: FlowableReturnValueHandler.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }
    final Flowable<?> observable = Flowable.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
                 .startDeferredResultProcessing(new FlowableAdapter<>(observable), mavContainer);
}
 
Example #19
Source File: ObservableReturnValueHandler.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }
    final Observable<?> observable = Observable.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
                 .startDeferredResultProcessing(new ObservableAdapter<>(observable), mavContainer);
}
 
Example #20
Source File: ObservableReturnValueHandler.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }
    final Observable<?> observable = Observable.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
                 .startDeferredResultProcessing(new ObservableAdapter<>(observable), mavContainer);
}
 
Example #21
Source File: ObservableReturnValueHandler.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final Observable<?> observable = Observable.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
                 .startDeferredResultProcessing(new ObservableDeferredResult(observable), mavContainer);
}
 
Example #22
Source File: SingleReturnValueHandler.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final Single<?> single = Single.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
                 .startDeferredResultProcessing(new SingleDeferredResult(single), mavContainer);
}
 
Example #23
Source File: StreamingResponseBodyReturnValueHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	this.handler = new StreamingResponseBodyReturnValueHandler();
	this.mavContainer = new ModelAndViewContainer();

	this.request = new MockHttpServletRequest("GET", "/path");
	this.response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(this.request, this.response);

	AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
	WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
	this.request.setAsyncSupported(true);
}
 
Example #24
Source File: DeferredResultReturnValueHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void testHandle(Object returnValue, Class<?> asyncType,
		Runnable setResultTask, Object expectedValue) throws Exception {

	ModelAndViewContainer mavContainer = new ModelAndViewContainer();
	MethodParameter returnType = on(TestController.class).resolveReturnType(asyncType, String.class);
	this.handler.handleReturnValue(returnValue, returnType, mavContainer, this.webRequest);

	assertTrue(this.request.isAsyncStarted());
	assertFalse(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult());

	setResultTask.run();

	assertTrue(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult());
	assertEquals(expectedValue, WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult());
}
 
Example #25
Source File: CompletionStageReturnValueHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	@SuppressWarnings("unchecked")
	CompletionStage<Object> future = (CompletionStage<Object>) returnValue;
	future.thenAccept(new Consumer<Object>() {
		@Override
		public void accept(Object result) {
			deferredResult.setResult(result);
		}
	});
	future.exceptionally(new Function<Throwable, Object>() {
		@Override
		public Object apply(Throwable ex) {
			deferredResult.setErrorResult(ex);
			return null;
		}
	});
}
 
Example #26
Source File: DeferredResultReturnValueHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	this.handler = new DeferredResultMethodReturnValueHandler();
	this.request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(this.request, response);

	AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, response);
	WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
	this.request.setAsyncSupported(true);
}
 
Example #27
Source File: DeferredResultMethodReturnValueHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	DeferredResult<?> deferredResult = (DeferredResult<?>) returnValue;
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);
}
 
Example #28
Source File: OpenSessionInViewInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #29
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according to the settings of this
 * {@code HibernateAccessor} and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if ((isSingleSession() && TransactionSynchronizationManager.hasResource(getSessionFactory())) ||
			org.springframework.orm.hibernate3.SessionFactoryUtils.isDeferredCloseActive(getSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		if (isSingleSession()) {
			// single session mode
			logger.debug("Opening single Hibernate Session in OpenSessionInViewInterceptor");
			Session session = org.springframework.orm.hibernate3.SessionFactoryUtils.getSession(
					getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
			applyFlushMode(session, false);
			org.springframework.orm.hibernate3.SessionHolder sessionHolder = new org.springframework.orm.hibernate3.SessionHolder(session);
			TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

			AsyncRequestInterceptor asyncRequestInterceptor =
					new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
		}
		else {
			// deferred close mode
			org.springframework.orm.hibernate3.SessionFactoryUtils.initDeferredClose(getSessionFactory());
		}
	}
}
 
Example #30
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {

	List<HttpMessageConverter<?>> converters = Arrays.asList(
			new StringHttpMessageConverter(), new MappingJackson2HttpMessageConverter());

	this.handler = new ResponseBodyEmitterReturnValueHandler(converters);
	this.request = new MockHttpServletRequest();
	this.response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(this.request, this.response);

	AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
	WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
	this.request.setAsyncSupported(true);
}