Java Code Examples for org.springframework.http.server.ServerHttpResponse#getBody()

The following examples show how to use org.springframework.http.server.ServerHttpResponse#getBody() . 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: StreamingResponseBodyReturnValueHandler.java    From spring-analysis-note with MIT License 5 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();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			outputMessage.flush();
			return;
		}
	}

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

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

	Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
}
 
Example 2
Source File: InstancesProxyController.java    From Moss with Apache License 2.0 5 votes vote down vote up
/**
 * 所以端点的请求代理入口:/instances/{instanceId}/actuator/**
 * @author xujin
 * @param instanceId
 * @param servletRequest
 * @param servletResponse
 * @return
 * @throws IOException
 */
@ResponseBody
@RequestMapping(path = REQUEST_MAPPING_PATH, method = {RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS})
public Mono<Void> endpointProxy(@PathVariable("instanceId") String instanceId,
                                HttpServletRequest servletRequest,
                                HttpServletResponse servletResponse) throws IOException {
    ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);

    String pathWithinApplication = UriComponentsBuilder.fromPath(servletRequest.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)
                                                                               .toString()).toUriString();
    String endpointLocalPath = getEndpointLocalPath(pathWithinApplication);

    URI uri = UriComponentsBuilder.fromPath(endpointLocalPath)
                                  .query(request.getURI().getRawQuery())
                                  .build(true)
                                  .toUri();

    //We need to explicitly block until the headers are recieved and write them before the async dispatch.
    //otherwise the FrameworkServlet will add wrong Allow header for OPTIONS request
    ClientResponse clientResponse = super.forward(instanceId,
        uri,
        request.getMethod(),
        request.getHeaders(),
        () -> BodyInserters.fromDataBuffers(DataBufferUtils.readInputStream(request::getBody,
            this.bufferFactory,
            4096
        ))
    ).block();

    ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);
    response.setStatusCode(clientResponse.statusCode());
    response.getHeaders().addAll(filterHeaders(clientResponse.headers().asHttpHeaders()));
    OutputStream responseBody = response.getBody();
    response.flush();

    return clientResponse.body(BodyExtractors.toDataBuffers())
                         .window(1)
                         .concatMap(body -> writeAndFlush(body, responseBody))
                         .then();
}
 
Example 3
Source File: StreamingResponseBodyReturnValueHandler.java    From java-technology-stack with MIT License 5 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();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			outputMessage.flush();
			return;
		}
	}

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

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

	Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
}
 
Example 4
Source File: StreamingResponseBodyReturnValueHandler.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;
	}

	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
	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();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			outputMessage.flush();
			return;
		}
	}

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

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

	Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(callable, mavContainer);
}
 
Example 5
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 6
Source File: InstancesProxyController.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(path = INSTANCE_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST,
		RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Mono<Void> endpointProxy(@PathVariable("instanceId") String instanceId, HttpServletRequest servletRequest,
		HttpServletResponse servletResponse) throws IOException {
	ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
	String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + INSTANCE_MAPPED_PATH,
			servletRequest);
	URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true)
			.toUri();

	// We need to explicitly block until the headers are recieved and write them
	// before the async dispatch.
	// otherwise the FrameworkServlet will add wrong Allow header for OPTIONS request
	Flux<DataBuffer> requestBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096);
	ClientResponse clientResponse = this.instanceWebProxy
			.forward(this.registry.getInstance(InstanceId.of(instanceId)), uri, request.getMethod(),
					this.httpHeadersFilter.filterHeaders(request.getHeaders()),
					BodyInserters.fromDataBuffers(requestBody))
			.block();

	ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);
	response.setStatusCode(clientResponse.statusCode());
	response.getHeaders().addAll(this.httpHeadersFilter.filterHeaders(clientResponse.headers().asHttpHeaders()));
	OutputStream responseBody = response.getBody();
	response.flush();

	return clientResponse.body(BodyExtractors.toDataBuffers()).window(1)
			.concatMap((body) -> writeAndFlush(body, responseBody)).then();
}
 
Example 7
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);
}
 
Example 8
Source File: ResponseBodyEmitterReturnValueHandler.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 {

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

	HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
	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();
		if (returnValue == null) {
			mavContainer.setRequestHandled(true);
			outputMessage.flush();
			return;
		}
	}

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

	ResponseBodyEmitterAdapter adapter = getAdapterFor(returnValue.getClass());
	if (adapter == null) {
		throw new IllegalStateException(
				"Could not find ResponseBodyEmitterAdapter for return value type: " + returnValue.getClass());
	}
	ResponseBodyEmitter emitter = adapter.adaptToEmitter(returnValue, outputMessage);
	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 9
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);
}