13347e10947c7b2420c50576d891f36a8ea8244b
[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
21 package org.onap.dcaegen2.services.sdk.rest.services.cbs.client.impl.adapters;
22
23 import com.google.gson.Gson;
24 import io.netty.handler.codec.http.HttpStatusClass;
25 import io.vavr.collection.Stream;
26 import java.io.IOException;
27 import java.util.function.BiConsumer;
28 import java.util.stream.Collectors;
29 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import reactor.core.publisher.Mono;
33 import reactor.netty.Connection;
34 import reactor.netty.http.client.HttpClient;
35 import reactor.netty.http.client.HttpClientRequest;
36 import reactor.netty.http.client.HttpClientResponse;
37
38 /**
39  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 11/15/18
40  */
41
42 public class CloudHttpClient {
43
44     private static final Logger LOGGER = LoggerFactory.getLogger(CloudHttpClient.class);
45
46     private final Gson gson = new Gson();
47     private final HttpClient httpClient;
48
49     public CloudHttpClient() {
50         this(HttpClient.create());
51     }
52
53
54     CloudHttpClient(HttpClient httpClient) {
55         this.httpClient = httpClient;
56     }
57
58     public <T> Mono<T> get(String url, RequestDiagnosticContext context, Class<T> bodyClass) {
59         final HttpClient clientWithHeaders = httpClient
60                 .doOnRequest((req, conn) -> logRequest(context, req))
61                 .doOnResponse((rsp, conn) -> logResponse(context, rsp))
62                 .headers(hdrs -> context.remoteCallHttpHeaders().forEach((BiConsumer<String, String>) hdrs::set));
63         return callHttpGet(clientWithHeaders, url, bodyClass);
64     }
65
66     public <T> Mono<T> get(String url, Class<T> bodyClass) {
67         return callHttpGet(httpClient, url, bodyClass);
68     }
69
70     private <T> Mono<T> callHttpGet(HttpClient client, String url, Class<T> bodyClass) {
71         return client.get()
72                 .uri(url)
73                 .responseSingle((resp, content) -> HttpStatusClass.SUCCESS.contains(resp.status().code())
74                         ? content.asString()
75                         : Mono.error(createException(url, resp)))
76                 .map(body -> parseJson(body, bodyClass));
77     }
78
79     private Exception createException(String url, HttpClientResponse response) {
80         return new IOException(String.format("Request failed for URL '%s'. Response code: %s",
81                 url,
82                 response.status()));
83     }
84
85     private <T> T parseJson(String body, Class<T> bodyClass) {
86         return gson.fromJson(body, bodyClass);
87     }
88
89     private void logRequest(RequestDiagnosticContext context, HttpClientRequest httpClientRequest) {
90         context.withSlf4jMdc(LOGGER.isDebugEnabled(), () -> {
91             LOGGER.debug("Request: {} {}", httpClientRequest.method(), httpClientRequest.uri());
92             if (LOGGER.isTraceEnabled()) {
93                 final String headers = Stream.ofAll(httpClientRequest.requestHeaders())
94                         .map(entry -> entry.getKey() + "=" + entry.getValue())
95                         .collect(Collectors.joining("\n"));
96                 LOGGER.trace(headers);
97             }
98         });
99     }
100
101     private void logResponse(RequestDiagnosticContext context, HttpClientResponse httpClientResponse) {
102         context.withSlf4jMdc(LOGGER.isDebugEnabled(), () -> {
103             LOGGER.debug("Response status: {}", httpClientResponse.status());
104         });
105     }
106 }
107