View Javadoc
1   /*
2    * Copyright 2022 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.apiclient.webflux.contract;
18  
19  import static java.util.Objects.nonNull;
20  import static org.springframework.core.GenericTypeResolver.resolveReturnTypeArgument;
21  
22  import java.lang.reflect.Method;
23  import java.util.function.BiFunction;
24  import org.bremersee.apiclient.webflux.Invocation;
25  import org.reactivestreams.Publisher;
26  import org.springframework.web.reactive.function.client.WebClient.ResponseSpec;
27  import reactor.core.publisher.Flux;
28  import reactor.core.publisher.Mono;
29  
30  /**
31   * The response function.
32   *
33   * @author Christian Bremer
34   */
35  public class ResponseFunction implements BiFunction<Invocation, ResponseSpec, Publisher<?>> {
36  
37    @Override
38    public Publisher<?> apply(Invocation invocation, ResponseSpec responseSpec) {
39  
40      Method method = invocation.getMethod();
41      Class<?> responseClass = method.getReturnType();
42      if (Mono.class.isAssignableFrom(responseClass)) {
43        Class<?> typeClass = resolveReturnTypeArgument(method, responseClass);
44        return nonNull(typeClass)
45            ? responseSpec.bodyToMono(typeClass)
46            : responseSpec.bodyToMono(responseClass);
47      }
48      if (Flux.class.isAssignableFrom(responseClass)) {
49        Class<?> typeClass = resolveReturnTypeArgument(method, responseClass);
50        return nonNull(typeClass)
51            ? responseSpec.bodyToFlux(typeClass)
52            : responseSpec.bodyToFlux(responseClass);
53      }
54      if (Publisher.class.isAssignableFrom(responseClass)) {
55        Class<?> typeClass = resolveReturnTypeArgument(method, responseClass);
56        return nonNull(typeClass)
57            ? responseSpec.bodyToFlux(typeClass)
58            : responseSpec.bodyToFlux(responseClass);
59      }
60      throw new IllegalStateException(
61          "Response class must be Mono, Flux or Publisher.");
62    }
63  }