Search in sources :

Example 1 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project spring-boot-admin by codecentric.

the class PrefixHandlerMappingTest method withoutPrefix.

@Test
public void withoutPrefix() throws Exception {
    TestController controller = new TestController();
    PrefixHandlerMapping mapping = new PrefixHandlerMapping(controller);
    mapping.setApplicationContext(this.context);
    mapping.afterPropertiesSet();
    assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/test")).getHandler(), equalTo((Object) new HandlerMethod(controller, this.method)));
    assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/noop")), nullValue());
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) Test(org.junit.Test)

Example 2 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project spring-framework by spring-projects.

the class RequestMappingHandlerAdapter method getExceptionHandlerMethod.

private InvocableHandlerMethod getExceptionHandlerMethod(Throwable ex, HandlerMethod handlerMethod) {
    Class<?> handlerType = handlerMethod.getBeanType();
    ExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.computeIfAbsent(handlerType, ExceptionHandlerMethodResolver::new);
    return Optional.ofNullable(resolver.resolveMethodByThrowable(ex)).map(method -> createHandlerMethod(handlerMethod.getBean(), method)).orElseGet(() -> this.exceptionHandlerAdviceCache.entrySet().stream().map(entry -> {
        if (entry.getKey().isApplicableToBeanType(handlerType)) {
            Method method = entry.getValue().resolveMethodByThrowable(ex);
            if (method != null) {
                Object bean = entry.getKey().resolveBean();
                return createHandlerMethod(bean, method);
            }
        }
        return null;
    }).filter(Objects::nonNull).findFirst().orElse(null));
}
Also used : InvocableHandlerMethod(org.springframework.web.reactive.result.method.InvocableHandlerMethod) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) BindingContext(org.springframework.web.reactive.BindingContext) MethodIntrospector.selectMethods(org.springframework.core.MethodIntrospector.selectMethods) Function(java.util.function.Function) HandlerMethodArgumentResolver(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver) InitializingBean(org.springframework.beans.factory.InitializingBean) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) LinkedHashMap(java.util.LinkedHashMap) HandlerMethod(org.springframework.web.method.HandlerMethod) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) ExceptionHandlerMethodResolver(org.springframework.web.method.annotation.ExceptionHandlerMethodResolver) Map(java.util.Map) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) DataBufferDecoder(org.springframework.core.codec.DataBufferDecoder) Method(java.lang.reflect.Method) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) HandlerAdapter(org.springframework.web.reactive.HandlerAdapter) WebBindingInitializer(org.springframework.web.bind.support.WebBindingInitializer) StringDecoder(org.springframework.core.codec.StringDecoder) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) SyncHandlerMethodArgumentResolver(org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver) Mono(reactor.core.publisher.Mono) ByteBufferDecoder(org.springframework.core.codec.ByteBufferDecoder) ApplicationContext(org.springframework.context.ApplicationContext) ByteArrayDecoder(org.springframework.core.codec.ByteArrayDecoder) HandlerResult(org.springframework.web.reactive.HandlerResult) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) Objects(java.util.Objects) List(java.util.List) ReflectionUtils(org.springframework.util.ReflectionUtils) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) ControllerAdviceBean(org.springframework.web.method.ControllerAdviceBean) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) InitBinder(org.springframework.web.bind.annotation.InitBinder) SyncInvocableHandlerMethod(org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod) ApplicationContextAware(org.springframework.context.ApplicationContextAware) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator) Assert(org.springframework.util.Assert) ExceptionHandlerMethodResolver(org.springframework.web.method.annotation.ExceptionHandlerMethodResolver) InvocableHandlerMethod(org.springframework.web.reactive.result.method.InvocableHandlerMethod) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) SyncInvocableHandlerMethod(org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod)

Example 3 with HandlerMethod

use of org.springframework.web.method.HandlerMethod 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, String lookupPath, 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<String> methods = helper.getAllowedMethods();
        if (HttpMethod.OPTIONS.matches(httpMethod.name())) {
            HttpOptionsHandler handler = new HttpOptionsHandler(methods);
            return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
        }
        throw new MethodNotAllowedException(httpMethod.name(), 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));
    }
    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;
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) ServerWebInputException(org.springframework.web.server.ServerWebInputException) MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 4 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project spring-framework by spring-projects.

the class AbstractHandlerMethodMapping method getHandlerInternal.

// Handler method lookup
/**
	 * Look up a handler method for the given request.
	 * @param exchange the current exchange
	 */
@Override
public Mono<HandlerMethod> getHandlerInternal(ServerWebExchange exchange) {
    String lookupPath = getPathHelper().getLookupPathForRequest(exchange);
    if (logger.isDebugEnabled()) {
        logger.debug("Looking up handler method for path " + lookupPath);
    }
    this.mappingRegistry.acquireReadLock();
    try {
        // Ensure form data is parsed for "params" conditions...
        return exchange.getRequestParams().then(() -> {
            HandlerMethod handlerMethod = null;
            try {
                handlerMethod = lookupHandlerMethod(lookupPath, exchange);
            } catch (Exception ex) {
                return Mono.error(ex);
            }
            if (logger.isDebugEnabled()) {
                if (handlerMethod != null) {
                    logger.debug("Returning handler method [" + handlerMethod + "]");
                } else {
                    logger.debug("Did not find handler method for [" + lookupPath + "]");
                }
            }
            if (handlerMethod != null) {
                handlerMethod = handlerMethod.createWithResolvedBean();
            }
            return Mono.justOrEmpty(handlerMethod);
        });
    } finally {
        this.mappingRegistry.releaseReadLock();
    }
}
Also used : HandlerMethod(org.springframework.web.method.HandlerMethod)

Example 5 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project spring-framework by spring-projects.

the class AbstractHandlerMethodMapping method getCorsConfiguration.

@Override
protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) {
    CorsConfiguration corsConfig = super.getCorsConfiguration(handler, exchange);
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.equals(PREFLIGHT_AMBIGUOUS_MATCH)) {
            return ALLOW_CORS_CONFIG;
        }
        CorsConfiguration methodConfig = this.mappingRegistry.getCorsConfiguration(handlerMethod);
        corsConfig = (corsConfig != null ? corsConfig.combine(methodConfig) : methodConfig);
    }
    return corsConfig;
}
Also used : CorsConfiguration(org.springframework.web.cors.CorsConfiguration) HandlerMethod(org.springframework.web.method.HandlerMethod)

Aggregations

HandlerMethod (org.springframework.web.method.HandlerMethod)235 Test (org.junit.jupiter.api.Test)86 Method (java.lang.reflect.Method)68 ModelAndView (org.springframework.web.servlet.ModelAndView)44 InvocableHandlerMethod (org.springframework.web.method.support.InvocableHandlerMethod)42 ArrayList (java.util.ArrayList)28 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)26 MethodParameter (org.springframework.core.MethodParameter)25 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)25 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)24 Test (org.junit.Test)20 ByteArrayHttpMessageConverter (org.springframework.http.converter.ByteArrayHttpMessageConverter)19 ResourceHttpMessageConverter (org.springframework.http.converter.ResourceHttpMessageConverter)17 AllEncompassingFormHttpMessageConverter (org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter)17 MappingJackson2XmlHttpMessageConverter (org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter)17 IOException (java.io.IOException)14 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)14 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)14 Map (java.util.Map)13 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)12