fc1985acb4a432ba59aa359b9c9b96660c5eb47b
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
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.onap.ccsdk.oran.a1policymanagementservice.configuration;
22
23 import com.google.common.io.CharStreams;
24 import com.google.gson.JsonArray;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonObject;
27
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.nio.charset.StandardCharsets;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Map.Entry;
40 import java.util.Set;
41
42 import javax.validation.constraints.NotNull;
43
44 import org.immutables.gson.Gson;
45 import org.immutables.value.Value;
46 import org.json.JSONObject;
47 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.http.HttpStatus;
51
52 /**
53  * Parser for the Json representing of the component configuration.
54  */
55 public class ApplicationConfigParser {
56     private static final Logger logger = LoggerFactory.getLogger(ApplicationConfigParser.class);
57
58     private static final String CONFIG = "config";
59     private static final String CONTROLLER = "controller";
60     private final ApplicationConfig applicationConfig;
61
62     public ApplicationConfigParser(ApplicationConfig applicationConfig) {
63         this.applicationConfig = applicationConfig;
64     }
65
66     @Value.Immutable
67     @Gson.TypeAdapters
68     public interface ConfigParserResult {
69         List<RicConfig> ricConfigs();
70
71         Map<String, ControllerConfig> controllerConfigs();
72
73         String dmaapConsumerTopicUrl();
74
75         String dmaapProducerTopicUrl();
76
77     }
78
79     public ConfigParserResult parse(JsonObject root) throws ServiceException {
80
81         validateJsonObjectAgainstSchema(root);
82
83         String dmaapProducerTopicUrl = "";
84         String dmaapConsumerTopicUrl = "";
85
86         JsonObject pmsConfigJson = root.getAsJsonObject(CONFIG);
87
88         if (pmsConfigJson == null) {
89             throw new ServiceException("Missing root configuration \"" + CONFIG + "\" in JSON: " + root);
90         }
91
92         JsonObject json = pmsConfigJson.getAsJsonObject("streams_publishes");
93         if (json != null) {
94             dmaapProducerTopicUrl = parseDmaapConfig(json);
95         }
96
97         json = pmsConfigJson.getAsJsonObject("streams_subscribes");
98         if (json != null) {
99             dmaapConsumerTopicUrl = parseDmaapConfig(json);
100         }
101
102         List<RicConfig> ricConfigs = parseRics(pmsConfigJson);
103         Map<String, ControllerConfig> controllerConfigs = parseControllerConfigs(pmsConfigJson);
104         checkConfigurationConsistency(ricConfigs, controllerConfigs);
105
106         return ImmutableConfigParserResult.builder() //
107                 .dmaapConsumerTopicUrl(dmaapConsumerTopicUrl) //
108                 .dmaapProducerTopicUrl(dmaapProducerTopicUrl) //
109                 .ricConfigs(ricConfigs) //
110                 .controllerConfigs(controllerConfigs) //
111                 .build();
112     }
113
114     private void validateJsonObjectAgainstSchema(Object object) throws ServiceException {
115         if (applicationConfig.getConfigurationFileSchemaPath() == null
116                 || applicationConfig.getConfigurationFileSchemaPath().isEmpty()) {
117             return;
118         }
119
120         try {
121             String schemaAsString = readSchemaFile();
122
123             JSONObject schemaJSON = new JSONObject(schemaAsString);
124             var schema = org.everit.json.schema.loader.SchemaLoader.load(schemaJSON);
125
126             String objectAsString = object.toString();
127             JSONObject json = new JSONObject(objectAsString);
128             schema.validate(json);
129         } catch (Exception e) {
130             throw new ServiceException("Json schema validation failure: " + e.toString());
131         }
132     }
133
134     private String readSchemaFile() throws IOException, ServiceException {
135         String filePath = applicationConfig.getConfigurationFileSchemaPath();
136         InputStream in = getClass().getResourceAsStream(filePath);
137         logger.debug("Reading application schema file from: {} with: {}", filePath, in);
138         if (in == null) {
139             throw new ServiceException("Could not read application configuration schema file: " + filePath,
140                     HttpStatus.INTERNAL_SERVER_ERROR);
141         }
142         return CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8));
143     }
144
145     private void checkConfigurationConsistency(List<RicConfig> ricConfigs,
146             Map<String, ControllerConfig> controllerConfigs) throws ServiceException {
147         Set<String> ricUrls = new HashSet<>();
148         Set<String> ricNames = new HashSet<>();
149         for (RicConfig ric : ricConfigs) {
150             if (!ricUrls.add(ric.baseUrl())) {
151                 throw new ServiceException("Configuration error, more than one RIC URL: " + ric.baseUrl());
152             }
153             if (!ricNames.add(ric.ricId())) {
154                 throw new ServiceException("Configuration error, more than one RIC with name: " + ric.ricId());
155             }
156             if (!ric.controllerName().isEmpty() && controllerConfigs.get(ric.controllerName()) == null) {
157                 throw new ServiceException(
158                         "Configuration error, controller configuration not found: " + ric.controllerName());
159             }
160         }
161     }
162
163     private List<RicConfig> parseRics(JsonObject config) throws ServiceException {
164         List<RicConfig> result = new ArrayList<>();
165         for (JsonElement ricElem : getAsJsonArray(config, "ric")) {
166             JsonObject ricJsonObj = ricElem.getAsJsonObject();
167             RicConfig ricConfig = ImmutableRicConfig.builder() //
168                     .ricId(get(ricJsonObj, "name", "id", "ricId").getAsString()) //
169                     .baseUrl(get(ricJsonObj, "baseUrl").getAsString()) //
170                     .managedElementIds(parseManagedElementIds(get(ricJsonObj, "managedElementIds").getAsJsonArray())) //
171                     .controllerName(getString(ricJsonObj, CONTROLLER, ""))
172                     .customAdapterClass(getString(ricJsonObj, "customAdapterClass", "")) //
173                     .build();
174             if (!ricConfig.baseUrl().isEmpty()) {
175                 result.add(ricConfig);
176             } else {
177                 logger.error("RIC configuration error {}, baseUrl is empty", ricConfig.ricId());
178             }
179         }
180         return result;
181     }
182
183     String getString(JsonObject obj, String name, String defaultValue) {
184         JsonElement elem = obj.get(name);
185         if (elem != null) {
186             return elem.getAsString();
187         }
188         return defaultValue;
189     }
190
191     Map<String, ControllerConfig> parseControllerConfigs(JsonObject config) throws ServiceException {
192         if (config.get(CONTROLLER) == null) {
193             return new HashMap<>();
194         }
195         Map<String, ControllerConfig> result = new HashMap<>();
196         for (JsonElement element : getAsJsonArray(config, CONTROLLER)) {
197             JsonObject controllerAsJson = element.getAsJsonObject();
198             ImmutableControllerConfig controllerConfig = ImmutableControllerConfig.builder() //
199                     .name(get(controllerAsJson, "name").getAsString()) //
200                     .baseUrl(get(controllerAsJson, "baseUrl").getAsString()) //
201                     .password(get(controllerAsJson, "password").getAsString()) //
202                     .userName(get(controllerAsJson, "userName").getAsString()) // )
203                     .build();
204
205             if (result.put(controllerConfig.name(), controllerConfig) != null) {
206                 throw new ServiceException(
207                         "Configuration error, more than one controller with name: " + controllerConfig.name());
208             }
209         }
210         return result;
211     }
212
213     private List<String> parseManagedElementIds(JsonArray asJsonObject) {
214         Iterator<JsonElement> iterator = asJsonObject.iterator();
215         List<String> managedElementIds = new ArrayList<>();
216         while (iterator.hasNext()) {
217             managedElementIds.add(iterator.next().getAsString());
218
219         }
220         return managedElementIds;
221     }
222
223     private static JsonElement get(JsonObject obj, String... alternativeMemberNames) throws ServiceException {
224         for (String memberName : alternativeMemberNames) {
225             JsonElement elem = obj.get(memberName);
226             if (elem != null) {
227                 return elem;
228             }
229         }
230         throw new ServiceException("Could not find member: " + Arrays.toString(alternativeMemberNames) + " in: " + obj);
231     }
232
233     private JsonArray getAsJsonArray(JsonObject obj, String memberName) throws ServiceException {
234         return get(obj, memberName).getAsJsonArray();
235     }
236
237     private String parseDmaapConfig(JsonObject streamCfg) throws ServiceException {
238         Set<Entry<String, JsonElement>> streamConfigEntries = streamCfg.entrySet();
239         if (streamConfigEntries.size() != 1) {
240             throw new ServiceException(
241                     "Invalid configuration. Number of streams must be one, config: " + streamConfigEntries);
242         }
243         JsonObject streamConfigEntry = streamConfigEntries.iterator().next().getValue().getAsJsonObject();
244         JsonObject dmaapInfo = get(streamConfigEntry, "dmaap_info").getAsJsonObject();
245         return getAsString(dmaapInfo, "topic_url");
246     }
247
248     private static @NotNull String getAsString(JsonObject obj, String memberName) throws ServiceException {
249         return get(obj, memberName).getAsString();
250     }
251 }