f384c1c1ba617496d0540527851ffd315101a990
[dcaegen2/services/sdk.git] /
1 /*
2  * ============LICENSE_START====================================
3  * DCAEGEN2-SERVICES-SDK
4  * =========================================================
5  * Copyright (C) 2019 Nokia. All rights reserved.
6  * =========================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=====================================
19  */
20 package org.onap.dcaegen2.services.sdk.rest.services.adapters.http;
21
22 import io.netty.handler.ssl.SslContext;
23 import io.vavr.collection.Stream;
24 import java.util.stream.Collectors;
25 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import reactor.core.publisher.Mono;
29 import reactor.netty.http.client.HttpClient;
30 import reactor.netty.http.client.HttpClient.ResponseReceiver;
31 import reactor.netty.http.client.HttpClientRequest;
32 import reactor.netty.http.client.HttpClientResponse;
33
34 /**
35  * @since 1.1.4
36  */
37 public class RxHttpClient {
38
39     private static final Logger LOGGER = LoggerFactory.getLogger(RxHttpClient.class);
40     private final HttpClient httpClient;
41
42     public static RxHttpClient create() {
43         return new RxHttpClient(HttpClient.create());
44     }
45
46     // TODO: hide netty from public api (io.netty.handler.ssl.SslContext)
47     public static RxHttpClient create(SslContext sslContext) {
48         return new RxHttpClient(HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)));
49     }
50
51     RxHttpClient(HttpClient httpClient) {
52         this.httpClient = httpClient;
53     }
54
55     public Mono<HttpResponse> call(HttpRequest request) {
56         return prepareRequest(request)
57                 .responseSingle((resp, content) ->
58                         content.asByteArray()
59                                 .defaultIfEmpty(new byte[0])
60                                 .map(bytes -> new NettyHttpResponse(request.url(), resp.status(), bytes)));
61     }
62
63     ResponseReceiver<?> prepareRequest(HttpRequest request) {
64         return httpClient
65                 .doOnRequest((req, conn) -> logRequest(request.diagnosticContext(), req))
66                 .doOnResponse((rsp, conn) -> logResponse(request.diagnosticContext(), rsp))
67                 .headers(hdrs -> request.headers().forEach(hdr -> hdrs.set(hdr._1, hdr._2)))
68                 .request(request.method().asNetty())
69                 .send(request.body())
70                 .uri(request.url());
71
72     }
73
74     private void logRequest(RequestDiagnosticContext context, HttpClientRequest httpClientRequest) {
75         context.withSlf4jMdc(LOGGER.isDebugEnabled(), () -> {
76             LOGGER.debug("Request: {} {} {}", httpClientRequest.method(), httpClientRequest.uri(),
77                     httpClientRequest.requestHeaders());
78             if (LOGGER.isTraceEnabled()) {
79                 final String headers = Stream.ofAll(httpClientRequest.requestHeaders())
80                         .map(entry -> entry.getKey() + "=" + entry.getValue())
81                         .collect(Collectors.joining("\n"));
82                 LOGGER.trace(headers);
83             }
84         });
85     }
86
87     private void logResponse(RequestDiagnosticContext context, HttpClientResponse httpClientResponse) {
88         context.withSlf4jMdc(LOGGER.isDebugEnabled(),
89                 () -> LOGGER.debug("Response status: {}", httpClientResponse.status()));
90     }
91 }