org.springframework.http.server.ServletServerHttpResponse Java Examples

The following examples show how to use org.springframework.http.server.ServletServerHttpResponse. 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: JsonHandlerMethodReturnValueHandler.java    From sca-best-practice 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 {
    mavContainer.setRequestHandled(true);
    HttpServletResponse httpServletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
    httpServletResponse.setContentType(CONTENT_TYPE);
    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(httpServletResponse);
    Locale locale = (Locale)webRequest.getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
        RequestAttributes.SCOPE_SESSION);
    String message;
    try {
        message = messageSource.getMessage(DEFAULT_SUCCESS_CODE, new Object[0], locale);
    } catch (NoSuchMessageException e) {
        message = DefaultMessagesProperties.getMessage(DEFAULT_SUCCESS_CODE);
    }
    JsonResponse jsonResponse = new JsonResponse(DEFAULT_SUCCESS_CODE, message, returnValue);
    outputMessage.getBody().write(StringUtils.toBytes(JsonUtils.toJson(jsonResponse)));
    outputMessage.getBody().flush();
}
 
Example #2
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void writeStreamJson() throws Exception {

	this.servletRequest.addHeader("Accept", "application/stream+json");

	EmitterProcessor<Bar> processor = EmitterProcessor.create();
	ResponseBodyEmitter emitter = handleValue(processor, Flux.class, forClass(Bar.class));

	EmitterHandler emitterHandler = new EmitterHandler();
	emitter.initialize(emitterHandler);

	ServletServerHttpResponse message = new ServletServerHttpResponse(this.servletResponse);
	emitter.extendResponse(message);

	Bar bar1 = new Bar("foo");
	Bar bar2 = new Bar("bar");

	processor.onNext(bar1);
	processor.onNext(bar2);
	processor.onComplete();

	assertEquals("application/stream+json", message.getHeaders().getContentType().toString());
	assertEquals(Arrays.asList(bar1, "\n", bar2, "\n"), emitterHandler.getValues());
}
 
Example #3
Source File: ResponseEntityAdvice.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
@Override
public Object beforeBodyWrite(Object o,
                              MethodParameter methodParameter,
                              MediaType mediaType,
                              Class<? extends HttpMessageConverter<?>> aClass,
                              ServerHttpRequest serverHttpRequest,
                              ServerHttpResponse HttpServletResponse) {
    if (serverHttpRequest instanceof ServletServerHttpRequest) {
        javax.servlet.http.HttpServletResponse response = ((ServletServerHttpResponse) HttpServletResponse).getServletResponse();
        if (hasError(HttpStatus.valueOf(response.getStatus()))) {
            return new Response(false, "status." + response.getStatus(), null, o);
        } else {
            return Response.ok(o);
        }
    }
    return o;
}
 
Example #4
Source File: HttpHeadersReturnValueHandler.java    From spring4-understanding with Apache License 2.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.isInstanceOf(HttpHeaders.class, returnValue);
	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 #5
Source File: RaptorHandlerExceptionResolver.java    From raptor with Apache License 2.0 6 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    if (RaptorHandlerUtils.isRaptorService(handler) && checkClient()) {
        log.error("RaptorHandlerExceptionResolver:",ex);
        response.setStatus(500);
        response.addHeader(RaptorConstants.HEADER_ERROR, "true");
        ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
        ErrorMessage errorMessage = createErrorMessage(ex);
        try {
            raptorMessageConverter.write(errorMessage, getMediaType(), outputMessage);
        } catch (IOException e) {
            log.error("Can't convert error message.", e);
            processConvertError(response, ex);
        }
        return new ModelAndView();
    }
    return null;
}
 
Example #6
Source File: ResponseEntityAdvice.java    From mPass with Apache License 2.0 6 votes vote down vote up
@Override
public Object beforeBodyWrite(Object o,
                              MethodParameter methodParameter,
                              MediaType mediaType,
                              Class<? extends HttpMessageConverter<?>> aClass,
                              ServerHttpRequest serverHttpRequest,
                              ServerHttpResponse HttpServletResponse) {
    if (serverHttpRequest instanceof ServletServerHttpRequest) {
        javax.servlet.http.HttpServletResponse response = ((ServletServerHttpResponse) HttpServletResponse).getServletResponse();
        if (hasError(HttpStatus.valueOf(response.getStatus()))) {
            return new Response(false, "status." + response.getStatus(), null, o);
        } else {
            return Response.ok(o);
        }
    }
    return o;
}
 
Example #7
Source File: HttpHeadersReturnValueHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(@Nullable 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);
		Assert.state(servletResponse != null, "No HttpServletResponse");
		ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
		outputMessage.getHeaders().putAll(headers);
		outputMessage.getBody();  // flush headers
	}
}
 
Example #8
Source File: HttpHeadersReturnValueHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(@Nullable 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);
		Assert.state(servletResponse != null, "No HttpServletResponse");
		ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
		outputMessage.getHeaders().putAll(headers);
		outputMessage.getBody();  // flush headers
	}
}
 
Example #9
Source File: AbstractMessageConverterMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example #10
Source File: HttpSockJsSessionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {

	super.setUp();

	this.frameFormat = new DefaultSockJsFrameFormat("%s");

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);

	this.servletRequest = new MockHttpServletRequest();
	this.servletRequest.setAsyncSupported(true);
	this.request = new ServletServerHttpRequest(this.servletRequest);
}
 
Example #11
Source File: SockJsServiceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-11919
public void handleInfoGetWildflyNPE() throws IOException {
	HttpServletResponse mockResponse = mock(HttpServletResponse.class);
	ServletOutputStream ous = mock(ServletOutputStream.class);
	given(mockResponse.getHeaders(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).willThrow(NullPointerException.class);
	given(mockResponse.getOutputStream()).willReturn(ous);
	this.response = new ServletServerHttpResponse(mockResponse);

	handleRequest("GET", "/echo/info", HttpStatus.OK);

	verify(mockResponse, times(1)).getOutputStream();
}
 
Example #12
Source File: AbstractMessageConverterMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example #13
Source File: SockJsServiceTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test  // SPR-11919
@SuppressWarnings("unchecked")
public void handleInfoGetWildflyNPE() throws Exception {
	HttpServletResponse mockResponse = mock(HttpServletResponse.class);
	ServletOutputStream ous = mock(ServletOutputStream.class);
	given(mockResponse.getHeaders(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).willThrow(NullPointerException.class);
	given(mockResponse.getOutputStream()).willReturn(ous);
	this.response = new ServletServerHttpResponse(mockResponse);

	handleRequest("GET", "/echo/info", HttpStatus.OK);

	verify(mockResponse, times(1)).getOutputStream();
}
 
Example #14
Source File: ObjectToStringHttpMessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
Example #15
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 #16
Source File: CustomAuthenticationEntryPoint.java    From spring-glee-o-meter with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
    ApiError apiError = new ApiError(UNAUTHORIZED);
    apiError.setMessage(e.getMessage());
    apiError.setDebugMessage(e.getMessage());

    ServerHttpResponse outputMessage = new ServletServerHttpResponse(httpServletResponse);
    outputMessage.setStatusCode(HttpStatus.UNAUTHORIZED);

    messageConverter.write(mapper.writeValueAsString(apiError), MediaType.APPLICATION_JSON, outputMessage);
}
 
Example #17
Source File: PropertiesHandlerMethodReturnValueHandler.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    Properties properties = (Properties) returnValue;

    ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;

    HttpServletResponse response = servletWebRequest.getResponse();
    ServletServerHttpResponse servletServerHttpResponse = new ServletServerHttpResponse(response);

    // 获取请求头
    HttpHeaders headers = servletServerHttpResponse.getHeaders();

    MediaType contentType = headers.getContentType();
    // 获取编码
    Charset charset = null;
    if (contentType != null) {
        charset = contentType.getCharset();
    }

    charset = charset == null ? Charset.forName("UTF-8") : charset;

    // 获取请求体
    OutputStream body = servletServerHttpResponse.getBody();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(body, charset);

    properties.store(outputStreamWriter, "Serialized by PropertiesHandlerMethodReturnValueHandler#handleReturnValue");

    // 告诉 Spring MVC 请求已经处理完毕
    mavContainer.setRequestHandled(true);
}
 
Example #18
Source File: JsonHandlerMethodReturnValueHandler.java    From everyone-java-blog 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);
    HttpServletResponse httpServletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
    httpServletResponse.setContentType(CONTENT_TYPE);
    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(httpServletResponse);
    JsonResponse jsonResponse = new JsonResponse(returnValue);
    outputMessage.getBody().write(StringUtils.toBytes(JsonUtils.toJson(jsonResponse)));
    outputMessage.getBody().flush();
}
 
Example #19
Source File: AbstractMessageConverterMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes the given return value to the given web request. Delegates to
 * {@link #writeWithMessageConverters(Object, MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse)}
 */
protected <T> void writeWithMessageConverters(T value, MethodParameter returnType, NativeWebRequest webRequest)
		throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
	writeWithMessageConverters(value, returnType, inputMessage, outputMessage);
}
 
Example #20
Source File: AnnotationMethodHandlerExceptionResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
private ModelAndView handleResponseBody(Object returnValue, ServletWebRequest webRequest)
		throws ServletException, IOException {

	HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());
	List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
	if (acceptedMediaTypes.isEmpty()) {
		acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
	}
	MediaType.sortByQualityValue(acceptedMediaTypes);
	HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());
	Class<?> returnValueType = returnValue.getClass();
	if (this.messageConverters != null) {
		for (MediaType acceptedMediaType : acceptedMediaTypes) {
			for (HttpMessageConverter messageConverter : this.messageConverters) {
				if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
					messageConverter.write(returnValue, acceptedMediaType, outputMessage);
					return new ModelAndView();
				}
			}
		}
	}
	if (logger.isWarnEnabled()) {
		logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " +
				acceptedMediaTypes);
	}
	return null;
}
 
Example #21
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 #22
Source File: SockJsHttpRequestHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
		throws ServletException, IOException {

	ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
	ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);

	try {
		this.sockJsService.handleRequest(request, response, getSockJsPath(servletRequest), this.webSocketHandler);
	}
	catch (Throwable ex) {
		throw new SockJsException("Uncaught failure in SockJS request, uri=" + request.getURI(), ex);
	}
}
 
Example #23
Source File: JettyRequestUpgradeStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
		String selectedProtocol, List<WebSocketExtension> selectedExtensions, Principal user,
		WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException {

	Assert.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required");
	HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

	Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required");
	HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse();

	Assert.isTrue(this.factory.isUpgradeRequest(servletRequest, servletResponse), "Not a WebSocket handshake");

	JettyWebSocketSession session = new JettyWebSocketSession(attributes, user);
	JettyWebSocketHandlerAdapter handlerAdapter = new JettyWebSocketHandlerAdapter(wsHandler, session);

	WebSocketHandlerContainer container =
			new WebSocketHandlerContainer(handlerAdapter, selectedProtocol, selectedExtensions);

	try {
		containerHolder.set(container);
		this.factory.acceptWebSocket(servletRequest, servletResponse);
	}
	catch (IOException ex) {
		throw new HandshakeFailureException(
				"Response update failed during upgrade to WebSocket: " + request.getURI(), ex);
	}
	finally {
		containerHolder.remove();
	}
}
 
Example #24
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(inputMessage.getServletRequest(), outputMessage.getServletResponse());
	HttpHeaders responseHeaders = outputMessage.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (inputMessage.getMethod() == HttpMethod.GET || inputMessage.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example #25
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void testEmitterContentType(String expected) throws Exception {
	ServletServerHttpResponse message = new ServletServerHttpResponse(this.servletResponse);
	ResponseBodyEmitter emitter = handleValue(Flux.empty(), Flux.class, forClass(String.class));
	emitter.extendResponse(message);
	assertEquals(expected, message.getHeaders().getContentType().toString());
	resetRequest();
}
 
Example #26
Source File: RequestResponseBodyAdviceChainTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {
	this.body = "body";
	this.contentType = MediaType.TEXT_PLAIN;
	this.converterType = StringHttpMessageConverter.class;
	this.paramType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), 0);
	this.returnType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), -1);
	this.request = new ServletServerHttpRequest(new MockHttpServletRequest());
	this.response = new ServletServerHttpResponse(new MockHttpServletResponse());
}
 
Example #27
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 #28
Source File: HttpEntityMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
	HttpHeaders responseHeaders = response.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example #29
Source File: JettyRequestUpgradeStrategy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
		String selectedProtocol, List<WebSocketExtension> selectedExtensions, Principal user,
		WebSocketHandler wsHandler, Map<String, Object> attributes) throws HandshakeFailureException {

	Assert.isInstanceOf(ServletServerHttpRequest.class, request);
	HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

	Assert.isInstanceOf(ServletServerHttpResponse.class, response);
	HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse();

	Assert.isTrue(this.factory.isUpgradeRequest(servletRequest, servletResponse), "Not a WebSocket handshake");

	JettyWebSocketSession session = new JettyWebSocketSession(attributes, user);
	JettyWebSocketHandlerAdapter handlerAdapter = new JettyWebSocketHandlerAdapter(wsHandler, session);

	WebSocketHandlerContainer container =
			new WebSocketHandlerContainer(handlerAdapter, selectedProtocol, selectedExtensions);

	try {
		wsContainerHolder.set(container);
		this.factory.acceptWebSocket(servletRequest, servletResponse);
	}
	catch (IOException ex) {
		throw new HandshakeFailureException(
				"Response update failed during upgrade to WebSocket: " + request.getURI(), ex);
	}
	finally {
		wsContainerHolder.remove();
	}
}
 
Example #30
Source File: DefaultCorsProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("resource")
public boolean processRequest(CorsConfiguration config, HttpServletRequest request, HttpServletResponse response)
		throws IOException {

	if (!CorsUtils.isCorsRequest(request)) {
		return true;
	}

	ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
	if (responseHasCors(serverResponse)) {
		logger.debug("Skip CORS processing: response already contains \"Access-Control-Allow-Origin\" header");
		return true;
	}

	ServletServerHttpRequest serverRequest = new ServletServerHttpRequest(request);
	if (WebUtils.isSameOrigin(serverRequest)) {
		logger.debug("Skip CORS processing: request is from same origin");
		return true;
	}

	boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
	if (config == null) {
		if (preFlightRequest) {
			rejectRequest(serverResponse);
			return false;
		}
		else {
			return true;
		}
	}

	return handleInternal(serverRequest, serverResponse, config, preFlightRequest);
}