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 / http / TokenHandler.java
1 package org.o.ran.oam.nf.oam.adopter.pm.sb.rest.client.http;
2
3 import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;
4
5 import com.google.gson.Gson;
6 import java.nio.charset.StandardCharsets;
7 import java.util.Base64;
8 import java.util.concurrent.ExecutionException;
9 import lombok.AccessLevel;
10 import lombok.NoArgsConstructor;
11 import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
12 import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
13 import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
14 import org.apache.hc.core5.http.HttpHeaders;
15 import org.apache.hc.core5.http.HttpStatus;
16 import org.apache.hc.core5.http.message.StatusLine;
17 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.exceptions.TokenGenerationException;
18 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.pojos.Adapter;
19 import org.o.ran.oam.nf.oam.adopter.pm.sb.rest.client.pojos.TokenResponse;
20
21 @NoArgsConstructor(access = AccessLevel.PRIVATE)
22 public final class TokenHandler {
23
24     public static final Gson GSON = new Gson();
25     public static final String HTTPS = "https://";
26
27     /**
28      * Request Token under defined endpoint.
29      */
30     public static synchronized String returnToken(final CloseableHttpAsyncClient client, final String tokenEndpoint,
31             final Adapter adapter) throws ExecutionException, InterruptedException {
32         final String host = HTTPS + adapter.getHostIpAddress();
33         final var request = SimpleHttpRequests.post(host + tokenEndpoint);
34         final var basicAuth = Base64.getEncoder().encodeToString(
35                 (adapter.getUsername() + ":" + adapter.getPassword()).getBytes(StandardCharsets.UTF_8));
36         request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
37         request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE);
38         request.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON_VALUE);
39
40         final SimpleHttpResponse response = client.execute(request, null).get();
41         final var statusLine = new StatusLine(response).toString();
42         if (response.getCode() != HttpStatus.SC_OK) {
43             throw new TokenGenerationException("Failed to obtain a token for host " + host + ": " + statusLine);
44         }
45         final String output = response.getBody().getBodyText();
46         if (output.isEmpty()) {
47             throw new TokenGenerationException(
48                     "Failed to obtain a token for host " + host + ", empty output: " + statusLine);
49         }
50         return GSON.fromJson(output, TokenResponse.class).getToken();
51     }
52 }