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.spring;
18  
19  import java.lang.reflect.Method;
20  import java.util.Optional;
21  import org.bremersee.apiclient.webflux.InvocationParameter;
22  import org.reactivestreams.Publisher;
23  import org.springframework.core.ParameterizedTypeReference;
24  import org.springframework.core.ResolvableType;
25  import org.springframework.web.reactive.function.client.WebClient.RequestBodyUriSpec;
26  import org.springframework.web.reactive.function.client.WebClient.RequestHeadersUriSpec;
27  
28  /**
29   * The publisher inserter.
30   *
31   * @author Christian Bremer
32   */
33  public class PublisherInserter extends SingleBodyInserter<InvocationParameter> {
34  
35    @Override
36    protected boolean isPossibleBodyValue(InvocationParameter invocationParameter) {
37      return invocationParameter.getValue() instanceof Publisher;
38    }
39  
40    @Override
41    protected InvocationParameter mapBody(InvocationParameter invocationParameter) {
42      return invocationParameter;
43    }
44  
45    @Override
46    protected RequestHeadersUriSpec<?> insert(
47        InvocationParameter invocationParameter,
48        RequestBodyUriSpec requestBodyUriSpec) {
49  
50      Method method = invocationParameter.getMethod();
51      int index = invocationParameter.getIndex();
52      //noinspection rawtypes
53      return Optional.of(ResolvableType.forMethodParameter(method, index))
54          .filter(ResolvableType::hasGenerics)
55          .map(resolvableType -> resolvableType.resolveGeneric(0))
56          .map(ParameterizedTypeReference::forType)
57          .map(ref -> (RequestHeadersUriSpec) requestBodyUriSpec
58              .body(invocationParameter.getValue(), ref))
59          .orElse(requestBodyUriSpec);
60    }
61  
62  }