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.ResolvableType;
24  import org.springframework.core.io.buffer.DataBuffer;
25  import org.springframework.web.reactive.function.BodyInserters;
26  import org.springframework.web.reactive.function.client.WebClient.RequestBodyUriSpec;
27  import org.springframework.web.reactive.function.client.WebClient.RequestHeadersUriSpec;
28  
29  /**
30   * The data buffers inserter.
31   *
32   * @author Christian Bremer
33   */
34  public class DataBuffersInserter extends SingleBodyInserter<Publisher<DataBuffer>> {
35  
36    @Override
37    protected boolean isPossibleBodyValue(InvocationParameter invocationParameter) {
38      return invocationParameter.getValue() instanceof Publisher
39          && isDataBuffer(invocationParameter);
40    }
41  
42    private boolean isDataBuffer(InvocationParameter invocationParameter) {
43      Method method = invocationParameter.getMethod();
44      int index = invocationParameter.getIndex();
45      return Optional.of(ResolvableType.forMethodParameter(method, index))
46          .filter(ResolvableType::hasGenerics)
47          .map(resolvableType -> resolvableType.resolveGeneric(0))
48          .filter(DataBuffer.class::isAssignableFrom)
49          .isPresent();
50    }
51  
52    @Override
53    protected Publisher<DataBuffer> mapBody(InvocationParameter invocationParameter) {
54      //noinspection unchecked
55      return (Publisher<DataBuffer>) invocationParameter.getValue();
56    }
57  
58    @Override
59    protected RequestHeadersUriSpec<?> insert(
60        Publisher<DataBuffer> body,
61        RequestBodyUriSpec requestBodyUriSpec) {
62  
63      //noinspection rawtypes
64      return (RequestHeadersUriSpec) requestBodyUriSpec.body(BodyInserters.fromDataBuffers(body));
65    }
66  
67  }