001/* 002 * Copyright 2002-2019 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.reactive.result.method.annotation; 018 019import java.util.List; 020 021import reactor.core.publisher.Mono; 022 023import org.springframework.core.MethodParameter; 024import org.springframework.core.ReactiveAdapterRegistry; 025import org.springframework.http.HttpEntity; 026import org.springframework.http.RequestEntity; 027import org.springframework.http.codec.HttpMessageReader; 028import org.springframework.http.server.reactive.ServerHttpRequest; 029import org.springframework.lang.Nullable; 030import org.springframework.web.reactive.BindingContext; 031import org.springframework.web.server.ServerWebExchange; 032 033/** 034 * Resolves method arguments of type {@link HttpEntity} or {@link RequestEntity} 035 * by reading the body of the request through a compatible 036 * {@code HttpMessageReader}. 037 * 038 * @author Rossen Stoyanchev 039 * @since 5.2 040 */ 041public class HttpEntityMethodArgumentResolver extends AbstractMessageReaderArgumentResolver { 042 043 public HttpEntityMethodArgumentResolver(List<HttpMessageReader<?>> readers, ReactiveAdapterRegistry registry) { 044 super(readers, registry); 045 } 046 047 048 @Override 049 public boolean supportsParameter(MethodParameter parameter) { 050 return checkParameterTypeNoReactiveWrapper(parameter, 051 type -> HttpEntity.class.equals(type) || RequestEntity.class.equals(type)); 052 } 053 054 @Override 055 public Mono<Object> resolveArgument( 056 MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) { 057 058 Class<?> entityType = parameter.getParameterType(); 059 return readBody(parameter.nested(), parameter, false, bindingContext, exchange) 060 .map(body -> createEntity(body, entityType, exchange.getRequest())) 061 .defaultIfEmpty(createEntity(null, entityType, exchange.getRequest())); 062 } 063 064 private Object createEntity(@Nullable Object body, Class<?> entityType, ServerHttpRequest request) { 065 return (RequestEntity.class.equals(entityType) ? 066 new RequestEntity<>(body, request.getHeaders(), request.getMethod(), request.getURI()) : 067 new HttpEntity<>(body, request.getHeaders())); 068 } 069 070}