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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
14 * ============LICENSE_END========================================================================
16 package org.oran.datafile.http;
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;
25 import javax.net.ssl.SSLHandshakeException;
26 import javax.net.ssl.SSLPeerUnverifiedException;
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;
48 * Gets file from PNF with HTTPS protocol.
51 public class DfcHttpsClient implements FileCollectClient {
53 protected CloseableHttpClient httpsClient;
55 private static final Logger logger = LoggerFactory.getLogger(DfcHttpsClient.class);
56 private static final int FIFTEEN_SECONDS = 15 * 1000;
58 private final FileServerData fileServerData;
59 private final PoolingHttpClientConnectionManager connectionManager;
61 public DfcHttpsClient(FileServerData fileServerData, PoolingHttpClientConnectionManager connectionManager) {
62 this.fileServerData = fileServerData;
63 this.connectionManager = connectionManager;
68 logger.trace("Setting httpsClient for file download.");
69 SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).build();
71 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(FIFTEEN_SECONDS).build();
73 httpsClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultSocketConfig(socketConfig)
74 .setDefaultRequestConfig(requestConfig).build();
76 logger.trace("httpsClient prepared for connection.");
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));
84 String authorizationContent = getAuthorizationContent();
85 if (!authorizationContent.isEmpty()) {
86 httpGet.addHeader("Authorization", authorizationContent);
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);
95 logger.trace("HTTPS collectFile OK");
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);
103 return HttpUtils.jwtAuthContent(jwtToken);
106 private boolean shouldUseBasicAuth(String jwtToken) throws DatafileTaskException {
107 return basicAuthValidNotPresentOrThrow() && jwtToken.isEmpty();
110 protected boolean basicAuthValidNotPresentOrThrow() throws DatafileTaskException {
111 if (isAuthDataEmpty()) {
114 if (HttpUtils.isBasicAuthDataFilled(fileServerData)) {
117 throw new DatafileTaskException("Not sufficient basic auth data for file.");
120 private boolean isAuthDataEmpty() {
121 return this.fileServerData.userId.isEmpty() && this.fileServerData.password.isEmpty();
124 protected HttpResponse makeCall(HttpGet httpGet) throws IOException, DatafileTaskException {
126 HttpResponse httpResponse = executeHttpClient(httpGet);
127 if (isResponseOk(httpResponse)) {
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)));
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.",
146 protected CloseableHttpResponse executeHttpClient(HttpGet httpGet) throws IOException {
147 return httpsClient.execute(httpGet);
150 protected boolean isResponseOk(HttpResponse httpResponse) {
151 return getResponseCode(httpResponse) == 200;
154 private int getResponseCode(HttpResponse httpResponse) {
155 return httpResponse.getStatusLine().getStatusCode();
158 protected boolean isErrorInConnection(HttpResponse httpResponse) {
159 return getResponseCode(httpResponse) >= 400;
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);
168 EntityUtils.consume(entity);
169 logger.trace("Transmission was successful - {} bytes downloaded.", numBytes);
172 protected long writeFile(Path localFile, InputStream stream) throws IOException {
173 return Files.copy(stream, localFile, StandardCopyOption.REPLACE_EXISTING);
177 public void close() {
178 logger.trace("Https client has ended downloading process.");