org.springframework.http.server.reactive.ServerHttpRequest Java Examples

The following examples show how to use org.springframework.http.server.reactive.ServerHttpRequest. 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: TracingWebFilter.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {
  final ServerHttpRequest request = exchange.getRequest();

  if (!shouldBeTraced(request)) {
    return chain.filter(exchange);
  }

  if (exchange.getAttribute(SERVER_SPAN_CONTEXT) != null) {
    if (LOG.isTraceEnabled()) {
      LOG.trace("Not tracing request " + request + " because it is already being traced");
    }
    return chain.filter(exchange);
  }

  return new TracingOperator(chain.filter(exchange), exchange, tracer, spanDecorators);
}
 
Example #2
Source File: SynchronossPartHttpMessageReaderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolveParts() {
	ServerHttpRequest request = generateMultipartRequest();
	ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class);
	MultiValueMap<String, Part> parts = this.reader.readMono(elementType, request, emptyMap()).block();
	assertEquals(2, parts.size());

	assertTrue(parts.containsKey("fooPart"));
	Part part = parts.getFirst("fooPart");
	assertTrue(part instanceof FilePart);
	assertEquals("fooPart", part.name());
	assertEquals("foo.txt", ((FilePart) part).filename());
	DataBuffer buffer = DataBufferUtils.join(part.content()).block();
	assertEquals(12, buffer.readableByteCount());
	byte[] byteContent = new byte[12];
	buffer.read(byteContent);
	assertEquals("Lorem Ipsum.", new String(byteContent));

	assertTrue(parts.containsKey("barPart"));
	part = parts.getFirst("barPart");
	assertTrue(part instanceof FormFieldPart);
	assertEquals("barPart", part.name());
	assertEquals("bar", ((FormFieldPart) part).value());
}
 
Example #3
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@GetMapping(MONO_ENDPOINT_PATH)
@ResponseBody
Mono<String> monoEndpoint(ServerHttpRequest request) {
    HttpHeaders headers = request.getHeaders();

    if ("true".equals(headers.getFirst("throw-exception"))) {
        throw new ApiException(ERROR_THROWN_IN_MONO_ENDPOINT);
    }

    if ("true".equals(headers.getFirst("return-exception-in-mono"))) {
        return Mono.error(
            new ApiException(ERROR_RETURNED_IN_MONO_ENDPOINT_MONO)
        );
    }

    return Mono.just(MONO_RESPONSE_PAYLOAD);
}
 
Example #4
Source File: DefaultServerResponseBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return this.inserter.insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example #5
Source File: InstancesProxyController.java    From Moss with Apache License 2.0 6 votes vote down vote up
@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,
                                ServerHttpRequest request,
                                ServerHttpResponse response) {
    String endpointLocalPath = getEndpointLocalPath(request.getPath().pathWithinApplication().value());
    URI uri = UriComponentsBuilder.fromPath(endpointLocalPath)
                                  .query(request.getURI().getRawQuery())
                                  .build(true)
                                  .toUri();

    return super.forward(instanceId, uri, request.getMethod(), request.getHeaders(),
        () -> BodyInserters.fromDataBuffers(request.getBody())).flatMap(clientResponse -> {
        response.setStatusCode(clientResponse.statusCode());
        response.getHeaders().addAll(filterHeaders(clientResponse.headers().asHttpHeaders()));
        return response.writeAndFlushWith(clientResponse.body(BodyExtractors.toDataBuffers()).window(1));
    });
}
 
Example #6
Source File: CrossFilter.java    From soul with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("all")
public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    if (CorsUtils.isCorsRequest(request)) {
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
        headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
        headers.add("Access-Control-Max-Age", MAX_AGE);
        headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS);
        headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE);
        headers.add("Access-Control-Allow-Credentials", "true");
        if (request.getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
    }
    return chain.filter(exchange);
}
 
Example #7
Source File: ReactiveUserOperator.java    From light-security with Apache License 2.0 6 votes vote down vote up
/**
 * 从request中获取token
 *
 * @param request request
 * @return token
 */
private String getTokenFromRequest(ServerHttpRequest request) {
    List<String> headers = request.getHeaders()
            .get(ConstantsSecurity.AUTHORIZATION_HEADER);
    if (CollectionUtils.isEmpty(headers)) {
        throw new LightSecurityException("没有找到名为Authorization的header");
    }
    String header = headers.get(0);
    if (!header.startsWith(ConstantsSecurity.BEARER)) {
        throw new LightSecurityException("token必须以'Bearer '开头");
    }
    if (header.length() <= SEVEN) {
        throw new LightSecurityException("token非法,长度 <= 7");
    }

    return header.substring(SEVEN);
}
 
Example #8
Source File: CorsFilter.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain chain) {
    ServerHttpRequest request = serverWebExchange.getRequest();
    ServerHttpResponse response = serverWebExchange.getResponse();
    HttpHeaders headers = response.getHeaders();
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
    headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
    headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
    if (request.getMethod() == HttpMethod.OPTIONS) {
        response.setStatusCode(HttpStatus.OK);
        return Mono.empty();
    }
    return chain.filter(serverWebExchange);
}
 
Example #9
Source File: TracingWebFilter.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
/**
 * It checks whether a request should be traced or not.
 *
 * @return whether request should be traced or not
 */
protected boolean shouldBeTraced(final ServerHttpRequest request) {
    final PathContainer pathWithinApplication = request.getPath().pathWithinApplication();
    // skip URLs matching skip pattern
    // e.g. pattern is defined as '/health|/status' then URL 'http://localhost:5000/context/health' won't be traced
    if (skipPattern != null) {
        final String url = pathWithinApplication.value();
        if (skipPattern.matcher(url).matches()) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Not tracing request " + request + " because it matches skip pattern: " + skipPattern);
            }
            return false;
        }
    }
    if (!urlPatterns.isEmpty() && urlPatterns.stream().noneMatch(urlPattern -> urlPattern.matches(pathWithinApplication))) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Not tracing request " + request + " because it does not match any URL pattern: " + urlPatterns);
        }
        return false;
    }
    return true;
}
 
Example #10
Source File: CorsUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Check if the request is a same-origin one, based on {@code Origin}, and
 * {@code Host} headers.
 *
 * <p><strong>Note:</strong> as of 5.1 this method ignores
 * {@code "Forwarded"} and {@code "X-Forwarded-*"} headers that specify the
 * client-originated address. Consider using the {@code ForwardedHeaderFilter}
 * to extract and use, or to discard such headers.
 *
 * @return {@code true} if the request is a same-origin one, {@code false} in case
 * of a cross-origin request
 * @deprecated as of 5.2, same-origin checks are performed directly by {@link #isCorsRequest}
 */
@Deprecated
public static boolean isSameOrigin(ServerHttpRequest request) {
	String origin = request.getHeaders().getOrigin();
	if (origin == null) {
		return true;
	}

	URI uri = request.getURI();
	String actualScheme = uri.getScheme();
	String actualHost = uri.getHost();
	int actualPort = getPort(uri.getScheme(), uri.getPort());
	Assert.notNull(actualScheme, "Actual request scheme must not be null");
	Assert.notNull(actualHost, "Actual request host must not be null");
	Assert.isTrue(actualPort != -1, "Actual request port must not be undefined");

	UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();
	return (actualScheme.equals(originUrl.getScheme()) &&
			actualHost.equals(originUrl.getHost()) &&
			actualPort == getPort(originUrl.getScheme(), originUrl.getPort()));
}
 
Example #11
Source File: WingtipsSpringWebfluxComponentTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@GetMapping(FLUX_ENDPOINT_PATH)
@ResponseBody
Flux<String> fluxEndpoint(ServerHttpRequest request) {
    HttpHeaders headers = request.getHeaders();

    if ("true".equals(headers.getFirst("throw-exception"))) {
        sleepThread(SLEEP_TIME_MILLIS);
        throw new RuntimeException("Error thrown in fluxEndpoint(), outside Flux");
    }

    if ("true".equals(headers.getFirst("return-exception-in-flux"))) {
        return Flux.just("foo")
                   .delayElements(Duration.ofMillis(SLEEP_TIME_MILLIS))
                   .map(d -> {
                       throw new RuntimeException("Error thrown in fluxEndpoint(), inside Flux");
                   });
    }

    long delayPerElementMillis = SLEEP_TIME_MILLIS / FLUX_ENDPOINT_PAYLOAD.size();
    return Flux.fromIterable(FLUX_ENDPOINT_PAYLOAD).delayElements(Duration.ofMillis(delayPerElementMillis));
}
 
Example #12
Source File: CorsUtilsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
private void testWithForwardedHeader(String serverName, int port,
		String forwardedHeader, String originHeader) {

	String url = "http://" + serverName;
	if (port != -1) {
		url = url + ":" + port;
	}

	MockServerHttpRequest.BaseBuilder<?> builder = get(url)
			.header("Forwarded", forwardedHeader)
			.header(HttpHeaders.ORIGIN, originHeader);

	ServerHttpRequest request = adaptFromForwardedHeaders(builder);
	assertTrue(CorsUtils.isSameOrigin(request));
}
 
Example #13
Source File: DefaultServerResponseBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	return this.inserter.insert(exchange.getResponse(), new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return context.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.of(exchange.getRequest());
		}
		@Override
		public Map<String, Object> hints() {
			hints.put(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			return hints;
		}
	});
}
 
Example #14
Source File: RequestHeaderSizeGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(RequestHeaderSizeGatewayFilterFactory.Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			ServerHttpRequest request = exchange.getRequest();
			HttpHeaders headers = request.getHeaders();
			Long headerSizeInBytes = 0L;

			for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
				List<String> values = headerEntry.getValue();
				for (String value : values) {
					headerSizeInBytes += Long.valueOf(value.getBytes().length);
				}
			}

			if (headerSizeInBytes > config.getMaxSize().toBytes()) {
				exchange.getResponse()
						.setStatusCode(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE);
				exchange.getResponse().getHeaders().add("errorMessage",
						getErrorMessage(headerSizeInBytes, config.getMaxSize()));
				return exchange.getResponse().setComplete();

			}

			return chain.filter(exchange);
		}

		@Override
		public String toString() {
			return filterToStringCreator(RequestHeaderSizeGatewayFilterFactory.this)
					.append("max", config.getMaxSize()).toString();
		}
	};
}
 
Example #15
Source File: SecurityContextRepository.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<SecurityContext> load(ServerWebExchange serverWebExchange) {
    ServerHttpRequest request = serverWebExchange.getRequest();
    String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (StringUtils.isNotBlank(authHeader) && StringUtils.startsWith(authHeader, FebsConstant.OAUTH2_TOKEN_TYPE)) {
        String authToken = StringUtils.substringAfter(authHeader, FebsConstant.OAUTH2_TOKEN_TYPE).trim();
        Authentication auth = new UsernamePasswordAuthenticationToken(authToken, authToken);
        return this.authenticationManager.authenticate(auth).map(SecurityContextImpl::new);
    } else {
        return Mono.empty();
    }
}
 
Example #16
Source File: ServerWebExchangeArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	return checkParameterTypeNoReactiveWrapper(parameter,
			type -> ServerWebExchange.class.isAssignableFrom(type) ||
					ServerHttpRequest.class.isAssignableFrom(type) ||
					ServerHttpResponse.class.isAssignableFrom(type) ||
					HttpMethod.class == type ||
					Locale.class == type ||
					TimeZone.class == type ||
					ZoneId.class == type ||
					UriBuilder.class == type || UriComponentsBuilder.class == type);
}
 
Example #17
Source File: BodyExtractors.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Extractor to read multipart data into {@code Flux<Part>}.
 * @return {@code BodyExtractor} for multipart request parts
 */
// Parameterized for server-side use
public static BodyExtractor<Flux<Part>, ServerHttpRequest> toParts() {
	return (serverRequest, context) -> {
		ResolvableType elementType = PART_TYPE;
		MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
		HttpMessageReader<Part> reader = findReader(elementType, mediaType, context);
		return readToFlux(serverRequest, context, elementType, reader);
	};
}
 
Example #18
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@GetMapping(path = RESPONSE_STATUS_EX_FOR_SPECIFIC_STATUS_CODE_ENDPOINT)
@ResponseBody
public String responseStatusExForSpecificStatusCodeEndpoint(ServerHttpRequest request) {
    int desiredStatusCode = Integer.parseInt(
        request.getHeaders().getFirst("desired-status-code")
    );
    throw new ResponseStatusException(
        HttpStatus.resolve(desiredStatusCode),
        "Synthetic ResponseStatusException with specific desired status code: " + desiredStatusCode
    );
}
 
Example #19
Source File: IndexRewriteFilter.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
    ServerHttpRequest request = serverWebExchange.getRequest();
    if (request.getURI()
        .getPath()
        .equals("/")) {
        return webFilterChain.filter(serverWebExchange.mutate()
            .request(builder -> builder.method(request.getMethod())
                .contextPath(request.getPath()
                    .toString())
                .path("/test"))
            .build());
    }
    return webFilterChain.filter(serverWebExchange);
}
 
Example #20
Source File: EncoderHttpMessageWriter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType actualType,
		ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request,
		ServerHttpResponse response, Map<String, Object> hints) {

	Map<String, Object> allHints = Hints.merge(hints,
			getWriteHints(actualType, elementType, mediaType, request, response));

	return write(inputStream, elementType, mediaType, response, allHints);
}
 
Example #21
Source File: HttpHandlerConnector.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ServerHttpRequest adaptRequest(MockClientHttpRequest request, Publisher<DataBuffer> body) {
	HttpMethod method = request.getMethod();
	URI uri = request.getURI();
	HttpHeaders headers = request.getHeaders();
	MultiValueMap<String, HttpCookie> cookies = request.getCookies();
	return MockServerHttpRequest.method(method, uri).headers(headers).cookies(cookies).body(body);
}
 
Example #22
Source File: DefaultServerRequestBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public DelegatingServerWebExchange(
		ServerHttpRequest request, ServerWebExchange delegate, List<HttpMessageReader<?>> messageReaders) {

	this.request = request;
	this.delegate = delegate;
	this.formDataMono = initFormData(request, messageReaders);
	this.multipartDataMono = initMultipartData(request, messageReaders);
}
 
Example #23
Source File: ResourceUrlProvider.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Get the public resource URL for the given URI string.
 * <p>The URI string is expected to be a path and if it contains a query or
 * fragment those will be preserved in the resulting public resource URL.
 * @param uriString the URI string to transform
 * @param exchange the current exchange
 * @return the resolved public resource URL path, or empty if unresolved
 */
public final Mono<String> getForUriString(String uriString, ServerWebExchange exchange) {
	ServerHttpRequest request = exchange.getRequest();
	int queryIndex = getQueryIndex(uriString);
	String lookupPath = uriString.substring(0, queryIndex);
	String query = uriString.substring(queryIndex);
	PathContainer parsedLookupPath = PathContainer.parsePath(lookupPath);

	return resolveResourceUrl(exchange, parsedLookupPath).map(resolvedPath ->
			request.getPath().contextPath().value() + resolvedPath + query);
}
 
Example #24
Source File: DecoderHttpMessageReader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<T> readMono(ResolvableType actualType, ResolvableType elementType,
		ServerHttpRequest request, ServerHttpResponse response, Map<String, Object> hints) {

	Map<String, Object> allHints = Hints.merge(hints,
			getReadHints(actualType, elementType, request, response));

	return readMono(elementType, request, allHints);
}
 
Example #25
Source File: ServerWebExchangeArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public void handle(
		ServerWebExchange exchange,
		ServerHttpRequest request,
		ServerHttpResponse response,
		WebSession session,
		HttpMethod httpMethod,
		Locale locale,
		TimeZone timeZone,
		ZoneId zoneId,
		UriComponentsBuilder uriComponentsBuilder,
		UriBuilder uriBuilder,
		String s,
		Mono<ServerWebExchange> monoExchange) {
}
 
Example #26
Source File: HandshakeWebSocketService.java    From java-technology-stack with MIT License 5 votes vote down vote up
private HandshakeInfo createHandshakeInfo(ServerWebExchange exchange, ServerHttpRequest request,
		@Nullable String protocol, Map<String, Object> attributes) {

	URI uri = request.getURI();
	// Copy request headers, as they might be pooled and recycled by
	// the server implementation once the handshake HTTP exchange is done.
	HttpHeaders headers = new HttpHeaders();
	headers.addAll(request.getHeaders());
	Mono<Principal> principal = exchange.getPrincipal();
	String logPrefix = exchange.getLogPrefix();
	InetSocketAddress remoteAddress = request.getRemoteAddress();
	return new HandshakeInfo(uri, headers, principal, protocol, remoteAddress, attributes, logPrefix);
}
 
Example #27
Source File: CorsConfig.java    From black-shop with Apache License 2.0 5 votes vote down vote up
@Bean
public WebFilter corsFilter() {
	return (ServerWebExchange ctx, WebFilterChain chain) -> {
		ServerHttpRequest request = ctx.getRequest();
		if (CorsUtils.isCorsRequest(request)) {
			HttpHeaders requestHeaders = request.getHeaders();
			ServerHttpResponse response = ctx.getResponse();
			HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
			HttpHeaders headers = response.getHeaders();
			headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
			headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,
					requestHeaders.getAccessControlRequestHeaders());
			if (requestMethod != null) {
				headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
			}
			headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
			headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
			headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
			if (request.getMethod() == HttpMethod.OPTIONS) {
				response.setStatusCode(HttpStatus.OK);
				return Mono.empty();
			}

		}
		return chain.filter(ctx);
	};
}
 
Example #28
Source File: FebsUtil.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 获取请求IP
 *
 * @param request ServerHttpRequest
 * @return String IP
 */
public static String getServerHttpRequestIpAddress(ServerHttpRequest request) {
    HttpHeaders headers = request.getHeaders();
    String ip = headers.getFirst("x-forwarded-for");
    if (ip != null && ip.length() != 0 && !UNKNOW.equalsIgnoreCase(ip)) {
        if (ip.contains(StringConstant.COMMA)) {
            ip = ip.split(StringConstant.COMMA)[0];
        }
    }
    if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
        ip = headers.getFirst("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
        ip = headers.getFirst("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
        ip = headers.getFirst("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
        ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
        ip = headers.getFirst("X-Real-IP");
    }
    if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
        ip = Objects.requireNonNull(request.getRemoteAddress()).getAddress().getHostAddress();
    }
    return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
 
Example #29
Source File: DefaultClientRequestBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> writeTo(ClientHttpRequest request, ExchangeStrategies strategies) {
	HttpHeaders requestHeaders = request.getHeaders();
	if (!this.headers.isEmpty()) {
		this.headers.entrySet().stream()
				.filter(entry -> !requestHeaders.containsKey(entry.getKey()))
				.forEach(entry -> requestHeaders
						.put(entry.getKey(), entry.getValue()));
	}

	MultiValueMap<String, HttpCookie> requestCookies = request.getCookies();
	if (!this.cookies.isEmpty()) {
		this.cookies.forEach((name, values) -> values.forEach(value -> {
			HttpCookie cookie = new HttpCookie(name, value);
			requestCookies.add(name, cookie);
		}));
	}

	return this.body.insert(request, new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return strategies.messageWriters();
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.empty();
		}
		@Override
		public Map<String, Object> hints() {
			return Hints.from(Hints.LOG_PREFIX_HINT, logPrefix());
		}
	});
}
 
Example #30
Source File: BodyInsertersTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void createContext() {
	final List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
	messageWriters.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
	messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()));
	messageWriters.add(new ResourceHttpMessageWriter());
	messageWriters.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
	Jackson2JsonEncoder jsonEncoder = new Jackson2JsonEncoder();
	messageWriters.add(new EncoderHttpMessageWriter<>(jsonEncoder));
	messageWriters.add(new ServerSentEventHttpMessageWriter(jsonEncoder));
	messageWriters.add(new FormHttpMessageWriter());
	messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
	messageWriters.add(new MultipartHttpMessageWriter(messageWriters));

	this.context = new BodyInserter.Context() {
		@Override
		public List<HttpMessageWriter<?>> messageWriters() {
			return messageWriters;
		}
		@Override
		public Optional<ServerHttpRequest> serverRequest() {
			return Optional.empty();
		}
		@Override
		public Map<String, Object> hints() {
			return hints;
		}
	};
	this.hints = new HashMap<>();
}