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