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

The following examples show how to use org.springframework.http.server.ServerHttpRequest. 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
Source Project: spring-boot-jpa   Source File: PageResponseBodyAdvisor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer,
		MediaType contentType, MethodParameter returnType,
		ServerHttpRequest request, ServerHttpResponse response) {

	Page<?> page = ((Page<?>) bodyContainer.getValue());

	response.getHeaders().add(CUSTOM_HEADER_META_PAGINATION,
			String.format(PAGE_METADATA_FMT, page.getNumber(), page.getSize(),
					page.getTotalElements(), page.getTotalPages(), page.isFirst(),
					page.isLast()));

	getHttpHeaderLinksString(request, page)
			.filter(StringUtils::isNotEmpty)
			.ifPresent(s -> response.getHeaders().add(HttpHeaders.LINK, s));

	// finally, strip out the actual content and replace it as the body value
	bodyContainer.setValue(page.getContent());
}
 
Example 2
@ResponseBody
@RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD,
		RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Flux<InstanceWebProxy.InstanceResponse> endpointProxy(
		@PathVariable("applicationName") String applicationName, HttpServletRequest servletRequest) {
	ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
	String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + APPLICATION_MAPPED_PATH,
			servletRequest);
	URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true)
			.toUri();

	Flux<DataBuffer> cachedBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096)
			.cache();

	return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), uri, request.getMethod(),
			this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(cachedBody));
}
 
Example 3
Source Project: uavstack   Source File: JSONPResponseBodyAdvice.java    License: 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 4
@Override
public void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
		AbstractHttpSockJsSession sockJsSession) throws SockJsException {

	String callback = getCallbackParam(request);
	if (!StringUtils.hasText(callback)) {
		response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
		try {
			response.getBody().write("\"callback\" parameter required".getBytes(UTF8_CHARSET));
		}
		catch (IOException ex) {
			sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
			throw new SockJsTransportFailureException("Failed to write to response", sockJsSession.getId(), ex);
		}
		return;
	}

	super.handleRequestInternal(request, response, sockJsSession);
}
 
Example 5
@Override
public void upgradeInternal(ServerHttpRequest httpRequest, ServerHttpResponse httpResponse,
		@Nullable String selectedProtocol, List<Extension> selectedExtensions, Endpoint endpoint)
		throws HandshakeFailureException {

	HttpServletRequest request = getHttpServletRequest(httpRequest);
	HttpServletResponse response = getHttpServletResponse(httpResponse);

	StringBuffer requestUrl = request.getRequestURL();
	String path = request.getRequestURI();  // shouldn't matter
	Map<String, String> pathParams = Collections.<String, String> emptyMap();

	ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(path, endpoint);
	endpointConfig.setSubprotocols(Collections.singletonList(selectedProtocol));
	endpointConfig.setExtensions(selectedExtensions);

	try {
		ServerContainer container = getContainer(request);
		upgradeMethod.invoke(container, request, response, endpointConfig, pathParams);
	}
	catch (Exception ex) {
		throw new HandshakeFailureException(
				"Servlet request failed to upgrade to WebSocket for " + requestUrl, ex);
	}
}
 
Example 6
Source Project: spring-analysis-note   Source File: HandshakeInterceptorChain.java    License: MIT License 6 votes vote down vote up
public boolean applyBeforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
		Map<String, Object> attributes) throws Exception {

	for (int i = 0; i < this.interceptors.size(); i++) {
		HandshakeInterceptor interceptor = this.interceptors.get(i);
		if (!interceptor.beforeHandshake(request, response, this.wsHandler, attributes)) {
			if (logger.isDebugEnabled()) {
				logger.debug(interceptor + " returns false from beforeHandshake - precluding handshake");
			}
			applyAfterHandshake(request, response, null);
			return false;
		}
		this.interceptorIndex = i;
	}
	return true;
}
 
Example 7
public boolean applyBeforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
		Map<String, Object> attributes) throws Exception {

	for (int i = 0; i < this.interceptors.size(); i++) {
		HandshakeInterceptor interceptor = this.interceptors.get(i);
		if (!interceptor.beforeHandshake(request, response, this.wsHandler, attributes)) {
			if (logger.isDebugEnabled()) {
				logger.debug(interceptor + " returns false from beforeHandshake - precluding handshake");
			}
			applyAfterHandshake(request, response, null);
			return false;
		}
		this.interceptorIndex = i;
	}
	return true;
}
 
Example 8
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
		WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

	HttpSession session = getSession(request);
	if (session != null) {
		if (isCopyHttpSessionId()) {
			attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId());
		}
		Enumeration<String> names = session.getAttributeNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			if (isCopyAllAttributes() || getAttributeNames().contains(name)) {
				attributes.put(name, session.getAttribute(name));
			}
		}
	}
	return true;
}
 
Example 9
Source Project: spring-analysis-note   Source File: AbstractSockJsService.java    License: MIT License 6 votes vote down vote up
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods)
		throws IOException {

	if (WebUtils.isSameOrigin(request)) {
		return true;
	}

	if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) {
		if (logger.isWarnEnabled()) {
			logger.warn("Origin header value '" + request.getHeaders().getOrigin() + "' not allowed.");
		}
		response.setStatusCode(HttpStatus.FORBIDDEN);
		return false;
	}

	return true;
}
 
Example 10
Source Project: WeEvent   Source File: WebSocketHandShakeInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get request ip,and check it
 *
 * @param request request
 * @return ip address
 */
private String getIpAddress(ServerHttpRequest request) {
    ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
    String ip = servletRequest.getServletRequest().getHeader("X-Forwarded-For");
    log.debug("ServerHttpRequest host: {}", ip);
    if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
        log.debug("unknown ServerHttpRequest host");
        return servletRequest.getRemoteAddress().getHostString();
    }

    String[] ips = ip.split(",");
    for (String strIp : ips) {
        if (!UNKNOWN.equalsIgnoreCase(strIp)) {
            return strIp;
        }
    }
    return "";
}
 
Example 11
Source Project: java-technology-stack   Source File: WebUtilsTests.java    License: 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 12
Source Project: spring-analysis-note   Source File: AbstractSockJsService.java    License: MIT License 6 votes vote down vote up
@Override
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
	if (request.getMethod() == HttpMethod.GET) {
		addNoCacheHeaders(response);
		if (checkOrigin(request, response)) {
			response.getHeaders().setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
			String content = String.format(
					INFO_CONTENT, random.nextInt(), isSessionCookieNeeded(), isWebSocketEnabled());
			response.getBody().write(content.getBytes());
		}

	}
	else if (request.getMethod() == HttpMethod.OPTIONS) {
		if (checkOrigin(request, response)) {
			addCacheHeaders(response);
			response.setStatusCode(HttpStatus.NO_CONTENT);
		}
	}
	else {
		sendMethodNotAllowed(response, HttpMethod.GET, HttpMethod.OPTIONS);
	}
}
 
Example 13
Source Project: flow-platform-x   Source File: ResponseMessageAdviser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object beforeBodyWrite(Object body,
                              MethodParameter returnType,
                              MediaType selectedContentType,
                              Class selectedConverterType,
                              ServerHttpRequest request,
                              ServerHttpResponse response) {

    if (body instanceof Resource) {
        return body;
    }

    if (MediaType.TEXT_PLAIN.equals(selectedContentType)) {
        return body;
    }

    return new ResponseMessage<>(StatusCode.OK, SUCCESS_MESSAGE, body);
}
 
Example 14
Source Project: data-highway   Source File: OfframpHandshakeInterceptor.java    License: 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 {

  log.info("Request received: {} {} - with headers: {}", request.getMethod(), request.getURI(), request.getHeaders());

  Map<String, String> segments = URI_TEMPLATE.match(request.getURI().getPath());
  attributes.put(VERSION, segments.get(VERSION));
  attributes.put(ROAD_NAME, segments.get(ROAD_NAME));
  attributes.put(STREAM_NAME, segments.get(STREAM_NAME));

  MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUri(request.getURI()).build().getQueryParams();

  DefaultOffset defaultOffset = Mono
      .justOrEmpty(parameters.getFirst(DEFAULT_OFFSET))
      .map(DefaultOffset::valueOf)
      .defaultIfEmpty(LATEST)
      .block();
  attributes.put(DEFAULT_OFFSET, defaultOffset);

  Set<Sensitivity> grants = Mono
      .justOrEmpty(parameters.get(GRANTS))
      .flatMapMany(Flux::fromIterable)
      .filter(s -> !s.isEmpty())
      .map(Sensitivity::valueOf)
      .collect(toSet())
      .block();
  attributes.put(GRANTS, grants);

  return super.beforeHandshake(request, response, wsHandler, attributes);
}
 
Example 15
Source Project: bird-java   Source File: RestJsonWrapperAdvice.java    License: MIT License 5 votes vote down vote up
@Override
public Object beforeBodyWrite(Object value, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> converter, ServerHttpRequest request, ServerHttpResponse response) {
    //返回结果时移除当前线程中的session数据
    SessionContext.removeSession();

    HttpHeaders headers = request.getHeaders();
    if(ArrayUtils.contains(INNER_CALL_HEADER,headers.getFirst("call"))){
        return value;
    }
    if(!(value instanceof OperationResult)){
        value = OperationResult.Success("success", value);
    }
    return value;
}
 
Example 16
@Override
public boolean beforeHandshake(ServerHttpRequest request,
                               ServerHttpResponse response,
                               WebSocketHandler wsHandler,
                               Map<String, Object> attributes) throws Exception {

    String sockJsPath = getSockJsPath(((ServletServerHttpRequest)request).getServletRequest());

    String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/");

    attributes.put("spaceKey", pathSegments[0]);

    return true;
}
 
Example 17
@Override
@Nullable
public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType contentType,
		Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	return processBody(body, returnType, contentType, converterType, request, response);
}
 
Example 18
@SuppressWarnings("unchecked")
@Nullable
private <T> Object processBody(@Nullable Object body, MethodParameter returnType, MediaType contentType,
		Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {
		if (advice.supports(returnType, converterType)) {
			body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,
					contentType, converterType, request, response);
		}
	}
	return body;
}
 
Example 19
protected void handleInvalidUpgradeHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
	if (logger.isErrorEnabled()) {
		logger.error("Handshake failed due to invalid Upgrade header: " + request.getHeaders().getUpgrade());
	}
	response.setStatusCode(HttpStatus.BAD_REQUEST);
	response.getBody().write("Can \"Upgrade\" only to \"WebSocket\".".getBytes(UTF8_CHARSET));
}
 
Example 20
@Override
@Nullable
public final Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType,
		MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	if (body == null) {
		return null;
	}
	MappingJacksonValue container = getOrCreateContainer(body);
	beforeBodyWriteInternal(container, contentType, returnType, request, response);
	return container;
}
 
Example 21
@Test
public void getBodyWithWrappedRequest() throws Exception {
	byte[] bytes = "content".getBytes("UTF-8");
	MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
	this.mockRequest.addFile(part);
	HttpServletRequest wrapped = new HttpServletRequestWrapper(this.mockRequest);
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(wrapped, "part");

	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
Example 22
@Test
public void getBody() throws Exception {
	byte[] bytes = "content".getBytes("UTF-8");
	MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
	this.mockRequest.addFile(part);
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part");

	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
Example 23
@Override
@Nullable
public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType contentType,
		Class<? extends HttpMessageConverter<?>> converterType,
		ServerHttpRequest request, ServerHttpResponse response) {

	return processBody(body, returnType, contentType, converterType, request, response);
}
 
Example 24
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
		Map<String, Object> attributes) {
	if (request instanceof ServletServerHttpRequest) {
		ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
		HttpSession session = servletRequest.getServletRequest().getSession(false);
		if (session != null) {
			setSessionId(attributes, session.getId());
		}
	}
	return true;
}
 
Example 25
@Nullable
private HttpSession getSession(ServerHttpRequest request) {
	if (request instanceof ServletServerHttpRequest) {
		ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
		return serverRequest.getServletRequest().getSession(isCreateSession());
	}
	return null;
}
 
Example 26
/**
 * Handle the first request for receiving messages on a SockJS HTTP transport
 * based session.
 * <p>Long polling-based transports (e.g. "xhr", "jsonp") complete the request
 * after writing the open frame. Streaming-based transports ("xhr_streaming",
 * "eventsource", and "htmlfile") leave the response open longer for further
 * streaming of message frames but will also close it eventually after some
 * amount of data has been sent.
 * @param request the current request
 * @param response the current response
 * @param frameFormat the transport-specific SocksJS frame format to use
 */
public void handleInitialRequest(ServerHttpRequest request, ServerHttpResponse response,
		SockJsFrameFormat frameFormat) throws SockJsException {

	this.uri = request.getURI();
	this.handshakeHeaders = request.getHeaders();
	this.principal = request.getPrincipal();
	this.localAddress = request.getLocalAddress();
	this.remoteAddress = request.getRemoteAddress();

	synchronized (this.responseLock) {
		try {
			this.response = response;
			this.frameFormat = frameFormat;
			this.asyncRequestControl = request.getAsyncRequestControl(response);
			this.asyncRequestControl.start(-1);

			disableShallowEtagHeaderFilter(request);

			// Let "our" handler know before sending the open frame to the remote handler
			delegateConnectionEstablished();

			handleRequestInternal(request, response, true);

			// Request might have been reset (e.g. polling sessions do after writing)
			this.readyToSend = isActive();
		}
		catch (Throwable ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
			throw new SockJsTransportFailureException("Failed to open session", getId(), ex);
		}
	}
}
 
Example 27
Source Project: java-technology-stack   Source File: WebSocketTransportHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
		WebSocketHandler wsHandler, SockJsSession wsSession) throws SockJsException {

	WebSocketServerSockJsSession sockJsSession = (WebSocketServerSockJsSession) wsSession;
	try {
		wsHandler = new SockJsWebSocketHandler(getServiceConfig(), wsHandler, sockJsSession);
		this.handshakeHandler.doHandshake(request, response, wsHandler, sockJsSession.getAttributes());
	}
	catch (Throwable ex) {
		sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
		throw new SockJsTransportFailureException("WebSocket handshake failure", wsSession.getId(), ex);
	}
}
 
Example 28
@Override
public WxMessage beforeBodyWrite(WxMessage body, MethodParameter returnType,
                                 MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                 ServerHttpRequest request, ServerHttpResponse response) {
    if (!(request instanceof ServletServerHttpRequest) || body == null) {
        return body;
    }
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    WxRequest wxRequest = WxWebUtils.getWxRequestFromRequest(servletRequest);
    return wxMessageProcessor.process(new WxRequestMessageParameter(wxRequest), body);
}
 
Example 29
public void applyAfterHandshake(ServerHttpRequest request, ServerHttpResponse response, Exception failure) {
	for (int i = this.interceptorIndex; i >= 0; i--) {
		HandshakeInterceptor interceptor = this.interceptors.get(i);
		try {
			interceptor.afterHandshake(request, response, this.wsHandler, failure);
		}
		catch (Throwable ex) {
			if (logger.isWarnEnabled()) {
				logger.warn(interceptor + " threw exception in afterHandshake: " + ex);
			}
		}
	}
}
 
Example 30
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType,
		Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
	if (null != body) {

		boolean encode = false;
		if (methodParameter.getMethod()
				.isAnnotationPresent((Class<? extends Annotation>) SecurityParameter.class)) {
			final SecurityParameter serializedField = (SecurityParameter) methodParameter
					.getMethodAnnotation((Class) SecurityParameter.class);
			encode = serializedField.outEncode();
		}
		if (encode) {
			log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");
			final ObjectMapper objectMapper = new ObjectMapper();
			try {
				final String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
				return DESHelper.encrypt(result);
			} catch (Exception e) {
				log.info(
						"对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密出现异常:" + e.getMessage());
			}
		}
		
	}

	return body;
}