Merge "Added support for using oauth token for Kafka"
[nonrtric/plt/ranpm.git] / datafilecollector / src / main / java / org / oran / datafile / model / FileData.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2023 Nordix Foundation.
4  *  Copyright (C) 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  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.oran.datafile.model;
23
24 import java.net.URI;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.List;
30 import java.util.Optional;
31
32 import lombok.Builder;
33
34 import org.apache.hc.core5.http.NameValuePair;
35 import org.apache.hc.core5.net.URIBuilder;
36 import org.oran.datafile.commons.FileServerData;
37 import org.oran.datafile.commons.FileServerData.FileServerDataBuilder;
38 import org.oran.datafile.commons.Scheme;
39 import org.oran.datafile.configuration.AppConfig;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Contains data, from the fileReady event, about the file to collect from the
45  * xNF.
46  *
47  */
48 @Builder
49 public class FileData {
50
51     private static final Logger logger = LoggerFactory.getLogger(FileData.class);
52
53     public FileReadyMessage.ArrayOfNamedHashMap fileInfo;
54
55     public FileReadyMessage.MessageMetaData messageMetaData;
56
57     public static Iterable<FileData> createFileData(FileReadyMessage msg) {
58         Collection<FileData> res = new ArrayList<>();
59         for (FileReadyMessage.ArrayOfNamedHashMap arr : msg.event.notificationFields.arrayOfNamedHashMap) {
60             FileData data = FileData.builder().fileInfo(arr).messageMetaData(msg.event.commonEventHeader).build();
61             res.add(data);
62         }
63         return res;
64     }
65
66     /**
67      * Get the name of the PNF, must be unique in the network.
68      *
69      * @return the name of the PNF, must be unique in the network
70      */
71     public String sourceName() {
72         return messageMetaData.sourceName;
73     }
74
75     public String name() {
76         return this.messageMetaData.sourceName + "/" + fileInfo.name;
77     }
78
79     /**
80      * Get the path to file to get from the PNF.
81      *
82      * @return the path to the file on the PNF.
83      */
84     public String remoteFilePath() {
85         return URI.create(fileInfo.hashMap.location).getPath();
86     }
87
88     public Scheme scheme() {
89         URI uri = URI.create(fileInfo.hashMap.location);
90         try {
91             return Scheme.getSchemeFromString(uri.getScheme());
92         } catch (Exception e) {
93             logger.warn("Could noit get scheme :{}", e.getMessage());
94             return Scheme.FTPES;
95         }
96     }
97
98     /**
99      * Get the path to the locally stored file.
100      *
101      * @return the path to the locally stored file.
102      */
103     public Path getLocalFilePath(AppConfig config) {
104         return Paths.get(config.getCollectedFilesPath(), this.messageMetaData.sourceName, fileInfo.name);
105     }
106
107     /**
108      * Get the data about the file server where the file should be collected from.
109      * Query data included as it can contain JWT token
110      *
111      * @return the data about the file server where the file should be collected
112      *         from.
113      */
114     public FileServerData fileServerData() {
115         URI uri = URI.create(fileInfo.hashMap.location);
116         Optional<String[]> userInfo = getUserNameAndPasswordIfGiven(uri.getUserInfo());
117
118         FileServerDataBuilder builder = FileServerData.builder() //
119             .serverAddress(uri.getHost()) //
120             .userId(userInfo.isPresent() ? userInfo.get()[0] : "") //
121             .password(userInfo.isPresent() ? userInfo.get()[1] : "");
122         if (uri.getPort() > 0) {
123             builder.port(uri.getPort());
124         }
125         URIBuilder uriBuilder = new URIBuilder(uri);
126         List<NameValuePair> query = uriBuilder.getQueryParams();
127         if (query != null && !query.isEmpty()) {
128             builder.queryParameters(query);
129         }
130         String fragment = uri.getRawFragment();
131         if (fragment != null && fragment.length() > 0) {
132             builder.uriRawFragment(fragment);
133         }
134         return builder.build();
135     }
136
137     /**
138      * Extracts user name and password from the user info, if it they are given in
139      * the URI.
140      *
141      * @param userInfoString the user info string from the URI.
142      *
143      * @return An <code>Optional</code> containing a String array with the user name
144      *         and password if given, or an empty
145      *         <code>Optional</code> if not given.
146      */
147     private static Optional<String[]> getUserNameAndPasswordIfGiven(String userInfoString) {
148         if (userInfoString != null) {
149             String[] userAndPassword = userInfoString.split(":");
150             if (userAndPassword.length == 2) {
151                 return Optional.of(userAndPassword);
152             } else if (userAndPassword.length == 1)// if just user
153             {
154                 String[] tab = new String[2];
155                 tab[0] = userAndPassword[0];
156                 tab[1] = "";// add empty password
157                 return Optional.of(tab);
158             }
159         }
160         return Optional.empty();
161     }
162 }