Java Code Examples for org.springframework.http.server.ServletServerHttpResponse

The following examples show how to use org.springframework.http.server.ServletServerHttpResponse. These examples are extracted from open source projects. 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
@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
@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 3
Source Project: mPaaS   Source File: ResponseEntityAdvice.java    License: 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 Project: mPass   Source File: ResponseEntityAdvice.java    License: 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 5
@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 6
Source Project: java-technology-stack   Source File: ReactiveTypeHandlerTests.java    License: 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 7
Source Project: raptor   Source File: RaptorHandlerExceptionResolver.java    License: 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 8
@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 9
@SuppressWarnings("unchecked")
protected void writeEntityWithMessageConverters(Object entity, HttpServletRequest request,
		HttpServletResponse response, ServerResponse.Context context)
		throws ServletException, IOException {

	ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
	MediaType contentType = getContentType(response);
	Class<?> entityClass = entity.getClass();

	for (HttpMessageConverter<?> messageConverter : context.messageConverters()) {
		if (messageConverter instanceof GenericHttpMessageConverter<?>) {
			GenericHttpMessageConverter<Object> genericMessageConverter =
					(GenericHttpMessageConverter<Object>) messageConverter;
			if (genericMessageConverter.canWrite(this.entityType, entityClass, contentType)) {
				genericMessageConverter.write(entity, this.entityType, contentType, serverResponse);
				return;
			}
		}
		if (messageConverter.canWrite(entityClass, contentType)) {
			((HttpMessageConverter<Object>)messageConverter).write(entity, contentType, serverResponse);
			return;
		}
	}

	List<MediaType> producibleMediaTypes = producibleMediaTypes(context.messageConverters(), entityClass);
	throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
}
 
Example 10
/**
 * 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 11
/**
 * 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 12
@Test
public void shouldAddTraceeHeaderToResponse() {
	Tracee.getBackend().put(INVOCATION_ID_KEY, "mySuperValue");
	final HttpServletRequest request = mock(HttpServletRequest.class);
	final HttpServletResponse response = mock(HttpServletResponse.class);

	advice.beforeBodyWrite(null, null, null, null, new ServletServerHttpRequest(request), new ServletServerHttpResponse(response));
	verify(response).setHeader(eq(TraceeConstants.TPIC_HEADER), eq(INVOCATION_ID_KEY + "=mySuperValue"));
}
 
Example 13
@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 14
@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 15
@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 16
@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 17
Source Project: spring-analysis-note   Source File: ReactiveTypeHandlerTests.java    License: 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 18
Source Project: spring-analysis-note   Source File: JettyRequestUpgradeStrategy.java    License: 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 19
Source Project: spring-analysis-note   Source File: SockJsHttpRequestHandler.java    License: 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 20
Source Project: spring-analysis-note   Source File: SockJsServiceTests.java    License: 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 21
@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 22
Source Project: spring-analysis-note   Source File: DefaultCorsProcessor.java    License: MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("resource")
public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
		HttpServletResponse response) throws IOException {

	response.addHeader(HttpHeaders.VARY, HttpHeaders.ORIGIN);
	response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
	response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);

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

	if (response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) != null) {
		logger.trace("Skip: response already contains \"Access-Control-Allow-Origin\"");
		return true;
	}

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

	return handleInternal(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response), config, preFlightRequest);
}
 
Example 23
@Before
public void setup() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
Example 24
Source Project: Moss   Source File: InstancesProxyController.java    License: 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 25
@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 26
/**
 * 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 27
@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 28
Source Project: java-technology-stack   Source File: HttpEntityMethodProcessor.java    License: 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
@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 30
@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());
}