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