Merge "Add tests to increase code coverage"
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / configuration / ApplicationConfigParser.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oransc.policyagent.configuration;
22
23 import com.google.gson.JsonArray;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
26
27 import java.net.MalformedURLException;
28 import java.net.URL;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.Set;
38
39 import javax.validation.constraints.NotNull;
40
41 import org.immutables.gson.Gson;
42 import org.immutables.value.Value;
43 import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
44 import org.oransc.policyagent.exceptions.ServiceException;
45 import org.springframework.http.MediaType;
46
47 /**
48  * Parser for the Json representing of the component configuration.
49  */
50 public class ApplicationConfigParser {
51
52     private static final String CONFIG = "config";
53     private static final String CONTROLLER = "controller";
54
55     @Value.Immutable
56     @Gson.TypeAdapters
57     public interface ConfigParserResult {
58         List<RicConfig> ricConfigs();
59
60         Properties dmaapPublisherConfig();
61
62         Properties dmaapConsumerConfig();
63
64         Map<String, ControllerConfig> controllerConfigs();
65     }
66
67     public ConfigParserResult parse(JsonObject root) throws ServiceException {
68
69         Properties dmaapPublisherConfig = new Properties();
70         Properties dmaapConsumerConfig = new Properties();
71
72         JsonObject agentConfigJson = root.getAsJsonObject(CONFIG);
73
74         if (agentConfigJson == null) {
75             throw new ServiceException("Missing root configuration \"" + CONFIG + "\" in JSON: " + root);
76         }
77
78         JsonObject json = agentConfigJson.getAsJsonObject("streams_publishes");
79         if (json != null) {
80             dmaapPublisherConfig = parseDmaapConfig(json);
81         }
82
83         json = agentConfigJson.getAsJsonObject("streams_subscribes");
84         if (json != null) {
85             dmaapConsumerConfig = parseDmaapConfig(json);
86         }
87
88         List<RicConfig> ricConfigs = parseRics(agentConfigJson);
89         Map<String, ControllerConfig> controllerConfigs = parseControllerConfigs(agentConfigJson);
90         checkConfigurationConsistency(ricConfigs, controllerConfigs);
91
92         return ImmutableConfigParserResult.builder() //
93             .dmaapConsumerConfig(dmaapConsumerConfig) //
94             .dmaapPublisherConfig(dmaapPublisherConfig) //
95             .ricConfigs(ricConfigs) //
96             .controllerConfigs(controllerConfigs) //
97             .build();
98     }
99
100     private void checkConfigurationConsistency(List<RicConfig> ricConfigs,
101         Map<String, ControllerConfig> controllerConfigs) throws ServiceException {
102         Set<String> ricUrls = new HashSet<>();
103         Set<String> ricNames = new HashSet<>();
104         for (RicConfig ric : ricConfigs) {
105             if (!ricUrls.add(ric.baseUrl())) {
106                 throw new ServiceException("Configuration error, more than one RIC URL: " + ric.baseUrl());
107             }
108             if (!ricNames.add(ric.name())) {
109                 throw new ServiceException("Configuration error, more than one RIC with name: " + ric.name());
110             }
111             if (!ric.controllerName().isEmpty() && controllerConfigs.get(ric.controllerName()) == null) {
112                 throw new ServiceException(
113                     "Configuration error, controller configuration not found: " + ric.controllerName());
114             }
115
116         }
117
118     }
119
120     private List<RicConfig> parseRics(JsonObject config) throws ServiceException {
121         List<RicConfig> result = new ArrayList<>();
122         for (JsonElement ricElem : getAsJsonArray(config, "ric")) {
123             JsonObject ricAsJson = ricElem.getAsJsonObject();
124             JsonElement controllerNameElement = ricAsJson.get(CONTROLLER);
125             ImmutableRicConfig ricConfig = ImmutableRicConfig.builder() //
126                 .name(get(ricAsJson, "name").getAsString()) //
127                 .baseUrl(get(ricAsJson, "baseUrl").getAsString()) //
128                 .managedElementIds(parseManagedElementIds(get(ricAsJson, "managedElementIds").getAsJsonArray())) //
129                 .controllerName(controllerNameElement != null ? controllerNameElement.getAsString() : "") //
130                 .build();
131             result.add(ricConfig);
132         }
133         return result;
134     }
135
136     Map<String, ControllerConfig> parseControllerConfigs(JsonObject config) throws ServiceException {
137         if (config.get(CONTROLLER) == null) {
138             return new HashMap<>();
139         }
140         Map<String, ControllerConfig> result = new HashMap<>();
141         for (JsonElement element : getAsJsonArray(config, CONTROLLER)) {
142             JsonObject controllerAsJson = element.getAsJsonObject();
143             ImmutableControllerConfig controllerConfig = ImmutableControllerConfig.builder() //
144                 .name(get(controllerAsJson, "name").getAsString()) //
145                 .baseUrl(get(controllerAsJson, "baseUrl").getAsString()) //
146                 .password(get(controllerAsJson, "password").getAsString()) //
147                 .userName(get(controllerAsJson, "userName").getAsString()) // )
148                 .build();
149
150             if (result.put(controllerConfig.name(), controllerConfig) != null) {
151                 throw new ServiceException(
152                     "Configuration error, more than one controller with name: " + controllerConfig.name());
153             }
154         }
155         return result;
156     }
157
158     private List<String> parseManagedElementIds(JsonArray asJsonObject) {
159         Iterator<JsonElement> iterator = asJsonObject.iterator();
160         List<String> managedElementIds = new ArrayList<>();
161         while (iterator.hasNext()) {
162             managedElementIds.add(iterator.next().getAsString());
163
164         }
165         return managedElementIds;
166     }
167
168     private static JsonElement get(JsonObject obj, String memberName) throws ServiceException {
169         JsonElement elem = obj.get(memberName);
170         if (elem == null) {
171             throw new ServiceException("Could not find member: '" + memberName + "' in: " + obj);
172         }
173         return elem;
174     }
175
176     private JsonArray getAsJsonArray(JsonObject obj, String memberName) throws ServiceException {
177         return get(obj, memberName).getAsJsonArray();
178     }
179
180     private Properties parseDmaapConfig(JsonObject streamCfg) throws ServiceException {
181         Set<Entry<String, JsonElement>> streamConfigEntries = streamCfg.entrySet();
182         if (streamConfigEntries.size() != 1) {
183             throw new ServiceException(
184                 "Invalid configuration. Number of streams must be one, config: " + streamConfigEntries);
185         }
186         JsonObject streamConfigEntry = streamConfigEntries.iterator().next().getValue().getAsJsonObject();
187         JsonObject dmaapInfo = get(streamConfigEntry, "dmaap_info").getAsJsonObject();
188         String topicUrl = getAsString(dmaapInfo, "topic_url");
189
190         try {
191             Properties dmaapProps = new Properties();
192             URL url = new URL(topicUrl);
193             String passwd = "";
194             String userName = "";
195             if (url.getUserInfo() != null) {
196                 String[] userInfo = url.getUserInfo().split(":");
197                 userName = userInfo[0];
198                 passwd = userInfo[1];
199             }
200             String urlPath = url.getPath();
201             DmaapUrlPath path = parseDmaapUrlPath(urlPath);
202
203             dmaapProps.put("ServiceName", url.getHost() + ":" + url.getPort() + "/events");
204             dmaapProps.put("topic", path.dmaapTopicName);
205             dmaapProps.put("host", url.getHost() + ":" + url.getPort());
206             dmaapProps.put("contenttype", MediaType.APPLICATION_JSON.toString());
207             dmaapProps.put("userName", userName);
208             dmaapProps.put("password", passwd);
209             dmaapProps.put("group", path.consumerGroup);
210             dmaapProps.put("id", path.consumerId);
211             dmaapProps.put("TransportType", ProtocolTypeConstants.HTTPNOAUTH.toString());
212             dmaapProps.put("timeout", "15000");
213             dmaapProps.put("limit", "100");
214             dmaapProps.put("maxBatchSize", "10");
215             dmaapProps.put("maxAgeMs", "10000");
216             dmaapProps.put("compress", true);
217             dmaapProps.put("MessageSentThreadOccurance", "2");
218             return dmaapProps;
219         } catch (MalformedURLException e) {
220             throw new ServiceException("Could not parse the URL", e);
221         }
222     }
223
224     private static @NotNull String getAsString(JsonObject obj, String memberName) throws ServiceException {
225         return get(obj, memberName).getAsString();
226     }
227
228     private class DmaapUrlPath {
229         final String dmaapTopicName;
230         final String consumerGroup;
231         final String consumerId;
232
233         DmaapUrlPath(String dmaapTopicName, String consumerGroup, String consumerId) {
234             this.dmaapTopicName = dmaapTopicName;
235             this.consumerGroup = consumerGroup;
236             this.consumerId = consumerId;
237         }
238     }
239
240     private DmaapUrlPath parseDmaapUrlPath(String urlPath) throws ServiceException {
241         String[] tokens = urlPath.split("/"); // /events/A1-P/users/sdnc1
242         if (!(tokens.length == 3 ^ tokens.length == 5)) {
243             throw new ServiceException("The path has incorrect syntax: " + urlPath);
244         }
245
246         final String dmaapTopicName = tokens[2]; // /events/A1-P
247         String consumerGroup = ""; // users
248         String consumerId = ""; // sdnc1
249         if (tokens.length == 5) {
250             consumerGroup = tokens[3];
251             consumerId = tokens[4];
252         }
253         return new DmaapUrlPath(dmaapTopicName, consumerGroup, consumerId);
254     }
255 }