org.springframework.http.server.ServletServerHttpRequest Java Examples

The following examples show how to use org.springframework.http.server.ServletServerHttpRequest. 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: FastJsonpResponseBodyAdvice.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked only if the converter type is {@code FastJsonpHttpMessageConverter4}.
 */
public void beforeBodyWriteInternal(MappingFastJsonValue bodyContainer, MediaType contentType,
                                    MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    for (String name : this.jsonpQueryParamNames) {
        String value = servletRequest.getParameter(name);
        if (value != null) {
            if (!isValidJsonpQueryParam(value)) {
                continue;
            }
            // MediaType contentTypeToUse = getContentType(contentType, request, response);
            // response.getHeaders().setContentType(contentTypeToUse);
            bodyContainer.setJsonpFunction(value);
            break;
        }
    }
}
 
Example #2
Source File: UriComponentsBuilderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void fromHttpRequestWithForwardedHostWithForwardedScheme() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(10080);
	request.addHeader("X-Forwarded-Host", "example.org");
	request.addHeader("X-Forwarded-Proto", "https");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("example.org", result.getHost());
	assertEquals("https", result.getScheme());
	assertEquals(-1, result.getPort());
}
 
Example #3
Source File: UriComponentsBuilderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void fromHttpRequest() throws URISyntaxException {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(-1);
	request.setRequestURI("/path");
	request.setQueryString("a=1");

	UriComponents result = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).build();
	assertEquals("http", result.getScheme());
	assertEquals("localhost", result.getHost());
	assertEquals(-1, result.getPort());
	assertEquals("/path", result.getPath());
	assertEquals("a=1", result.getQuery());
}
 
Example #4
Source File: ServletUriComponentsBuilder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize a builder with a scheme, host,and port (but not path and query).
 */
private static ServletUriComponentsBuilder initFromRequest(HttpServletRequest request) {
	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();
	String scheme = uriComponents.getScheme();
	String host = uriComponents.getHost();
	int port = uriComponents.getPort();

	ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder();
	builder.scheme(scheme);
	builder.host(host);
	if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) {
		builder.port(port);
	}
	return builder;
}
 
Example #5
Source File: UriComponentsBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void fromHttpRequestMultipleForwardedHeader()  {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addHeader("Forwarded", "host=84.198.58.199;proto=https");
	request.addHeader("Forwarded", "proto=ftp; host=1.2.3.4");
	request.setScheme("http");
	request.setServerName("example.com");
	request.setRequestURI("/rest/mobile/users/1");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https", result.getScheme());
	assertEquals("84.198.58.199", result.getHost());
	assertEquals("/rest/mobile/users/1", result.getPath());
}
 
Example #6
Source File: UriComponentsBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void fromHttpRequest() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(-1);
	request.setRequestURI("/path");
	request.setQueryString("a=1");

	UriComponents result = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).build();
	assertEquals("http", result.getScheme());
	assertEquals("localhost", result.getHost());
	assertEquals(-1, result.getPort());
	assertEquals("/path", result.getPath());
	assertEquals("a=1", result.getQuery());
}
 
Example #7
Source File: RequestResponseBodyAdviceChainTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void requestBodyAdvice() throws IOException {
	RequestBodyAdvice requestAdvice = Mockito.mock(RequestBodyAdvice.class);
	ResponseBodyAdvice<String> responseAdvice = Mockito.mock(ResponseBodyAdvice.class);
	List<Object> advice = Arrays.asList(requestAdvice, responseAdvice);
	RequestResponseBodyAdviceChain chain = new RequestResponseBodyAdviceChain(advice);

	HttpInputMessage wrapped = new ServletServerHttpRequest(new MockHttpServletRequest());
	given(requestAdvice.supports(this.paramType, String.class, this.converterType)).willReturn(true);
	given(requestAdvice.beforeBodyRead(eq(this.request), eq(this.paramType), eq(String.class),
			eq(this.converterType))).willReturn(wrapped);

	assertSame(wrapped, chain.beforeBodyRead(this.request, this.paramType, String.class, this.converterType));

	String modified = "body++";
	given(requestAdvice.afterBodyRead(eq(this.body), eq(this.request), eq(this.paramType),
			eq(String.class), eq(this.converterType))).willReturn(modified);

	assertEquals(modified, chain.afterBodyRead(this.body, this.request, this.paramType,
			String.class, this.converterType));
}
 
Example #8
Source File: UriComponentsBuilderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void fromHttpRequestMultipleForwardedHeader() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addHeader("Forwarded", "host=84.198.58.199;proto=https");
	request.addHeader("Forwarded", "proto=ftp; host=1.2.3.4");
	request.setScheme("http");
	request.setServerName("example.com");
	request.setRequestURI("/rest/mobile/users/1");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https", result.getScheme());
	assertEquals("84.198.58.199", result.getHost());
	assertEquals("/rest/mobile/users/1", result.getPath());
}
 
Example #9
Source File: WebUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if the request is a same-origin one, based on {@code Origin}, {@code Host},
 * {@code Forwarded} and {@code X-Forwarded-Host} headers.
 * @return {@code true} if the request is a same-origin one, {@code false} in case
 * of cross-origin request
 * @since 4.2
 */
public static boolean isSameOrigin(HttpRequest request) {
	String origin = request.getHeaders().getOrigin();
	if (origin == null) {
		return true;
	}
	UriComponentsBuilder urlBuilder;
	if (request instanceof ServletServerHttpRequest) {
		// Build more efficiently if we can: we only need scheme, host, port for origin comparison
		HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
		urlBuilder = new UriComponentsBuilder().
				scheme(servletRequest.getScheme()).
				host(servletRequest.getServerName()).
				port(servletRequest.getServerPort()).
				adaptFromForwardedHeaders(request.getHeaders());
	}
	else {
		urlBuilder = UriComponentsBuilder.fromHttpRequest(request);
	}
	UriComponents actualUrl = urlBuilder.build();
	UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();
	return (ObjectUtils.nullSafeEquals(actualUrl.getHost(), originUrl.getHost()) &&
			getPort(actualUrl) == getPort(originUrl));
}
 
Example #10
Source File: WebSocketInterceptor.java    From FlyCms with MIT License 6 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1, WebSocketHandler arg2,
		Map<String, Object> attributes) throws Exception {
	// 将ServerHttpRequest转换成request请求相关的类,用来获取request域中的用户信息
	if (request instanceof ServletServerHttpRequest) {
		ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
		HttpSession session = servletRequest.getServletRequest().getSession(false);
		if (session != null) {
			// 使用userName区分WebSocketHandler,以便定向发送消息
			User user = (User) session.getAttribute(Const.SESSION_USER);
			//System.out.println("=======当前登录用户=======" + user.getUserId());
			attributes.put("accountId", user.getUserId());
			attributes.put("sessionid", session.getId());
		}else {
			return false;
		}
	}
	//System.out.println("连接到我了");
	return true;
}
 
Example #11
Source File: UriComponentsBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12816
public void fromHttpRequestWithForwardedProtoMultiValueHeader() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(8080);
	request.setRequestURI("/mvc-showcase");
	request.addHeader("X-Forwarded-Host", "a.example.org");
	request.addHeader("X-Forwarded-Port", "443");
	request.addHeader("X-Forwarded-Proto", "https,https");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https://a.example.org/mvc-showcase", result.toString());
}
 
Example #12
Source File: UriComponentsBuilderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void fromHttpRequestWithForwardedProtoMultiValueHeader() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(8080);
	request.setRequestURI("/mvc-showcase");
	request.addHeader("X-Forwarded-Host", "a.example.org");
	request.addHeader("X-Forwarded-Port", "443");
	request.addHeader("X-Forwarded-Proto", "https,https");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https://a.example.org/mvc-showcase", result.toString());
}
 
Example #13
Source File: ServletUriComponentsBuilderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void fromRequestWithForwardedHostAndPort() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(80);
	request.setRequestURI("/mvc-showcase");
	request.addHeader("X-Forwarded-Proto", "https");
	request.addHeader("X-Forwarded-Host", "84.198.58.199");
	request.addHeader("X-Forwarded-Port", "443");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https://84.198.58.199/mvc-showcase", result.toString());
}
 
Example #14
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 #15
Source File: ServletUriComponentsBuilder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize a builder with a scheme, host,and port (but not path and query).
 */
private static ServletUriComponentsBuilder initFromRequest(HttpServletRequest request) {
	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();
	String scheme = uriComponents.getScheme();
	String host = uriComponents.getHost();
	int port = uriComponents.getPort();

	ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder();
	builder.scheme(scheme);
	builder.host(host);
	if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) {
		builder.port(port);
	}
	return builder;
}
 
Example #16
Source File: WebUtilsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void testWithXForwardedHeaders(String serverName, int port, String forwardedProto,
		String forwardedHost, int forwardedPort, String originHeader) throws Exception {

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setServerName(serverName);
	if (port != -1) {
		request.setServerPort(port);
	}
	if (forwardedProto != null) {
		request.addHeader("X-Forwarded-Proto", forwardedProto);
	}
	if (forwardedHost != null) {
		request.addHeader("X-Forwarded-Host", forwardedHost);
	}
	if (forwardedPort != -1) {
		request.addHeader("X-Forwarded-Port", String.valueOf(forwardedPort));
	}
	request.addHeader(HttpHeaders.ORIGIN, originHeader);

	HttpServletRequest requestToUse = adaptFromForwardedHeaders(request);
	ServerHttpRequest httpRequest = new ServletServerHttpRequest(requestToUse);

	assertTrue(WebUtils.isSameOrigin(httpRequest));
}
 
Example #17
Source File: JSONPResponseBodyAdvice.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                              Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                              ServerHttpResponse response) {

    ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class);
    if(responseJsonp == null){
        responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class);
    }

    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    String callbackMethodName = servletRequest.getParameter(responseJsonp.callback());

    if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invalid jsonp parameter value:" + callbackMethodName);
        }
        callbackMethodName = null;
    }

    JSONPObject jsonpObject = new JSONPObject(callbackMethodName);
    jsonpObject.addParameter(body);
    beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response);
    return jsonpObject;
}
 
Example #18
Source File: HttpEntityMethodProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
	List<String> ifNoneMatch = inputMessage.getHeaders().getIfNoneMatch();
	long ifModifiedSince = inputMessage.getHeaders().getIfModifiedSince();
	String eTag = addEtagPadding(outputMessage.getHeaders().getETag());
	long lastModified = outputMessage.getHeaders().getLastModified();
	boolean notModified = false;

	if (!ifNoneMatch.isEmpty() && (inputMessage.getHeaders().containsKey(HttpHeaders.IF_UNMODIFIED_SINCE)
			|| inputMessage.getHeaders().containsKey(HttpHeaders.IF_MATCH))) {
		// invalid conditional request, do not process
	}
	else if (lastModified != -1 && StringUtils.hasLength(eTag)) {
		notModified = isETagNotModified(ifNoneMatch, eTag) && isTimeStampNotModified(ifModifiedSince, lastModified);
	}
	else if (lastModified != -1) {
		notModified = isTimeStampNotModified(ifModifiedSince, lastModified);
	}
	else if (StringUtils.hasLength(eTag)) {
		notModified = isETagNotModified(ifNoneMatch, eTag);
	}
	return notModified;
}
 
Example #19
Source File: UriComponentsBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-12816
public void fromHttpRequestWithForwardedProtoMultiValueHeader() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(8080);
	request.setRequestURI("/mvc-showcase");
	request.addHeader("X-Forwarded-Host", "a.example.org");
	request.addHeader("X-Forwarded-Port", "443");
	request.addHeader("X-Forwarded-Proto", "https,https");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https://a.example.org/mvc-showcase", result.toString());
}
 
Example #20
Source File: UriComponentsBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void fromHttpRequestForwardedHeaderWithoutHostPortAndWithServerPort()  {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addHeader("Forwarded", "proto=https; host=84.198.58.199");
	request.setScheme("http");
	request.setServerPort(8080);
	request.setServerName("example.com");
	request.setRequestURI("/rest/mobile/users/1");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https", result.getScheme());
	assertEquals("84.198.58.199", result.getHost());
	assertEquals("/rest/mobile/users/1", result.getPath());
	assertEquals(-1, result.getPort());
	assertEquals("https://84.198.58.199/rest/mobile/users/1", result.toUriString());
}
 
Example #21
Source File: UriComponentsBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-12771
public void fromHttpRequestResetsPortBeforeSettingIt() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addHeader("X-Forwarded-Proto", "https");
	request.addHeader("X-Forwarded-Host", "84.198.58.199");
	request.addHeader("X-Forwarded-Port", 443);
	request.setScheme("http");
	request.setServerName("example.com");
	request.setServerPort(80);
	request.setRequestURI("/rest/mobile/users/1");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https", result.getScheme());
	assertEquals("84.198.58.199", result.getHost());
	assertEquals(-1, result.getPort());
	assertEquals("/rest/mobile/users/1", result.getPath());
}
 
Example #22
Source File: UriComponentsBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void fromHttpRequestForwardedHeaderWithHostPortAndWithoutServerPort()  {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addHeader("Forwarded", "proto=https; host=84.198.58.199:9090");
	request.setScheme("http");
	request.setServerName("example.com");
	request.setRequestURI("/rest/mobile/users/1");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https", result.getScheme());
	assertEquals("84.198.58.199", result.getHost());
	assertEquals("/rest/mobile/users/1", result.getPath());
	assertEquals(9090, result.getPort());
	assertEquals("https://84.198.58.199:9090/rest/mobile/users/1", result.toUriString());
}
 
Example #23
Source File: UriComponentsBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12771
public void fromHttpRequestWithForwardedProtoAndDefaultPort() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(80);
	request.setRequestURI("/mvc-showcase");
	request.addHeader("X-Forwarded-Proto", "https");
	request.addHeader("X-Forwarded-Host", "84.198.58.199");
	request.addHeader("X-Forwarded-Port", "443");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https://84.198.58.199/mvc-showcase", result.toString());
}
 
Example #24
Source File: FilterAdvice.java    From jfilter with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to find filter and extract ignorable fields from methodParameter
 *
 * @param obj                {@link Object} object sent from response of Spring Web Service
 * @param methodParameter    {@link MethodParameter}
 * @param mediaType          {@link MediaType}
 * @param aClass             {@link HttpMessageConverter}
 * @param serverHttpRequest  {@link ServerHttpRequest}
 * @param serverHttpResponse {@link ServerHttpResponse}
 * @return {@link FilterClassWrapper} if BaseFilter is found FilterClassWrapper contains list of ignorable fields,
 * else returns FilterClassWrapper with HashMap zero length
 */
@Override
public Serializable beforeBodyWrite(Object obj, MethodParameter methodParameter, MediaType mediaType,
                                    Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                    ServerHttpResponse serverHttpResponse) {
    FilterFields filterFields;

    //Getting HttpServletRequest from serverHttpRequest
    HttpServletRequest servletServerHttpRequest = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
    RequestSession requestSession = new RequestSession(servletServerHttpRequest);

    //Proccess filters
    BaseFilter filter = filterProvider.getFilter(methodParameter);
    if (filter != null) {
        //Get fields from static filter
        filterFields = filter.getFields(obj, requestSession);
    } else {
        //Get fields from dynamic filter
        filterFields = dynamicFilterProvider.getFields(methodParameter, requestSession);
    }

    MethodParameterDetails methodParameterDetails = new MethodParameterDetails(methodParameter, mediaType, filterFields);

    return new FilterClassWrapper(obj, methodParameterDetails);
}
 
Example #25
Source File: RaptorHandlerMethodProcessor.java    From raptor with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
    HttpMethod httpMethod = inputMessage.getMethod();
    switch (httpMethod) {
        case GET:
        case HEAD:
            return bindData(parameter, mavContainer, webRequest, binderFactory);
        case POST:
        case PUT:
        case PATCH:
        case DELETE:
        case OPTIONS:
            return convertBody(parameter, mavContainer, webRequest, binderFactory);
        default:
            return null;
    }
}
 
Example #26
Source File: ForwardedHeaderFilter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
ForwardedHeaderExtractingRequest(HttpServletRequest request, UrlPathHelper pathHelper) {
	super(request);

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();
	int port = uriComponents.getPort();

	this.scheme = uriComponents.getScheme();
	this.secure = "https".equals(this.scheme);
	this.host = uriComponents.getHost();
	this.port = (port == -1 ? (this.secure ? 443 : 80) : port);

	String baseUrl = this.scheme + "://" + this.host + (port == -1 ? "" : ":" + port);
	Supplier<HttpServletRequest> delegateRequest = () -> (HttpServletRequest) getRequest();
	this.forwardedPrefixExtractor = new ForwardedPrefixExtractor(delegateRequest, pathHelper, baseUrl);
}
 
Example #27
Source File: RequestResponseBodyMethodProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter methodParam,
		Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {

	HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
	ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);

	Object arg = readWithMessageConverters(inputMessage, methodParam, paramType);
	if (arg == null) {
		if (methodParam.getParameterAnnotation(RequestBody.class).required()) {
			throw new HttpMessageNotReadableException("Required request body is missing: " +
					methodParam.getMethod().toGenericString());
		}
	}
	return arg;
}
 
Example #28
Source File: DispatcherServlet.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * No handler found -> set appropriate HTTP response status.
 * @param request current HTTP request
 * @param response current HTTP response
 * @throws Exception if preparing the response failed
 */
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
	if (pageNotFoundLogger.isWarnEnabled()) {
		pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + getRequestUri(request) +
				"] in DispatcherServlet with name '" + getServletName() + "'");
	}
	if (this.throwExceptionIfNoHandlerFound) {
		throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
				new ServletServerHttpRequest(request).getHeaders());
	}
	else {
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
	}
}
 
Example #29
Source File: ForwardedHeaderFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sendRedirect(String location) throws IOException {
	UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(location);

	// Absolute location
	if (builder.build().getScheme() != null) {
		super.sendRedirect(location);
		return;
	}

	// Network-path reference
	if (location.startsWith("//")) {
		String scheme = this.request.getScheme();
		super.sendRedirect(builder.scheme(scheme).toUriString());
		return;
	}

	// Relative to Servlet container root or to current request
	String path = (location.startsWith(FOLDER_SEPARATOR) ? location :
			StringUtils.applyRelativePath(this.request.getRequestURI(), location));

	String result = UriComponentsBuilder
			.fromHttpRequest(new ServletServerHttpRequest(this.request))
			.replacePath(path)
			.build().normalize().toUriString();

	super.sendRedirect(result);
}
 
Example #30
Source File: HttpHandshakeInterceptor.java    From openvidu with Apache License 2.0 5 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
		Map<String, Object> attributes) throws Exception {
	if (request instanceof ServletServerHttpRequest) {
		HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession();
		session.setMaxInactiveInterval(1800); // HttpSession will expire in 30 minutes
		attributes.put("httpSession", session);
		log.info("{} HttpSession {}", session.isNew() ? "New" : "Old", session.getId());
	}
	return true;
}