001/*
002 * Copyright 2002-2018 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.function.server.support;
018
019import java.lang.reflect.Method;
020
021import reactor.core.publisher.Mono;
022
023import org.springframework.core.MethodParameter;
024import org.springframework.web.reactive.HandlerAdapter;
025import org.springframework.web.reactive.HandlerResult;
026import org.springframework.web.reactive.function.server.HandlerFunction;
027import org.springframework.web.reactive.function.server.RouterFunctions;
028import org.springframework.web.reactive.function.server.ServerRequest;
029import org.springframework.web.server.ServerWebExchange;
030
031/**
032 * {@code HandlerAdapter} implementation that supports {@link HandlerFunction HandlerFunctions}.
033 *
034 * @author Arjen Poutsma
035 * @since 5.0
036 */
037public class HandlerFunctionAdapter implements HandlerAdapter {
038
039        private static final MethodParameter HANDLER_FUNCTION_RETURN_TYPE;
040
041        static {
042                try {
043                        Method method = HandlerFunction.class.getMethod("handle", ServerRequest.class);
044                        HANDLER_FUNCTION_RETURN_TYPE = new MethodParameter(method, -1);
045                }
046                catch (NoSuchMethodException ex) {
047                        throw new IllegalStateException(ex);
048                }
049        }
050
051
052        @Override
053        public boolean supports(Object handler) {
054                return handler instanceof HandlerFunction;
055        }
056
057        @Override
058        public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
059                HandlerFunction<?> handlerFunction = (HandlerFunction<?>) handler;
060                ServerRequest request = exchange.getRequiredAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
061                return handlerFunction.handle(request)
062                                .map(response -> new HandlerResult(handlerFunction, response, HANDLER_FUNCTION_RETURN_TYPE));
063        }
064}