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