a99fedd55d780d9898f931439b7794cd47cb43a8
[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                     try {
69                         return returnToken(DefaultHttpRestClient.this.client, DefaultHttpRestClient.this.tokenEndpoint,
70                                 adapter);
71                     } catch (final Exception error) {
72                         LOG.error("Failed to read time zone", error);
73                         throw error;
74                     }
75                 }
76             });
77
78     @GuardedBy("this")
79     private final LoadingCache<Adapter, ZoneId> zoneIdCache =
80             CacheBuilder.newBuilder().build(new CacheLoader<>() {
81                 @Override
82                 public ZoneId load(final Adapter adapter) {
83                     return readTimeZone(DefaultHttpRestClient.this, timeZoneEndpoint,  adapter)
84                                    .doOnError(error -> LOG.error("Failed to read time zone", error))
85                                    .blockingGet();
86                 }
87             });
88     private final String pmFilesEndpoint;
89     private final String timeZoneEndpoint;
90     private final String tokenEndpoint;
91
92     /**
93      * Default constructor.
94      */
95     @Autowired
96     public DefaultHttpRestClient(final CloseableHttpAsyncClient httpAsyncClient,
97             final PmEndpointsUrlsProperties properties) {
98         this.client = httpAsyncClient;
99         this.pmFilesEndpoint = properties.getRanPmEndpoint();
100         this.timeZoneEndpoint = properties.getRanTimeZoneOffsetEndpoint();
101         this.tokenEndpoint = properties.getRanTokenEndpoint();
102     }
103
104
105     @Override
106     public synchronized Single<ZipInputStream> readFiles(final Adapter adapter) {
107         return readPerformanceManagementFiles(this, pmFilesEndpoint, adapter);
108     }
109
110     @Override
111     public Single<ZoneId> getTimeZone(final Adapter adapter) {
112         try {
113             final ZoneId zoneId = zoneIdCache.get(adapter);
114             final String offset = OFFSET_FORMATTER.format(zoneId.getRules().getOffset(Instant.now()));
115             LOG.info("Adapter {} has offset {}", adapter.getHostIpAddress(), offset);
116             return Single.just(zoneId);
117         } catch (final Exception e) {
118             final Throwable cause = e.getCause();
119             if (cause instanceof PerformanceManagementException) {
120                 return Single.error(cause);
121             }
122             return Single.error(new ZoneIdException("Failed to get Zone ID for " + adapter.getHostIpAddress(), cause));
123         }
124     }
125
126     /**
127      * Execute GET request on adapter endpoint.
128      * @param adapter destiny
129      * @param url endpoint
130      * @return response
131      */
132     public Single<SimpleHttpResponse> get(final Adapter adapter, final String url) {
133         return getToken(adapter).flatMap(token -> {
134             final SimpleHttpRequest request =
135                 SimpleHttpRequests.get(HTTPS + adapter.getHostIpAddress() + url);
136             request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE);
137             request.addHeader(HttpHeaders.AUTHORIZATION, BEARER + token);
138             return Single.fromFuture(client.execute(request, null))
139                     .doOnSubscribe(result -> LOG.trace("GET Request started {} ...", request))
140                     .doOnSuccess(result -> LOG.trace("GET Request finished {}", request));
141         });
142     }
143
144     private Single<String> getToken(final Adapter adapter) {
145         try {
146             final String token = sessionCache.get(adapter);
147             return Single.just(token);
148         } catch (final Exception e) {
149             if (e.getCause() instanceof TokenGenerationException || e.getCause() instanceof ConnectionClosedException) {
150                 return Single.error(e.getCause());
151             }
152             return Single.error(e);
153         }
154     }
155 }