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
9 * http://www.apache.org/licenses/LICENSE-2.0
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
15 * ============LICENSE_END========================================================================
17 package org.oran.datafile.http;
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;
26 import javax.net.ssl.SSLHandshakeException;
27 import javax.net.ssl.SSLPeerUnverifiedException;
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;
50 * Gets file from PNF with HTTPS protocol.
53 public class DfcHttpsClient implements FileCollectClient {
55 protected CloseableHttpClient httpsClient;
57 private static final Logger logger = LoggerFactory.getLogger(DfcHttpsClient.class);
58 private static final int FIFTEEN_SECONDS = 15 * 1000;
60 private final FileServerData fileServerData;
61 private final PoolingHttpClientConnectionManager connectionManager;
62 private final SecurityContext securityContext;
64 public DfcHttpsClient(SecurityContext securityContext, FileServerData fileServerData,
65 PoolingHttpClientConnectionManager connectionManager) {
66 this.fileServerData = fileServerData;
67 this.connectionManager = connectionManager;
68 this.securityContext = securityContext;
73 logger.trace("Setting httpsClient for file download.");
74 SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).build();
76 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(FIFTEEN_SECONDS).build();
78 httpsClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultSocketConfig(socketConfig)
79 .setDefaultRequestConfig(requestConfig).build();
81 logger.trace("httpsClient prepared for connection.");
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));
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);
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);
103 logger.trace("HTTPS collectFile OK");
106 HttpResponse makeCall(HttpGet httpGet) throws IOException, DatafileTaskException {
108 HttpResponse httpResponse = executeHttpClient(httpGet);
109 if (isResponseOk(httpResponse)) {
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)));
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.",
128 CloseableHttpResponse executeHttpClient(HttpGet httpGet) throws IOException {
129 return httpsClient.execute(httpGet);
132 boolean isResponseOk(HttpResponse httpResponse) {
133 return getResponseCode(httpResponse) == 200;
136 private int getResponseCode(HttpResponse httpResponse) {
137 return httpResponse.getStatusLine().getStatusCode();
140 boolean isErrorInConnection(HttpResponse httpResponse) {
141 return getResponseCode(httpResponse) >= 400;
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);
150 EntityUtils.consume(entity);
151 logger.trace("Transmission was successful - {} bytes downloaded.", numBytes);
154 long writeFile(Path localFile, InputStream stream) throws IOException {
155 return Files.copy(stream, localFile, StandardCopyOption.REPLACE_EXISTING);
159 public void close() {
160 logger.trace("Https client has ended downloading process.");