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

The following examples show how to use org.springframework.http.server.ServerHttpResponse#flush() . 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: AbstractHttpSockJsSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void writeFrameInternal(SockJsFrame frame) throws IOException {
	if (isActive()) {
		SockJsFrameFormat frameFormat = this.frameFormat;
		ServerHttpResponse response = this.response;
		if (frameFormat != null && response != null) {
			String formattedFrame = frameFormat.format(frame);
			if (logger.isTraceEnabled()) {
				logger.trace("Writing to HTTP response: " + formattedFrame);
			}
			response.getBody().write(formattedFrame.getBytes(SockJsFrame.CHARSET));
			response.flush();
		}
	}
}
 
Example 2
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 3
Source File: StreamingSockJsSession.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		boolean initialRequest) throws IOException {

	byte[] prelude = getPrelude(request);
	Assert.notNull(prelude);
	response.getBody().write(prelude);
	response.flush();

	if (initialRequest) {
		writeFrame(SockJsFrame.openFrame());
	}
	flushCache();
}
 
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: StreamingSockJsSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		boolean initialRequest) throws IOException {

	byte[] prelude = getPrelude(request);
	response.getBody().write(prelude);
	response.flush();

	if (initialRequest) {
		writeFrame(SockJsFrame.openFrame());
	}
	flushCache();
}
 
Example 6
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 7
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 8
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 9
Source File: StreamingSockJsSession.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		boolean initialRequest) throws IOException {

	byte[] prelude = getPrelude(request);
	response.getBody().write(prelude);
	response.flush();

	if (initialRequest) {
		writeFrame(SockJsFrame.openFrame());
	}
	flushCache();
}
 
Example 10
Source File: AbstractHttpSockJsSession.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void writeFrameInternal(SockJsFrame frame) throws IOException {
	if (isActive()) {
		SockJsFrameFormat frameFormat = this.frameFormat;
		ServerHttpResponse response = this.response;
		if (frameFormat != null && response != null) {
			String formattedFrame = frameFormat.format(frame);
			if (logger.isTraceEnabled()) {
				logger.trace("Writing to HTTP response: " + formattedFrame);
			}
			response.getBody().write(formattedFrame.getBytes(SockJsFrame.CHARSET));
			response.flush();
		}
	}
}
 
Example 11
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 12
Source File: DefaultCorsProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Handle the given request.
 */
protected boolean handleInternal(ServerHttpRequest request, ServerHttpResponse response,
		CorsConfiguration config, boolean preFlightRequest) throws IOException {

	String requestOrigin = request.getHeaders().getOrigin();
	String allowOrigin = checkOrigin(config, requestOrigin);
	HttpHeaders responseHeaders = response.getHeaders();

	if (allowOrigin == null) {
		logger.debug("Reject: '" + requestOrigin + "' origin is not allowed");
		rejectRequest(response);
		return false;
	}

	HttpMethod requestMethod = getMethodToUse(request, preFlightRequest);
	List<HttpMethod> allowMethods = checkMethods(config, requestMethod);
	if (allowMethods == null) {
		logger.debug("Reject: HTTP '" + requestMethod + "' is not allowed");
		rejectRequest(response);
		return false;
	}

	List<String> requestHeaders = getHeadersToUse(request, preFlightRequest);
	List<String> allowHeaders = checkHeaders(config, requestHeaders);
	if (preFlightRequest && allowHeaders == null) {
		logger.debug("Reject: headers '" + requestHeaders + "' are not allowed");
		rejectRequest(response);
		return false;
	}

	responseHeaders.setAccessControlAllowOrigin(allowOrigin);

	if (preFlightRequest) {
		responseHeaders.setAccessControlAllowMethods(allowMethods);
	}

	if (preFlightRequest && !allowHeaders.isEmpty()) {
		responseHeaders.setAccessControlAllowHeaders(allowHeaders);
	}

	if (!CollectionUtils.isEmpty(config.getExposedHeaders())) {
		responseHeaders.setAccessControlExposeHeaders(config.getExposedHeaders());
	}

	if (Boolean.TRUE.equals(config.getAllowCredentials())) {
		responseHeaders.setAccessControlAllowCredentials(true);
	}

	if (preFlightRequest && config.getMaxAge() != null) {
		responseHeaders.setAccessControlMaxAge(config.getMaxAge());
	}

	response.flush();
	return true;
}
 
Example 13
Source File: DefaultCorsProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Invoked when one of the CORS checks failed.
 * The default implementation sets the response status to 403 and writes
 * "Invalid CORS request" to the response.
 */
protected void rejectRequest(ServerHttpResponse response) throws IOException {
	response.setStatusCode(HttpStatus.FORBIDDEN);
	response.getBody().write("Invalid CORS request".getBytes(StandardCharsets.UTF_8));
	response.flush();
}
 
Example 14
Source File: DefaultCorsProcessor.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Handle the given request.
 */
protected boolean handleInternal(ServerHttpRequest request, ServerHttpResponse response,
		CorsConfiguration config, boolean preFlightRequest) throws IOException {

	String requestOrigin = request.getHeaders().getOrigin();
	String allowOrigin = checkOrigin(config, requestOrigin);
	HttpHeaders responseHeaders = response.getHeaders();

	responseHeaders.addAll(HttpHeaders.VARY, Arrays.asList(HttpHeaders.ORIGIN,
			HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));

	if (allowOrigin == null) {
		logger.debug("Reject: '" + requestOrigin + "' origin is not allowed");
		rejectRequest(response);
		return false;
	}

	HttpMethod requestMethod = getMethodToUse(request, preFlightRequest);
	List<HttpMethod> allowMethods = checkMethods(config, requestMethod);
	if (allowMethods == null) {
		logger.debug("Reject: HTTP '" + requestMethod + "' is not allowed");
		rejectRequest(response);
		return false;
	}

	List<String> requestHeaders = getHeadersToUse(request, preFlightRequest);
	List<String> allowHeaders = checkHeaders(config, requestHeaders);
	if (preFlightRequest && allowHeaders == null) {
		logger.debug("Reject: headers '" + requestHeaders + "' are not allowed");
		rejectRequest(response);
		return false;
	}

	responseHeaders.setAccessControlAllowOrigin(allowOrigin);

	if (preFlightRequest) {
		responseHeaders.setAccessControlAllowMethods(allowMethods);
	}

	if (preFlightRequest && !allowHeaders.isEmpty()) {
		responseHeaders.setAccessControlAllowHeaders(allowHeaders);
	}

	if (!CollectionUtils.isEmpty(config.getExposedHeaders())) {
		responseHeaders.setAccessControlExposeHeaders(config.getExposedHeaders());
	}

	if (Boolean.TRUE.equals(config.getAllowCredentials())) {
		responseHeaders.setAccessControlAllowCredentials(true);
	}

	if (preFlightRequest && config.getMaxAge() != null) {
		responseHeaders.setAccessControlMaxAge(config.getMaxAge());
	}

	response.flush();
	return true;
}
 
Example 15
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 16
Source File: DefaultCorsProcessor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Handle the given request.
 */
protected boolean handleInternal(ServerHttpRequest request, ServerHttpResponse response,
		CorsConfiguration config, boolean preFlightRequest) throws IOException {

	String requestOrigin = request.getHeaders().getOrigin();
	String allowOrigin = checkOrigin(config, requestOrigin);

	HttpMethod requestMethod = getMethodToUse(request, preFlightRequest);
	List<HttpMethod> allowMethods = checkMethods(config, requestMethod);

	List<String> requestHeaders = getHeadersToUse(request, preFlightRequest);
	List<String> allowHeaders = checkHeaders(config, requestHeaders);

	if (allowOrigin == null || allowMethods == null || (preFlightRequest && allowHeaders == null)) {
		rejectRequest(response);
		return false;
	}

	HttpHeaders responseHeaders = response.getHeaders();
	responseHeaders.setAccessControlAllowOrigin(allowOrigin);
	responseHeaders.add(HttpHeaders.VARY, HttpHeaders.ORIGIN);

	if (preFlightRequest) {
		responseHeaders.setAccessControlAllowMethods(allowMethods);
	}

	if (preFlightRequest && !allowHeaders.isEmpty()) {
		responseHeaders.setAccessControlAllowHeaders(allowHeaders);
	}

	if (!CollectionUtils.isEmpty(config.getExposedHeaders())) {
		responseHeaders.setAccessControlExposeHeaders(config.getExposedHeaders());
	}

	if (Boolean.TRUE.equals(config.getAllowCredentials())) {
		responseHeaders.setAccessControlAllowCredentials(true);
	}

	if (preFlightRequest && config.getMaxAge() != null) {
		responseHeaders.setAccessControlMaxAge(config.getMaxAge());
	}

	response.flush();
	return true;
}
 
Example 17
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 18
Source File: DefaultCorsProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Handle the given request.
 */
protected boolean handleInternal(ServerHttpRequest request, ServerHttpResponse response,
		CorsConfiguration config, boolean preFlightRequest) throws IOException {

	String requestOrigin = request.getHeaders().getOrigin();
	String allowOrigin = checkOrigin(config, requestOrigin);

	HttpMethod requestMethod = getMethodToUse(request, preFlightRequest);
	List<HttpMethod> allowMethods = checkMethods(config, requestMethod);

	List<String> requestHeaders = getHeadersToUse(request, preFlightRequest);
	List<String> allowHeaders = checkHeaders(config, requestHeaders);

	if (allowOrigin == null || allowMethods == null || (preFlightRequest && allowHeaders == null)) {
		rejectRequest(response);
		return false;
	}

	HttpHeaders responseHeaders = response.getHeaders();
	responseHeaders.setAccessControlAllowOrigin(allowOrigin);
	responseHeaders.add(HttpHeaders.VARY, HttpHeaders.ORIGIN);

	if (preFlightRequest) {
		responseHeaders.setAccessControlAllowMethods(allowMethods);
	}

	if (preFlightRequest && !allowHeaders.isEmpty()) {
		responseHeaders.setAccessControlAllowHeaders(allowHeaders);
	}

	if (!CollectionUtils.isEmpty(config.getExposedHeaders())) {
		responseHeaders.setAccessControlExposeHeaders(config.getExposedHeaders());
	}

	if (Boolean.TRUE.equals(config.getAllowCredentials())) {
		responseHeaders.setAccessControlAllowCredentials(true);
	}

	if (preFlightRequest && config.getMaxAge() != null) {
		responseHeaders.setAccessControlMaxAge(config.getMaxAge());
	}

	response.flush();
	return true;
}
 
Example 19
Source File: ResponseBodyEmitterReturnValueHandler.java    From spring-analysis-note 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);

	// Wrap the response to ignore further header changes
	// Headers will be flushed at the first write
	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);
}