use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.
the class ForwardedHeaderTransformerTests method forwardedHeader.
@Test
void forwardedHeader() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("Forwarded", "host=84.198.58.199;proto=https");
ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/path"));
assertForwardedHeadersRemoved(request);
}
use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.
the class ForwardedHeaderTransformerTests method xForwardedFor.
@Test
public void xForwardedFor() throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
headers.add("x-forwarded-for", "203.0.113.195, 70.41.3.18, 150.172.238.178");
ServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb")).headers(headers).build();
request = this.requestMutator.apply(request);
assertThat(request.getRemoteAddress()).isNotNull();
assertThat(request.getRemoteAddress().getHostName()).isEqualTo("203.0.113.195");
}
use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.
the class ForwardedHeaderTransformer method apply.
/**
* Apply and remove, or remove Forwarded type headers.
* @param request the request
*/
@Override
public ServerHttpRequest apply(ServerHttpRequest request) {
if (hasForwardedHeaders(request)) {
ServerHttpRequest.Builder builder = request.mutate();
if (!this.removeOnly) {
URI uri = UriComponentsBuilder.fromHttpRequest(request).build(true).toUri();
builder.uri(uri);
String prefix = getForwardedPrefix(request);
if (prefix != null) {
builder.path(prefix + uri.getRawPath());
builder.contextPath(prefix);
}
InetSocketAddress remoteAddress = request.getRemoteAddress();
remoteAddress = UriComponentsBuilder.parseForwardedFor(request, remoteAddress);
if (remoteAddress != null) {
builder.remoteAddress(remoteAddress);
}
}
removeForwardedHeaders(builder);
request = builder.build();
}
return request;
}
use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.
the class AbstractMessageReaderArgumentResolver method readBody.
/**
* Read the body from a method argument with {@link HttpMessageReader}.
* @param bodyParam represents the element type for the body
* @param actualParam the actual method argument type; possibly different
* from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
* @param isBodyRequired true if the body is required
* @param bindingContext the binding context to use
* @param exchange the current exchange
* @return a Mono with the value to use for the method argument
* @since 5.0.2
*/
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam, boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {
ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
Class<?> resolvedType = bodyType.resolve();
ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
MediaType contentType = request.getHeaders().getContentType();
MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
Object[] hints = extractValidationHints(bodyParam);
if (mediaType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
if (logger.isDebugEnabled()) {
logger.debug("Form data is accessed via ServerWebExchange.getFormData() in WebFlux.");
}
return Mono.error(new ResponseStatusException(HttpStatus.UNSUPPORTED_MEDIA_TYPE));
}
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + (contentType != null ? "Content-Type:" + contentType : "No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
}
for (HttpMessageReader<?> reader : getMessageReaders()) {
if (reader.canRead(elementType, mediaType)) {
Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
if (adapter != null && adapter.isMultiValue()) {
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
}
Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
if (isBodyRequired) {
flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
}
if (hints != null) {
flux = flux.doOnNext(target -> validate(target, hints, bodyParam, bindingContext, exchange));
}
return Mono.just(adapter.fromPublisher(flux));
} else {
// Single-value (with or without reactive type wrapper)
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
}
Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
if (isBodyRequired) {
mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
}
if (hints != null) {
mono = mono.doOnNext(target -> validate(target, hints, bodyParam, bindingContext, exchange));
}
return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
}
}
}
// No compatible reader but body may be empty..
HttpMethod method = request.getMethod();
if (contentType == null && SUPPORTED_METHODS.contains(method)) {
Flux<DataBuffer> body = request.getBody().doOnNext(buffer -> {
DataBufferUtils.release(buffer);
// Body not empty, back toy 415..
throw new UnsupportedMediaTypeStatusException(mediaType, getSupportedMediaTypes(elementType), elementType);
});
if (isBodyRequired) {
body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
}
return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
}
return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, getSupportedMediaTypes(elementType), elementType));
}
use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.
the class RequestMappingInfoHandlerMapping method handleNoMatch.
/**
* Iterate all RequestMappingInfos once again, look if any match by URL at
* least and raise exceptions accordingly.
* @throws MethodNotAllowedException for matches by URL but not by HTTP method
* @throws UnsupportedMediaTypeStatusException if there are matches by URL
* and HTTP method but not by consumable media types
* @throws NotAcceptableStatusException if there are matches by URL and HTTP
* method but not by producible media types
* @throws ServerWebInputException if there are matches by URL and HTTP
* method but not by query parameter conditions
*/
@Override
protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> infos, ServerWebExchange exchange) throws Exception {
PartialMatchHelper helper = new PartialMatchHelper(infos, exchange);
if (helper.isEmpty()) {
return null;
}
ServerHttpRequest request = exchange.getRequest();
if (helper.hasMethodsMismatch()) {
HttpMethod httpMethod = request.getMethod();
Set<HttpMethod> methods = helper.getAllowedMethods();
if (HttpMethod.OPTIONS.equals(httpMethod)) {
Set<MediaType> mediaTypes = helper.getConsumablePatchMediaTypes();
HttpOptionsHandler handler = new HttpOptionsHandler(methods, mediaTypes);
return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
}
throw new MethodNotAllowedException(httpMethod, methods);
}
if (helper.hasConsumesMismatch()) {
Set<MediaType> mediaTypes = helper.getConsumableMediaTypes();
MediaType contentType;
try {
contentType = request.getHeaders().getContentType();
} catch (InvalidMediaTypeException ex) {
throw new UnsupportedMediaTypeStatusException(ex.getMessage());
}
throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(mediaTypes), exchange.getRequest().getMethod());
}
if (helper.hasProducesMismatch()) {
Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
throw new NotAcceptableStatusException(new ArrayList<>(mediaTypes));
}
if (helper.hasParamsMismatch()) {
throw new ServerWebInputException("Unsatisfied query parameter conditions: " + helper.getParamConditions() + ", actual parameters: " + request.getQueryParams());
}
return null;
}
Aggregations