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