308b47e07428925df03bd642e83e9c2e8428de35
[nonrtric/plt/ranpm.git] / datafilecollector / src / main / java / org / oran / datafile / http / HttpUtils.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018-2023 Nordix Foundation. All rights reserved.
4  * Modifications Copyright (C) 2020-2021 Nokia. All rights reserved
5  * ===============================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END========================================================================
18  */
19
20 package org.oran.datafile.http;
21
22 import java.util.Base64;
23 import java.util.List;
24
25 import org.apache.hc.core5.http.NameValuePair;
26 import org.apache.http.HttpStatus;
27 import org.oran.datafile.model.FileServerData;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 public final class HttpUtils implements HttpStatus {
32
33     private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
34     public static final int HTTP_DEFAULT_PORT = 80;
35     public static final int HTTPS_DEFAULT_PORT = 443;
36
37     private HttpUtils() {
38     }
39
40     public static String nonRetryableResponse(int responseCode) {
41         return "Unexpected response code - " + responseCode;
42     }
43
44     public static String retryableResponse(int responseCode) {
45         return "Unexpected response code - " + responseCode + ". No retry attempts will be done.";
46     }
47
48     public static boolean isSuccessfulResponseCodeWithDataRouter(Integer statusCode) {
49         return statusCode >= 200 && statusCode < 300;
50     }
51
52     public static String basicAuthContent(String username, String password) {
53         return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
54     }
55
56     /**
57      * Prepare uri to retrieve file from xNF using HTTP connection. If JWT token was
58      * included
59      * in the queryParameters, it is removed. Other entries are rewritten.
60      *
61      * @param fileServerData fileServerData including - server address, port,
62      *        queryParameters and uriRawFragment
63      * @param remoteFile file which has to be downloaded
64      * @return uri String representing the xNF HTTP location
65      */
66     public static String prepareHttpUri(FileServerData fileServerData, String remoteFile) {
67         return prepareUri("http", fileServerData, remoteFile, HTTP_DEFAULT_PORT);
68     }
69
70     /**
71      * Prepare uri to retrieve file from xNF using HTTPS connection. If JWT token
72      * was included
73      * in the queryParameters, it is removed. Other entries are rewritten.
74      *
75      * @param fileServerData fileServerData including - server address, port,
76      *        queryParameters and uriRawFragment
77      * @param remoteFile file which has to be downloaded
78      * @return uri String representing the xNF HTTPS location
79      */
80     public static String prepareHttpsUri(FileServerData fileServerData, String remoteFile) {
81         return prepareUri("https", fileServerData, remoteFile, HTTPS_DEFAULT_PORT);
82     }
83
84     /**
85      * Prepare uri to retrieve file from xNF. If JWT token was included
86      * in the queryParameters, it is removed. Other entries are rewritten.
87      *
88      * @param scheme scheme which is used during the connection
89      * @param fileServerData fileServerData including - server address, port, query
90      *        and fragment
91      * @param remoteFile file which has to be downloaded
92      * @param defaultPort default port which exchange empty entry for given
93      *        connection type
94      * @return uri String representing the xNF location
95      */
96     public static String prepareUri(String scheme, FileServerData fileServerData, String remoteFile, int defaultPort) {
97         int port = fileServerData.port != null ? fileServerData.port : defaultPort;
98         String query = queryParametersAsString(fileServerData.queryParameters);
99         String fragment = fileServerData.uriRawFragment;
100         if (!query.isEmpty()) {
101             query = "?" + query;
102         }
103         if (!fragment.isEmpty()) {
104             fragment = "#" + fragment;
105         }
106         return scheme + "://" + fileServerData.serverAddress + ":" + port + remoteFile + query + fragment;
107     }
108
109     /**
110      *
111      *
112      * @param query list of NameValuePair of elements sent in the queryParameters
113      * @return String representation of queryParameters elements which were provided
114      *         in the input
115      *         Empty string is possible when queryParameters is empty.
116      */
117     private static String queryParametersAsString(List<NameValuePair> query) {
118         if (query.isEmpty()) {
119             return "";
120         }
121         StringBuilder sb = new StringBuilder();
122         for (NameValuePair nvp : query) {
123             sb.append(nvp.getName());
124             if (nvp.getValue() != null) {
125                 sb.append("=");
126                 sb.append(nvp.getValue());
127             }
128             sb.append("&");
129         }
130         if ((sb.length() > 0) && (sb.charAt(sb.length() - 1) == '&')) {
131             sb.deleteCharAt(sb.length() - 1);
132         }
133         return sb.toString();
134     }
135 }