Fix Sonar complains
[oam/nf-oam-adopter.git] / ves-nf-oam-adopter / ves-nf-oam-adopter-pm-sb-rest-client / src / main / java / org / o / ran / oam / nf / oam / adopter / pm / sb / rest / client / DefaultHttpRestClient.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  O-RAN-SC
4  *  ================================================================================
5  *  Copyright © 2021 AT&T Intellectual Property. 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  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.o.ran.oam.nf.oam.adopter.pm.sb.rest.client;
21
22 import static org.o.ran.oam.nf.oam.adopter.pm.sb.rest.client.http.DownloadPerformanceManagementFilesHandler.readPerformanceManagementFiles;
23 import static org.o.ran.oam.nf.oam.adopter.pm.sb.rest.client.http.OffSetTimeZoneHandler.readTimeZone;
24 import static org.o.ran.oam.nf.oam.adopter.pm.sb.rest.client.http.TokenHandler.returnToken;
25 import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;
26
27 import com.google.common.cache.CacheBuilder;
28 import com.google.common.cache.CacheLoader;
29 import com.google.common.cache.LoadingCache;
30 import io.reactivex.rxjava3.core.Single;
31 import java.time.Instant;
32 import java.time.ZoneId;
33 import java.time.format.DateTimeFormatter;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.zip.ZipInputStream;
37 import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
38 import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
39 import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
40 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
41 import org.apache.hc.core5.http.ConnectionClosedException;
42 import org.apache.hc.core5.http.HttpHeaders;
43 import org.checkerframework.checker.lock.qual.GuardedBy;
44 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.api.HttpRestClient;
45 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.exceptions.PerformanceManagementException;
46 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.exceptions.TokenGenerationException;
47 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.exceptions.ZoneIdException;
48 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.pojos.Adapter;
49 import org.o.ran.oam.nf.oam.adopter.pm.sb.rest.client.properties.PmEndpointsUrlsProperties;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.stereotype.Service;
54
55 @Service
56 public final class DefaultHttpRestClient implements HttpRestClient {
57     private static final Logger LOG = LoggerFactory.getLogger(DefaultHttpRestClient.class);
58
59     public static final String HTTPS = "https://";
60     public static final String BEARER = "Bearer ";
61     private static final DateTimeFormatter OFFSET_FORMATTER = DateTimeFormatter.ofPattern("xxx");
62     private final CloseableHttpAsyncClient client;
63     @GuardedBy("this")
64     private final LoadingCache<Adapter, String> sessionCache =
65             CacheBuilder.newBuilder().refreshAfterWrite(59, TimeUnit.MINUTES).build(new CacheLoader<>() {
66                 @Override
67                 public String load(final Adapter adapter) throws ExecutionException, InterruptedException {
68                     return returnToken(DefaultHttpRestClient.this.client, DefaultHttpRestClient.this.tokenEndpoint,
69                             adapter);
70                 }
71             });
72
73     @GuardedBy("this")
74     private final LoadingCache<Adapter, ZoneId> zoneIdCache =
75             CacheBuilder.newBuilder().build(new CacheLoader<>() {
76                 @Override
77                 public ZoneId load(final Adapter adapter) {
78                     return readTimeZone(DefaultHttpRestClient.this, timeZoneEndpoint,  adapter)
79                                    .doOnError(error -> LOG.error("Failed to read time zone", error))
80                                    .blockingGet();
81                 }
82             });
83     private final String pmFilesEndpoint;
84     private final String timeZoneEndpoint;
85     private final String tokenEndpoint;
86
87     /**
88      * Default constructor.
89      */
90     @Autowired
91     public DefaultHttpRestClient(final CloseableHttpAsyncClient httpAsyncClient,
92             final PmEndpointsUrlsProperties properties) {
93         this.client = httpAsyncClient;
94         this.pmFilesEndpoint = properties.getRanPmEndpoint();
95         this.timeZoneEndpoint = properties.getRanTimeZoneOffsetEndpoint();
96         this.tokenEndpoint = properties.getRanTokenEndpoint();
97     }
98
99
100     @Override
101     public synchronized Single<ZipInputStream> readFiles(final Adapter adapter) {
102         return readPerformanceManagementFiles(this, pmFilesEndpoint, adapter);
103     }
104
105     @Override
106     public Single<ZoneId> getTimeZone(final Adapter adapter) {
107         try {
108             final ZoneId zoneId = zoneIdCache.get(adapter);
109             final String offset = OFFSET_FORMATTER.format(zoneId.getRules().getOffset(Instant.now()));
110             LOG.info("Adapter {} has offset {}", adapter.getHostIpAddress(), offset);
111             return Single.just(zoneId);
112         } catch (final Exception e) {
113             final Throwable cause = e.getCause();
114             if (cause instanceof PerformanceManagementException) {
115                 return Single.error(cause);
116             }
117             return Single.error(new ZoneIdException("Failed to get Zone ID for " + adapter.getHostIpAddress(), cause));
118         }
119     }
120
121     /**
122      * Execute GET request on adapter endpoint.
123      * @param adapter destiny
124      * @param url endpoint
125      * @return response
126      */
127     public Single<SimpleHttpResponse> get(final Adapter adapter, final String url) {
128         return getToken(adapter).flatMap(token -> {
129             final SimpleHttpRequest request =
130                 SimpleHttpRequests.get(HTTPS + adapter.getHostIpAddress() + url);
131             request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE);
132             request.addHeader(HttpHeaders.AUTHORIZATION, BEARER + token);
133             return Single.fromFuture(client.execute(request, null))
134                     .doOnSubscribe(result -> LOG.trace("GET Request started {} ...", request))
135                     .doOnSuccess(result -> LOG.trace("GET Request finished {}", request));
136         });
137     }
138
139     private Single<String> getToken(final Adapter adapter) {
140         try {
141             final String token = sessionCache.get(adapter);
142             return Single.just(token);
143         } catch (final Exception e) {
144             if (e.getCause() instanceof TokenGenerationException || e.getCause() instanceof ConnectionClosedException) {
145                 return Single.error(e.getCause());
146             }
147             return Single.error(e);
148         }
149     }
150 }