Java Code Examples for org.springframework.web.method.support.ModelAndViewContainer#setRequestHandled()

The following examples show how to use org.springframework.web.method.support.ModelAndViewContainer#setRequestHandled() . 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: 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 2
Source File: HttpHeadersReturnValueHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);

	Assert.state(returnValue instanceof HttpHeaders, "HttpHeaders expected");
	HttpHeaders headers = (HttpHeaders) returnValue;

	if (!headers.isEmpty()) {
		HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
		ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
		outputMessage.getHeaders().putAll(headers);
		outputMessage.getBody();  // flush headers
	}
}
 
Example 3
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 4
Source File: RaptorHandlerMethodProcessor.java    From raptor 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 {
    mavContainer.setRequestHandled(true);
    ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
    ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

    //设置Response header,本应该放在拦截器中实现,但是handler处理完后,response已经关闭了,拦截器无法后置处理response
    RaptorContextInitHandlerInterceptor.applyResponse(outputMessage.getServletResponse());

    writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
 
Example 5
Source File: ModelAndViewMethodReturnValueHandler.java    From lams with GNU General Public License v2.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;
	}

	ModelAndView mav = (ModelAndView) returnValue;
	if (mav.isReference()) {
		String viewName = mav.getViewName();
		mavContainer.setViewName(viewName);
		if (viewName != null && isRedirectViewName(viewName)) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	else {
		View view = mav.getView();
		mavContainer.setView(view);
		if (view instanceof SmartView) {
			if (((SmartView) view).isRedirectView()) {
				mavContainer.setRedirectModelScenario(true);
			}
		}
	}
	mavContainer.setStatus(mav.getStatus());
	mavContainer.addAllAttributes(mav.getModel());
}
 
Example 6
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 7
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 8
Source File: ObserableReturnValueHandler.java    From chassis 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<>();
    ((Observable<?>) returnValue).subscribe( new Observer<Object>() {
        @Override
        public void onCompleted() {
            if (!deferredResult.hasResult()) {
                logger.error( "onComplete before onNext");
                deferredResult.setResult(null);
            }
        }

        @Override
        public void onError(Throwable e) {
            deferredResult.setErrorResult(e);
        }

        @Override
        public void onNext(Object args) {
            deferredResult.setResult(args);
        }
    });
    WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult,mavContainer);
}
 
Example 9
Source File: PollableMethodReturnValueHandler.java    From openemm with GNU Affero General Public License v3.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);
    } else {
        Pollable<?> pollable = (Pollable<?>) returnValue;

        pollingService.submit(pollable);

        WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(pollable.getDeferredResult(), mavContainer);
    }
}
 
Example 10
Source File: RequestResponseBodyMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	mavContainer.setRequestHandled(true);
	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	// Try even with null return value. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
}
 
Example 11
Source File: ObservableReturnValueHandler.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 Observable<?> observable = Observable.class.cast(returnValue);
    WebAsyncUtils.getAsyncManager(webRequest)
            .startDeferredResultProcessing(new ObservableDeferredResult(observable), mavContainer);
}
 
Example 12
Source File: ServletResponseMethodArgumentResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set {@link ModelAndViewContainer#setRequestHandled(boolean)} to
 * {@code false} to indicate that the method signature provides access
 * to the response. If subsequently the underlying method returns
 * {@code null}, the request is considered directly handled.
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

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

	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
	Class<?> paramType = parameter.getParameterType();

	if (ServletResponse.class.isAssignableFrom(paramType)) {
		Object nativeResponse = webRequest.getNativeResponse(paramType);
		if (nativeResponse == null) {
			throw new IllegalStateException(
					"Current response is not of type [" + paramType.getName() + "]: " + response);
		}
		return nativeResponse;
	}
	else if (OutputStream.class.isAssignableFrom(paramType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(paramType)) {
		return response.getWriter();
	}
	else {
		// should not happen
		Method method = parameter.getMethod();
		throw new UnsupportedOperationException("Unknown parameter type: " + paramType + " in method: " + method);
	}
}
 
Example 13
Source File: CallableMethodReturnValueHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
}
 
Example 14
Source File: ServletInvocableHandlerMethod.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invoke the method and handle the return value through one of the
 * configured {@link HandlerMethodReturnValueHandler}s.
 * @param webRequest the current request
 * @param mavContainer the ModelAndViewContainer for this request
 * @param providedArgs "given" arguments matched by type (not resolved)
 */
public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
		Object... providedArgs) throws Exception {

	Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
	setResponseStatus(webRequest);

	if (returnValue == null) {
		if (isRequestNotModified(webRequest) || getResponseStatus() != null || mavContainer.isRequestHandled()) {
			mavContainer.setRequestHandled(true);
			return;
		}
	}
	else if (StringUtils.hasText(getResponseStatusReason())) {
		mavContainer.setRequestHandled(true);
		return;
	}

	mavContainer.setRequestHandled(false);
	try {
		this.returnValueHandlers.handleReturnValue(
				returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
	}
	catch (Exception ex) {
		if (logger.isTraceEnabled()) {
			logger.trace(getReturnValueHandlingErrorMessage("Error handling return value", returnValue), ex);
		}
		throw ex;
	}
}
 
Example 15
Source File: HttpEntityMethodProcessor.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 {

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

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}

	Object body = responseEntity.getBody();
	if (responseEntity instanceof ResponseEntity) {
		outputMessage.setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
		if (HttpMethod.GET == inputMessage.getMethod() && isResourceNotModified(inputMessage, outputMessage)) {
			outputMessage.setStatusCode(HttpStatus.NOT_MODIFIED);
			// Ensure headers are flushed, no body should be written.
			outputMessage.flush();
			// Skip call to converters, as they may update the body.
			return;
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(body, returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 16
Source File: ModelAndViewMethodReturnValueHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

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

	ModelAndView mav = (ModelAndView) returnValue;
	if (mav.isReference()) {
		String viewName = mav.getViewName();
		mavContainer.setViewName(viewName);
		if (viewName != null && isRedirectViewName(viewName)) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	else {
		View view = mav.getView();
		mavContainer.setView(view);
		if (view instanceof SmartView && ((SmartView) view).isRedirectView()) {
			mavContainer.setRedirectModelScenario(true);
		}
	}
	mavContainer.setStatus(mav.getStatus());
	mavContainer.addAllAttributes(mav.getModel());
}
 
Example 17
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 18
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

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

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders outputHeaders = outputMessage.getHeaders();
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		for (Map.Entry<String, List<String>> entry : entityHeaders.entrySet()) {
			if (HttpHeaders.VARY.equals(entry.getKey()) && outputHeaders.containsKey(HttpHeaders.VARY)) {
				List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
				if (!values.isEmpty()) {
					outputHeaders.setVary(values);
				}
			}
			else {
				outputHeaders.put(entry.getKey(), entry.getValue());
			}
		}
	}

	if (responseEntity instanceof ResponseEntity) {
		int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
		outputMessage.getServletResponse().setStatus(returnStatus);
		if (returnStatus == 200) {
			if (isResourceNotModified(inputMessage, outputMessage)) {
				// Ensure headers are flushed, no body should be written.
				outputMessage.flush();
				// Skip call to converters, as they may update the body.
				return;
			}
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 19
Source File: ResponseBodyEmitterReturnValueHandler.java    From spring4-understanding with Apache License 2.0 4 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(ResponseBodyEmitter.class, returnValue);
	ResponseBodyEmitter emitter = (ResponseBodyEmitter) returnValue;
	emitter.extendResponse(outputMessage);

	// Commit the response and wrap to ignore further header changes
	outputMessage.getBody();
	outputMessage.flush();
	outputMessage = new StreamingServletServerHttpResponse(outputMessage);

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

	HttpMessageConvertingHandler handler = new HttpMessageConvertingHandler(outputMessage, deferredResult);
	emitter.initialize(handler);
}
 
Example 20
Source File: ResponseBodyEmitterReturnValueHandler.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

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

	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
	Assert.state(response != null, "No HttpServletResponse");
	ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);

	if (returnValue instanceof ResponseEntity) {
		ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue;
		response.setStatus(responseEntity.getStatusCodeValue());
		outputMessage.getHeaders().putAll(responseEntity.getHeaders());
		returnValue = responseEntity.getBody();
		returnType = returnType.nested();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			outputMessage.flush();
			return;
		}
	}

	ServletRequest request = webRequest.getNativeRequest(ServletRequest.class);
	Assert.state(request != null, "No ServletRequest");

	ResponseBodyEmitter emitter;
	if (returnValue instanceof ResponseBodyEmitter) {
		emitter = (ResponseBodyEmitter) returnValue;
	}
	else {
		emitter = this.reactiveHandler.handleValue(returnValue, returnType, mavContainer, webRequest);
		if (emitter == null) {
			// Not streaming: write headers without committing response..
			outputMessage.getHeaders().forEach((headerName, headerValues) -> {
				for (String headerValue : headerValues) {
					response.addHeader(headerName, headerValue);
				}
			});
			return;
		}
	}
	emitter.extendResponse(outputMessage);

	// At this point we know we're streaming..
	ShallowEtagHeaderFilter.disableContentCaching(request);

	// Commit the response and wrap to ignore further header changes
	outputMessage.getBody();
	outputMessage.flush();
	outputMessage = new StreamingServletServerHttpResponse(outputMessage);

	DeferredResult<?> deferredResult = new DeferredResult<>(emitter.getTimeout());
	WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);

	HttpMessageConvertingHandler handler = new HttpMessageConvertingHandler(outputMessage, deferredResult);
	emitter.initialize(handler);
}