5cd0a3185576194988c32b833c74c5d70dce042e
[nonrtric/plt/ranpm.git] / datafilecollector / src / main / java / org / oran / datafile / http / DfcHttpsClient.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2021 Nokia. All rights reserved.
4  * Copyright (C) 2023 Nordix Foundation.
5  * ===============================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7  * in compliance with the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software distributed under the License
12  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13  * or implied. See the License for the specific language governing permissions and limitations under
14  * the License.
15  * ============LICENSE_END========================================================================
16  */
17 package org.oran.datafile.http;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.UnknownHostException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.nio.file.StandardCopyOption;
25
26 import javax.net.ssl.SSLHandshakeException;
27 import javax.net.ssl.SSLPeerUnverifiedException;
28
29 import org.apache.http.HttpEntity;
30 import org.apache.http.HttpResponse;
31 import org.apache.http.client.config.RequestConfig;
32 import org.apache.http.client.methods.CloseableHttpResponse;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.config.SocketConfig;
35 import org.apache.http.conn.ConnectTimeoutException;
36 import org.apache.http.conn.HttpHostConnectException;
37 import org.apache.http.impl.client.CloseableHttpClient;
38 import org.apache.http.impl.client.HttpClients;
39 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
40 import org.apache.http.util.EntityUtils;
41 import org.oran.datafile.commons.FileCollectClient;
42 import org.oran.datafile.exceptions.DatafileTaskException;
43 import org.oran.datafile.exceptions.NonRetryableDatafileTaskException;
44 import org.oran.datafile.model.FileServerData;
45 import org.oran.datafile.oauth2.SecurityContext;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * Gets file from PNF with HTTPS protocol.
51  *
52  */
53 public class DfcHttpsClient implements FileCollectClient {
54
55     protected CloseableHttpClient httpsClient;
56
57     private static final Logger logger = LoggerFactory.getLogger(DfcHttpsClient.class);
58     private static final int FIFTEEN_SECONDS = 15 * 1000;
59
60     private final FileServerData fileServerData;
61     private final PoolingHttpClientConnectionManager connectionManager;
62     private final SecurityContext securityContext;
63
64     public DfcHttpsClient(SecurityContext securityContext, FileServerData fileServerData,
65         PoolingHttpClientConnectionManager connectionManager) {
66         this.fileServerData = fileServerData;
67         this.connectionManager = connectionManager;
68         this.securityContext = securityContext;
69     }
70
71     @Override
72     public void open() {
73         logger.trace("Setting httpsClient for file download.");
74         SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).build();
75
76         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(FIFTEEN_SECONDS).build();
77
78         httpsClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultSocketConfig(socketConfig)
79             .setDefaultRequestConfig(requestConfig).build();
80
81         logger.trace("httpsClient prepared for connection.");
82     }
83
84     @Override
85     public void collectFile(String remoteFile, Path localFile) throws DatafileTaskException {
86         logger.trace("Prepare to collectFile {}", localFile);
87         HttpGet httpGet = new HttpGet(HttpUtils.prepareHttpsUri(fileServerData, remoteFile));
88
89         String authorizationContent = this.securityContext.getBearerAuthToken();
90         if (!authorizationContent.isEmpty()) {
91             httpGet.addHeader("Authorization", "Bearer " + authorizationContent);
92         } else if (!this.fileServerData.password.isEmpty()) {
93             authorizationContent = HttpUtils.basicAuthContent(this.fileServerData.userId, this.fileServerData.password);
94             httpGet.addHeader("Authorization", authorizationContent);
95         }
96         try {
97             HttpResponse httpResponse = makeCall(httpGet);
98             processResponse(httpResponse, localFile);
99         } catch (IOException e) {
100             logger.error("marker", e);
101             throw new DatafileTaskException("Error downloading file from server. ", e);
102         }
103         logger.trace("HTTPS collectFile OK");
104     }
105
106     HttpResponse makeCall(HttpGet httpGet) throws IOException, DatafileTaskException {
107         try {
108             HttpResponse httpResponse = executeHttpClient(httpGet);
109             if (isResponseOk(httpResponse)) {
110                 return httpResponse;
111             }
112
113             EntityUtils.consume(httpResponse.getEntity());
114             if (isErrorInConnection(httpResponse)) {
115                 logger.warn("Failed to download file, reason: {}, code: {}",
116                     httpResponse.getStatusLine().getReasonPhrase(), httpResponse.getStatusLine());
117                 throw new NonRetryableDatafileTaskException(HttpUtils.retryableResponse(getResponseCode(httpResponse)));
118             }
119             throw new DatafileTaskException(HttpUtils.nonRetryableResponse(getResponseCode(httpResponse)));
120         } catch (ConnectTimeoutException | UnknownHostException | HttpHostConnectException | SSLHandshakeException
121             | SSLPeerUnverifiedException e) {
122             logger.warn("Unable to get file from xNF: {}", e.getMessage());
123             throw new NonRetryableDatafileTaskException("Unable to get file from xNF. No retry attempts will be done.",
124                 e);
125         }
126     }
127
128     CloseableHttpResponse executeHttpClient(HttpGet httpGet) throws IOException {
129         return httpsClient.execute(httpGet);
130     }
131
132     boolean isResponseOk(HttpResponse httpResponse) {
133         return getResponseCode(httpResponse) == 200;
134     }
135
136     private int getResponseCode(HttpResponse httpResponse) {
137         return httpResponse.getStatusLine().getStatusCode();
138     }
139
140     boolean isErrorInConnection(HttpResponse httpResponse) {
141         return getResponseCode(httpResponse) >= 400;
142     }
143
144     void processResponse(HttpResponse response, Path localFile) throws IOException {
145         logger.trace("Starting to process response.");
146         HttpEntity entity = response.getEntity();
147         InputStream stream = entity.getContent();
148         long numBytes = writeFile(localFile, stream);
149         stream.close();
150         EntityUtils.consume(entity);
151         logger.trace("Transmission was successful - {} bytes downloaded.", numBytes);
152     }
153
154     long writeFile(Path localFile, InputStream stream) throws IOException {
155         return Files.copy(stream, localFile, StandardCopyOption.REPLACE_EXISTING);
156     }
157
158     @Override
159     public void close() {
160         logger.trace("Https client has ended downloading process.");
161     }
162 }