2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
23 import com.att.research.xacml.util.XACMLProperties;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.DeserializationFeature;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import com.fasterxml.jackson.databind.ObjectWriter;
29 import com.fasterxml.jackson.databind.node.ArrayNode;
30 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
31 import com.fasterxml.jackson.databind.node.ObjectNode;
32 import com.google.gson.Gson;
34 import java.io.BufferedInputStream;
35 import java.io.BufferedOutputStream;
37 import java.io.FileOutputStream;
38 import java.io.IOException;
39 import java.io.OutputStream;
40 import java.io.PrintWriter;
41 import java.io.StringReader;
42 import java.nio.file.Files;
43 import java.nio.file.Path;
44 import java.nio.file.Paths;
45 import java.util.ArrayList;
46 import java.util.Enumeration;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.LinkedHashMap;
51 import java.util.LinkedList;
52 import java.util.List;
54 import java.util.Map.Entry;
56 import java.util.TreeMap;
57 import java.util.TreeSet;
58 import java.util.UUID;
59 import java.util.regex.Pattern;
60 import java.util.zip.ZipEntry;
61 import java.util.zip.ZipFile;
63 import javax.json.Json;
64 import javax.json.JsonArray;
65 import javax.json.JsonArrayBuilder;
66 import javax.json.JsonObject;
67 import javax.json.JsonObjectBuilder;
68 import javax.json.JsonReader;
69 import javax.json.JsonValue;
70 import javax.servlet.http.HttpServletRequest;
71 import javax.servlet.http.HttpServletResponse;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
81 import org.apache.commons.compress.utils.IOUtils;
82 import org.apache.commons.fileupload.FileItem;
83 import org.apache.commons.fileupload.FileUploadException;
84 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
85 import org.apache.commons.fileupload.servlet.ServletFileUpload;
86 import org.apache.commons.io.FileUtils;
87 import org.apache.commons.lang.StringUtils;
88 import org.json.JSONArray;
89 import org.json.JSONObject;
90 import org.onap.policy.common.logging.flexlogger.FlexLogger;
91 import org.onap.policy.common.logging.flexlogger.Logger;
92 import org.onap.policy.rest.XACMLRestProperties;
93 import org.onap.policy.rest.adapter.PolicyRestAdapter;
94 import org.onap.policy.rest.dao.CommonClassDao;
95 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
96 import org.onap.policy.rest.jpa.MicroServiceModels;
97 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
98 import org.onap.policy.rest.jpa.PolicyEntity;
99 import org.onap.policy.rest.util.MSAttributeObject;
100 import org.onap.policy.rest.util.MSModelUtils;
101 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
102 import org.onap.portalsdk.core.controller.RestrictedBaseController;
103 import org.onap.portalsdk.core.web.support.JsonMessage;
104 import org.springframework.beans.factory.annotation.Autowired;
105 import org.springframework.http.MediaType;
106 import org.springframework.stereotype.Controller;
107 import org.springframework.web.bind.annotation.RequestMapping;
108 import org.springframework.web.servlet.ModelAndView;
112 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
113 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
115 private static CommonClassDao commonClassDao;
117 public static CommonClassDao getCommonClassDao() {
118 return commonClassDao;
121 public static void setCommonClassDao(CommonClassDao commonClassDao) {
122 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
125 private MicroServiceModels newModel;
126 private String newFile;
127 private String directory;
128 private List<String> modelList = new ArrayList<>();
129 private List<String> dirDependencyList = new ArrayList<>();
130 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
131 String referenceAttributes;
132 String attributeString;
133 Set<String> allManyTrueKeys = null;
134 private Map<String, String> sigRules = null;
136 public static final String DATATYPE = "data_types.policy.data.";
137 public static final String PROPERTIES = ".properties.";
138 public static final String TYPE = ".type";
139 public static final String STRING = "string";
140 public static final String INTEGER = "integer";
141 public static final String LIST = "list";
142 public static final String DEFAULT = ".default";
143 public static final String REQUIRED = ".required";
144 public static final String MATCHABLE = ".matchable";
145 public static final String MANYFALSE = ":MANY-false";
146 private static final Pattern PATTERN = Pattern.compile("[A][0-9]");
147 private static final String POLICYJSON = "policyJSON";
150 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) {
151 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
154 public CreateDcaeMicroServiceController() {
158 protected PolicyRestAdapter policyAdapter = null;
159 private int priorityCount;
160 private Map<String, String> attributesListRefMap = new HashMap<>();
161 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
162 private Map<String, String> jsonStringValues = new HashMap<>();
164 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
166 String jsonContent = null;
168 LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
170 String tempJson = root.get(POLICYJSON).toString();
171 JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString());
172 if (policyJSON != null) {
173 tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString();
175 // ---replace empty value with the value below before calling decodeContent method.
176 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
177 LOGGER.info("dummyValue:" + dummyValue);
179 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
180 ObjectMapper mapper = new ObjectMapper();
181 JsonNode tempJsonNode = mapper.readTree(tempJson);
182 jsonContent = decodeContent(tempJsonNode).toString();
183 constructJson(policyData, jsonContent, dummyValue);
184 } catch (Exception e) {
185 LOGGER.error("Error while decoding microservice content", e);
188 // ----Here is the final step to reset the original value back.
189 if (policyData.getJsonBody() != null && jsonStringValues.size() > 0) {
190 String contentBody = policyData.getJsonBody();
191 JSONObject contentJson = new JSONObject(contentBody);
192 JSONObject content = contentJson.getJSONObject("content");
193 content = setOriginalJsonObject(content, jsonStringValues);
194 contentJson.put("content", content);
195 policyData.setJsonBody(contentJson.toString());
201 private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
202 for (Object key : jsonObj.keySet()) {
203 String keyStr = (String) key;
204 Object keyvalue = jsonObj.get(keyStr);
205 if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) {
206 jsonStringValues.put(keyStr, keyvalue.toString());
207 // --- set default value
208 jsonObj.put(keyStr, "JSON_STRING");
211 // for nested objects iteration if required
212 if (keyvalue instanceof JSONObject) {
213 saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
214 // --- set default value
215 jsonObj.put(keyStr, "JSON_STRING");
218 if (keyvalue instanceof JSONArray) {
219 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
220 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
221 saveOriginalJsonObject(temp, jsonStringValues);
229 private JSONObject setOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
230 for (Object key : jsonObj.keySet()) {
231 String keyStr = (String) key;
232 Object keyvalue = jsonObj.get(keyStr);
233 String originalValue = getOriginalValue(keyStr);
234 if (originalValue != null) {
235 jsonObj.put(keyStr, originalValue);
238 // for nested objects iteration if required
239 if (keyvalue instanceof JSONObject) {
240 setOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
241 jsonObj.put(keyStr, originalValue);
244 if (keyvalue instanceof JSONArray) {
245 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
246 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
247 setOriginalJsonObject(temp, jsonStringValues);
255 private GroupPolicyScopeList getPolicyObject(String policyScope) {
256 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
259 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue)
261 ObjectWriter om = new ObjectMapper().writer();
263 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
264 MicroServiceModels returnModel = new MicroServiceModels();
265 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
266 if (policyAdapter.getServiceType() != null) {
267 microServiceObject.setService(policyAdapter.getServiceType());
268 microServiceObject.setVersion(policyAdapter.getVersion());
269 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
271 if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) {
272 if (policyAdapter.getUuid() != null) {
273 microServiceObject.setUuid(policyAdapter.getUuid());
275 if (policyAdapter.getLocation() != null) {
276 microServiceObject.setLocation(policyAdapter.getLocation());
278 if (policyAdapter.getConfigName() != null) {
279 microServiceObject.setConfigName(policyAdapter.getConfigName());
281 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
282 if (policyScopeValue != null) {
283 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
287 if (policyAdapter.getPolicyName() != null) {
288 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
290 if (policyAdapter.getPolicyDescription() != null) {
291 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
293 if (policyAdapter.getPriority() != null) {
294 microServiceObject.setPriority(policyAdapter.getPriority());
296 microServiceObject.setPriority("9999");
299 if (policyAdapter.getRiskLevel() != null) {
300 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
302 if (policyAdapter.getRiskType() != null) {
303 microServiceObject.setRiskType(policyAdapter.getRiskType());
305 if (policyAdapter.getGuard() != null) {
306 microServiceObject.setGuard(policyAdapter.getGuard());
308 microServiceObject.setContent(jsonContent);
309 String modelName = policyAdapter.getServiceType();
310 String versionName = policyAdapter.getVersion();
311 List<Object> triggerData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version",
312 modelName + ":" + versionName);
313 MicroServiceModels model = null;
314 boolean ruleCheck = false;
315 boolean SymptomRuleCheck = false;
316 if (!triggerData.isEmpty()) {
317 model = (MicroServiceModels) triggerData.get(0);
318 if (model.getRuleFormation() != null) {
319 microServiceObject.setUiContent(jsonContent);
321 if (model.getRuleFormation().contains("@")) {
322 SymptomRuleCheck = true;
327 json = om.writeValueAsString(microServiceObject);
328 } catch (JsonProcessingException e) {
329 LOGGER.error("Error writing out the object", e);
331 LOGGER.info("input json: " + json);
332 LOGGER.info("input jsonContent: " + jsonContent);
333 String cleanJson = cleanUPJson(json);
334 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
336 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
337 LOGGER.info("tempJson: " + tempJson);
338 cleanJson = removeNullAttributes(tempJson);
339 if (cleanJson.contains("\\")) {
340 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\"}, new String[] {""});
342 policyAdapter.setJsonBody(cleanJson);
344 ObjectMapper mapper = new ObjectMapper();
345 JsonNode tempJsonNode = mapper.readTree(cleanJson);
347 // JsonNode tempJsonNode = mapper.readTree(cleanJson);
348 ObjectNode finalJson = (ObjectNode) tempJsonNode;
349 JsonNode object = tempJsonNode.get("content");
350 String primaryKey1 = model.getRuleFormation();
351 String[] primaryKeyForSignatures = primaryKey1.split("@");
352 for (String primaryKeyForSignature : primaryKeyForSignatures) {
353 String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
354 JsonNode triggerSig = object.get(primarykeyAlarm);
355 sigRules = new HashMap<>();
356 String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
357 StringBuilder sb = null;
358 if (triggerSig instanceof ArrayNode) {
359 for (int i = 0; i < triggerSig.size(); i++) {
360 sb = new StringBuilder();
361 parseData(triggerSig.get(i), parseKey);
363 List<?> keyList = new ArrayList<>(sigRules.keySet());
364 for (int j = keyList.size() - 1; j >= 0; j--) {
365 String key = (String) keyList.get(j);
366 String jsonNode = sigRules.get(key);
367 constructRule(sb, jsonNode, sigRules);
369 sb.append(")").toString();
370 putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
371 sigRules = new HashMap<>();
374 sb = new StringBuilder();
375 parseData(triggerSig, parseKey);
378 policyAdapter.setJsonBody(finalJson.toString());
380 return policyAdapter;
383 private JsonNode putRuletoJson(JsonNode tmpJsonNode, int item, StringBuilder sb, String parseKey,
385 JsonNode tmp = tmpJsonNode;
386 ObjectNode objectNode = (ObjectNode) tmp;
387 JsonNode jsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
388 JsonNode tempRuleJsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
389 String[] tempSt = parseKey.split("\\.");
390 for (String value : tempSt) {
391 if (value.contains("[")) {
392 if (tempRuleJsonNode instanceof ArrayNode) {
393 JsonNode tempRuleNode = tempRuleJsonNode.get(item);
394 ((ArrayNode) tempRuleJsonNode).removeAll();
395 ((ArrayNode) tempRuleJsonNode).add(tempRuleNode);
396 objectNode = (ObjectNode) tempRuleJsonNode.get(item);
398 String key = value.substring(0, value.indexOf('['));
399 objectNode.remove(key);
400 objectNode.put(key, sb.toString());
403 jsonNode = jsonNode.get(value);
404 if (jsonNode instanceof ArrayNode) {
405 tempRuleJsonNode = jsonNode;
406 jsonNode = jsonNode.get(item);
413 public boolean checkPattern(String patternString) {
414 return PATTERN.matcher(patternString).find();
421 * @param jsonNode the json node
422 * @param sigRules2 the sig rules 2
424 public void constructRule(StringBuilder sb, String jsonNode, Map<String, String> sigRules2) {
426 String cleanJsonNode = jsonNode.replace("\"\"", " ");
427 cleanJsonNode = cleanJsonNode.replaceAll("\"", "");
428 cleanJsonNode = cleanJsonNode.replaceAll("\\(", "");
429 cleanJsonNode = cleanJsonNode.replaceAll("\\)", "");
430 boolean flag = false;
431 if (cleanJsonNode.contains("OR")) {
435 for (String rowValue : cleanJsonNode.split(" ")) {
436 if (checkPattern(rowValue)) {
437 String value = sigRules2.get(rowValue);
438 LOGGER.info(" Value is:" + value);
439 constructRule(sb, value, sigRules2);
441 if ((count == 0) && (!("AND").equals(rowValue)) && (!("OR").equals(rowValue))) {
445 LOGGER.info(" " + rowValue + " ");
446 sb.append(" " + rowValue + " ");
447 if (count % 3 == 0) {
461 * @param jsonNode the json node
462 * @param string the string
464 public void parseData(JsonNode jsonNode, String string) {
465 if (string.contains(".")) {
466 String firstIndex = string.substring(0, string.indexOf('.'));
467 JsonNode signtures = jsonNode.get(firstIndex);
468 String subIndex = string.substring(firstIndex.length() + 1);
469 if (signtures instanceof ArrayNode) {
470 for (int i = 0; i < signtures.size(); i++) {
471 parseData(signtures.get(i), subIndex);
474 parseData(signtures, subIndex);
477 if (string.contains("[")) {
478 String ruleIndex = string.substring(0, string.indexOf('['));
479 String[] keys = string.substring(string.indexOf('[') + 1, string.lastIndexOf(']')).split(",");
480 String key = "A" + Integer.valueOf(sigRules.size() + 1);
481 JsonNode node = jsonNode.get(ruleIndex);
482 StringBuilder sb = new StringBuilder("(");
483 for (int i = 0; i < keys.length; i++) {
484 sb.append(node.get(keys[i].trim()));
487 sigRules.put(key, sb.toString());
492 public String removeNullAttributes(String cleanJson) {
493 ObjectMapper mapper = new ObjectMapper();
496 JsonNode rootNode = mapper.readTree(cleanJson);
497 JsonNode returnNode = mapper.readTree(cleanJson);
498 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
499 boolean remove = false;
500 JsonObject removed = null;
501 boolean contentChanged = false;
502 while (fieldsIterator.hasNext()) {
503 Map.Entry<String, JsonNode> field = fieldsIterator.next();
504 final String key = field.getKey();
505 final JsonNode value = field.getValue();
506 if ("content".equalsIgnoreCase(key)) {
507 String contentStr = value.toString();
508 try (JsonReader reader = Json.createReader(new StringReader(contentStr))) {
509 JsonObject jsonContent = reader.readObject();
510 removed = removeNull(jsonContent);
511 if (!jsonContent.toString().equals(removed.toString())) {
512 contentChanged = true;
516 if (value == null || value.isNull()) {
517 ((ObjectNode) returnNode).remove(key);
522 cleanJson = returnNode.toString();
524 if (value == null || value.isNull()) {
525 ((ObjectNode) returnNode).remove(key);
530 cleanJson = returnNode.toString();
533 if (contentChanged) {
534 // set modified content to cleanJson
535 JSONObject jObject = new JSONObject(cleanJson);
536 jObject.put("content", removed.toString());
537 cleanJson = cleanUPJson(jObject.toString());
540 } catch (IOException e) {
541 LOGGER.error("Error writing out the JsonNode", e);
547 * To verify if it is a JSON string. If it is, then return its original value.
549 * @param key holds the values
552 private String getOriginalValue(String key) {
553 for (String k : jsonStringValues.keySet()) {
554 if (k.contains("@")) {
555 String[] arrOfKeys = k.split("@");
556 for (int i = 0; i < arrOfKeys.length; i++) {
557 if (arrOfKeys[i].contains(".")) {
558 arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
559 if (arrOfKeys[i].equals(key)) {
560 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
561 new String[] {"\\\""});
566 if (k.endsWith(key)) {
567 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
574 public JsonArray removeNull(JsonArray array) {
575 JsonArrayBuilder builder = Json.createArrayBuilder();
577 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
578 JsonValue value = it.next();
579 switch (value.getValueType()) {
581 JsonArray a = removeNull(array.getJsonArray(i));
586 JsonObject object = removeNull(array.getJsonObject(i));
587 if (!object.isEmpty())
591 String s = array.getString(i);
592 if (s != null && !s.isEmpty())
596 builder.add(array.getJsonNumber(i));
600 builder.add(array.getBoolean(i));
606 return builder.build();
609 public JsonObject removeNull(JsonObject obj) {
610 JsonObjectBuilder builder = Json.createObjectBuilder();
611 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
612 Entry<String, JsonValue> e = it.next();
613 String key = e.getKey();
614 JsonValue value = e.getValue();
615 switch (value.getValueType()) {
617 JsonArray array = removeNull(obj.getJsonArray(key));
618 if (!array.isEmpty())
619 builder.add(key, array);
622 JsonObject object = removeNull(obj.getJsonObject(key));
623 if (!object.isEmpty()) {
624 if (!jsonStringValues.isEmpty()) {
625 String originalValue = getOriginalValue(key);
626 if (originalValue != null) {
627 builder.add(key, object.toString());
631 builder.add(key, object);
635 String s = obj.getString(key);
636 if (s != null && !s.isEmpty()) {
637 if (!jsonStringValues.isEmpty()) {
638 String originalValue = getOriginalValue(key);
639 if (originalValue != null) {
640 s = getOriginalValue(key);
647 builder.add(key, obj.getJsonNumber(key));
651 builder.add(key, obj.getBoolean(key));
657 return builder.build();
660 public String cleanUPJson(String json) {
661 String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
662 new String[] {"\\", "\\", "\\"});
663 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
665 StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"});
667 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""},
668 new String[] {"\"", "\"", "[{", "}]"});
669 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[{", "}]\""}, new String[] {"[{", "}]"});
670 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
671 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"{", "}\""}, new String[] {"{", "}"});
672 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\"\"", "\"\""}, new String[] {"\"", "\""});
673 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\""}, new String[] {""});
674 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\""}, new String[] {"\""});
675 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\\\\\\"}, new String[] {"\""});
676 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\\""}, new String[] {"\""});
677 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
681 public JSONObject decodeContent(JsonNode jsonNode) {
682 Iterator<JsonNode> jsonElements = jsonNode.elements();
683 Iterator<String> jsonKeys = jsonNode.fieldNames();
684 Map<String, String> element = new TreeMap<>();
685 while (jsonElements.hasNext() && jsonKeys.hasNext()) {
686 element.put(jsonKeys.next(), jsonElements.next().toString());
688 JSONObject jsonResult = new JSONObject();
689 JSONArray jsonArray = null;
690 String oldValue = null;
691 String nodeKey = null;
692 String arryKey = null;
693 Boolean isArray = false;
694 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
695 ObjectNode node = nodeFactory.objectNode();
696 String prevKey = null;
698 for (Entry<String, String> entry : element.entrySet()) {
699 String key = entry.getKey();
700 String value = entry.getValue();
701 if (key.contains(".")) {
702 presKey = key.substring(0, key.indexOf('.'));
703 } else if (key.contains("@")) {
704 presKey = key.substring(0, key.indexOf('@'));
708 // first check if we are different from old.
709 LOGGER.info(key + "\n");
710 if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".")
711 && oldValue != null) {
712 if (!oldValue.equals(key.substring(0, key.indexOf('@')))) {
713 jsonResult.put(oldValue, jsonArray);
714 jsonArray = new JSONArray();
716 } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) {
717 jsonResult.put(oldValue, jsonArray);
719 jsonArray = new JSONArray();
724 if (key.contains(".")) {
725 if (nodeKey == null) {
726 nodeKey = key.substring(0, key.indexOf('.'));
728 if (nodeKey.equals(key.substring(0, key.indexOf('.')))) {
729 node.put(key.substring(key.indexOf('.') + 1), value);
731 if (node.size() != 0) {
732 if (nodeKey.contains("@")) {
733 if (arryKey == null) {
734 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
736 if (nodeKey.endsWith("@0")) {
738 jsonArray = new JSONArray();
740 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
741 jsonArray.put(decodeContent(node));
743 if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@'))))
744 || !key.contains("@")) {
745 jsonResult.put(arryKey, jsonArray);
746 jsonArray = new JSONArray();
748 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
751 jsonResult.put(nodeKey, decodeContent(node));
753 node = nodeFactory.objectNode();
755 nodeKey = key.substring(0, key.indexOf('.'));
756 if (nodeKey.contains("@")) {
757 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
759 node.put(key.substring(key.indexOf('.') + 1), value);
762 if (node.size() != 0) {
763 if (nodeKey.contains("@")) {
764 if (arryKey == null) {
765 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
767 if (nodeKey.endsWith("@0")) {
769 jsonArray = new JSONArray();
771 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
772 jsonArray.put(decodeContent(node));
774 jsonResult.put(arryKey, jsonArray);
775 jsonArray = new JSONArray();
776 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
779 jsonResult.put(nodeKey, decodeContent(node));
781 node = nodeFactory.objectNode();
783 if (key.contains("@")) {
785 if (key.endsWith("@0") || jsonArray == null) {
786 jsonArray = new JSONArray();
788 } else if (!key.contains("@")) {
792 if (oldValue == null) {
793 oldValue = key.substring(0, key.indexOf('@'));
795 if (oldValue != prevKey) {
796 oldValue = key.substring(0, key.indexOf('@'));
798 if (oldValue.equals(key.substring(0, key.indexOf('@')))) {
799 jsonArray.put(value);
801 jsonResult.put(oldValue, jsonArray);
802 jsonArray = new JSONArray();
804 oldValue = key.substring(0, key.indexOf('@'));
806 jsonResult.put(key, value);
810 if (node.size() > 0) {
811 if (nodeKey.contains("@")) {
812 if (jsonArray == null) {
813 jsonArray = new JSONArray();
815 if (arryKey == null) {
816 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
818 jsonArray.put(decodeContent(node));
819 jsonResult.put(arryKey, jsonArray);
822 jsonResult.put(nodeKey, decodeContent(node));
825 if (isArray && jsonArray.length() > 0) {
826 jsonResult.put(oldValue, jsonArray);
832 value = {"/policyController/getDCAEMSTemplateData.htm"},
833 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
834 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
836 // TreeSet is used to ensure that individual items appear before their containing collection.
837 allManyTrueKeys = new TreeSet<>();
838 ObjectMapper mapper = new ObjectMapper();
839 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
840 JsonNode root = mapper.readTree(request.getReader());
842 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
843 String servicename = value.split("-v")[0];
844 String version = null;
845 if (value.contains("-v")) {
846 version = value.split("-v")[1];
848 MicroServiceModels returnModel = getAttributeObject(servicename, version);
850 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
851 JSONObject jsonHdDefaultObj = null;
852 if (returnHeaderDefauls != null) {
853 jsonHdDefaultObj = new JSONObject();
854 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
855 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
856 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
857 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
858 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
860 String headDefautlsData = "";
861 if (jsonHdDefaultObj != null) {
862 headDefautlsData = jsonHdDefaultObj.toString();
864 headDefautlsData = "null";
867 // Get all keys with "MANY-true" defined in their value from subAttribute
868 Set<String> allkeys = null;
869 if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
870 JSONObject json = new JSONObject(returnModel.getSub_attributes());
872 allkeys = allManyTrueKeys;
873 allManyTrueKeys = new TreeSet<>();
874 LOGGER.info("allkeys : " + allkeys);
877 // Get element order info
878 String dataOrderInfo = returnModel.getDataOrderInfo();
879 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
880 dataOrderInfo = "\"" + dataOrderInfo + "\"";
882 LOGGER.info("dataOrderInfo : " + dataOrderInfo);
884 String allMnyTrueKeys = "";
885 if (allkeys != null) {
886 allMnyTrueKeys = allkeys.toString();
889 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
891 JSONObject jsonObject = new JSONObject(jsonModel);
893 JSONObject finalJsonObject = null;
894 if (allkeys != null) {
895 Iterator<String> iter = allkeys.iterator();
896 while (iter.hasNext()) {
897 // Convert to array values for MANY-true keys
898 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
899 jsonObject = finalJsonObject;
903 if (finalJsonObject != null) {
904 LOGGER.info(finalJsonObject.toString());
905 jsonModel = finalJsonObject.toString();
908 // get all properties with "MANY-true" defined in Ref_attributes
909 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
910 if (manyTrueProperties != null) {
911 JSONObject jsonObj = new JSONObject(jsonModel);
912 for (String s : manyTrueProperties) {
914 // convert to array element for MANY-true properties
915 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
916 jsonObj = finalJsonObject;
919 if (finalJsonObject != null) {
920 LOGGER.info(finalJsonObject.toString());
921 jsonModel = finalJsonObject.toString();
925 response.setCharacterEncoding("UTF-8");
926 response.setContentType("application / json");
927 request.setCharacterEncoding("UTF-8");
928 List<Object> list = new ArrayList<>();
929 PrintWriter out = response.getWriter();
930 String responseString = mapper.writeValueAsString(returnModel);
934 if ("".equals(allMnyTrueKeys)) {
935 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
936 + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
938 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
939 + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
943 out.write(list.toString());
947 @SuppressWarnings({"unchecked", "rawtypes"})
948 private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
949 Map<String, String> attributeMap = new HashMap<>();
950 Map<String, String> refAttributeMap = new HashMap<>();
951 String attribute = returnModel.getAttributes();
952 if (attribute != null) {
953 attribute = attribute.trim();
955 String refAttribute = returnModel.getRef_attributes();
956 if (refAttribute != null) {
957 refAttribute = refAttribute.trim();
959 String enumAttribute = returnModel.getEnumValues();
960 if (enumAttribute != null) {
961 enumAttribute = enumAttribute.trim();
963 if (!StringUtils.isEmpty(attribute)) {
964 attributeMap = convert(attribute, ",");
966 if (!StringUtils.isEmpty(refAttribute)) {
967 refAttributeMap = convert(refAttribute, ",");
970 Gson gson = new Gson();
972 String subAttributes = returnModel.getSub_attributes();
973 if (subAttributes != null) {
974 subAttributes = subAttributes.trim();
979 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
981 JSONObject object = new JSONObject();
982 JSONArray array = new JSONArray();
984 for (Entry<String, String> keySet : attributeMap.entrySet()) {
985 array = new JSONArray();
986 String value = keySet.getValue();
987 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
989 object.put(keySet.getKey().trim(), array);
991 object.put(keySet.getKey().trim(), value.trim());
995 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
996 array = new JSONArray();
997 String value = keySet.getValue().split(":")[0];
998 if (gsonObject.containsKey(value)) {
999 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1000 array.put(recursiveReference(value, gsonObject, enumAttribute));
1001 object.put(keySet.getKey().trim(), array);
1003 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1006 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1007 array.put(value.trim());
1008 object.put(keySet.getKey().trim(), array);
1010 object.put(keySet.getKey().trim(), value.trim());
1015 return object.toString();
1018 @SuppressWarnings("unchecked")
1019 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
1020 JSONObject object = new JSONObject();
1021 Map<String, String> map;
1022 Object returnClass = subAttributeMap.get(name);
1023 map = (Map<String, String>) returnClass;
1026 for (Entry<String, String> m : map.entrySet()) {
1027 String[] splitValue = m.getValue().split(":");
1028 array = new JSONArray();
1029 if (subAttributeMap.containsKey(splitValue[0])) {
1030 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1031 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1032 object.put(m.getKey().trim(), array);
1034 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1037 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1038 array.put(splitValue[0].trim());
1039 object.put(m.getKey().trim(), array);
1041 object.put(m.getKey().trim(), splitValue[0].trim());
1049 public JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1050 return convertToArrayElement(json, new HashSet<>(), keyValue);
1053 private JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1054 for (String key : json.keySet()) {
1055 Object obj = json.get(key);
1056 if (key.equals(keyValue.trim())) {
1057 if (!(obj instanceof JSONArray)) {
1058 JSONArray newJsonArray = new JSONArray();
1059 newJsonArray.put(obj);
1060 json.put(key, newJsonArray);
1062 LOGGER.info("key : " + key);
1063 LOGGER.info("obj : " + obj);
1064 LOGGER.info("json.get(key) : " + json.get(key));
1065 LOGGER.info("keyValue : " + keyValue);
1066 keys.addAll(json.keySet());
1071 if (obj instanceof JSONObject) {
1072 convertToArrayElement(json.getJSONObject(key), keyValue);
1075 if (obj instanceof JSONArray) {
1076 convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
1083 // call this method to get all MANY-true properties
1084 public Set<String> getManyTrueProperties(String referAttributes) {
1085 LOGGER.info("referAttributes : " + referAttributes);
1086 Set<String> manyTrueProperties = new HashSet<>();
1088 if (referAttributes != null) {
1089 String[] referAarray = referAttributes.split(",");
1090 String[] element = null;
1091 for (int i = 0; i < referAarray.length; i++) {
1092 element = referAarray[i].split("=");
1093 if (element.length > 1 && element[1].contains("MANY-true")) {
1094 manyTrueProperties.add(element[0]);
1099 return manyTrueProperties;
1102 // call this method to start the recursive
1103 private Set<String> getAllKeys(JSONObject json) {
1104 return getAllKeys(json, new HashSet<>());
1107 private Set<String> getAllKeys(JSONArray arr) {
1108 return getAllKeys(arr, new HashSet<>());
1111 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1112 for (int i = 0; i < arr.length(); i++) {
1113 Object obj = arr.get(i);
1114 if (obj instanceof JSONObject)
1115 keys.addAll(getAllKeys(arr.getJSONObject(i)));
1116 if (obj instanceof JSONArray)
1117 keys.addAll(getAllKeys(arr.getJSONArray(i)));
1123 // this method returns a set of keys with "MANY-true" defined in their value.
1124 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1125 for (String key : json.keySet()) {
1126 Object obj = json.get(key);
1127 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
1128 LOGGER.info("key : " + key);
1129 LOGGER.info("obj : " + obj);
1130 allManyTrueKeys.add(key);
1132 if (obj instanceof JSONObject)
1133 keys.addAll(getAllKeys(json.getJSONObject(key)));
1134 if (obj instanceof JSONArray)
1135 keys.addAll(getAllKeys(json.getJSONArray(key)));
1142 value = {"/policyController/getModelServiceVersioneData.htm"},
1143 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1144 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
1145 throws IOException {
1146 ObjectMapper mapper = new ObjectMapper();
1147 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1148 JsonNode root = mapper.readTree(request.getReader());
1150 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1151 String servicename = value.split("-v")[0];
1152 Set<String> returnList = getVersionList(servicename);
1154 response.setCharacterEncoding("UTF-8");
1155 response.setContentType("application / json");
1156 request.setCharacterEncoding("UTF-8");
1157 List<Object> list = new ArrayList<>();
1158 PrintWriter out = response.getWriter();
1159 String responseString = mapper.writeValueAsString(returnList);
1160 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}");
1162 out.write(list.toString());
1166 private Set<String> getVersionList(String name) {
1167 MicroServiceModels workingModel;
1168 Set<String> list = new HashSet<>();
1169 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1170 for (int i = 0; i < microServiceModelsData.size(); i++) {
1171 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1172 if (workingModel.getVersion() != null) {
1173 list.add(workingModel.getVersion());
1175 list.add("Default");
1181 private MicroServiceModels getAttributeObject(String name, String version) {
1182 MicroServiceModels workingModel = new MicroServiceModels();
1183 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1184 for (int i = 0; i < microServiceModelsData.size(); i++) {
1185 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1186 if (version != null) {
1187 if (workingModel.getVersion() != null) {
1188 if (workingModel.getVersion().equals(version)) {
1189 return workingModel;
1192 return workingModel;
1195 return workingModel;
1199 return workingModel;
1202 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
1203 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName",
1208 value = {"/get_DCAEPriorityValues"},
1209 method = {org.springframework.web.bind.annotation.RequestMethod.GET},
1210 produces = MediaType.APPLICATION_JSON_VALUE)
1211 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
1213 Map<String, Object> model = new HashMap<>();
1214 ObjectMapper mapper = new ObjectMapper();
1215 List<String> priorityList = new ArrayList<>();
1217 for (int i = 1; i < priorityCount; i++) {
1218 priorityList.add(String.valueOf(i));
1220 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1221 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1222 JSONObject j = new JSONObject(msg);
1223 response.getWriter().write(j.toString());
1224 } catch (Exception e) {
1229 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1230 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1231 Object policyData = policyAdapter.getPolicyData();
1232 PolicyType policy = (PolicyType) policyData;
1233 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1234 String policyNameValue =
1235 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
1236 policyAdapter.setPolicyName(policyNameValue);
1237 String description = "";
1239 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1240 } catch (Exception e) {
1241 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
1242 description = policy.getDescription();
1244 policyAdapter.setPolicyDescription(description);
1245 // Get the target data under policy.
1246 TargetType target = policy.getTarget();
1247 if (target != null) {
1248 // Under target we have AnyOFType
1249 List<AnyOfType> anyOfList = target.getAnyOf();
1250 if (anyOfList != null) {
1251 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1252 while (iterAnyOf.hasNext()) {
1253 AnyOfType anyOf = iterAnyOf.next();
1254 // Under AnyOFType we have AllOFType
1255 List<AllOfType> allOfList = anyOf.getAllOf();
1256 if (allOfList != null) {
1257 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1258 while (iterAllOf.hasNext()) {
1259 AllOfType allOf = iterAllOf.next();
1260 // Under AllOFType we have Match
1261 List<MatchType> matchList = allOf.getMatch();
1262 if (matchList != null) {
1263 Iterator<MatchType> iterMatch = matchList.iterator();
1264 while (matchList.size() > 1 && iterMatch.hasNext()) {
1265 MatchType match = iterMatch.next();
1267 // Under the match we have attribute value and
1268 // attributeDesignator. So,finally down to the actual attribute.
1270 AttributeValueType attributeValue = match.getAttributeValue();
1271 String value = (String) attributeValue.getContent().get(0);
1272 AttributeDesignatorType designator = match.getAttributeDesignator();
1273 String attributeId = designator.getAttributeId();
1274 // First match in the target is OnapName, so set that value.
1275 if ("ONAPName".equals(attributeId)) {
1276 policyAdapter.setOnapName(value);
1278 if ("ConfigName".equals(attributeId)) {
1279 policyAdapter.setConfigName(value);
1281 if ("uuid".equals(attributeId)) {
1282 policyAdapter.setUuid(value);
1284 if ("location".equals(attributeId)) {
1285 policyAdapter.setLocation(value);
1287 if ("RiskType".equals(attributeId)) {
1288 policyAdapter.setRiskType(value);
1290 if ("RiskLevel".equals(attributeId)) {
1291 policyAdapter.setRiskLevel(value);
1293 if ("guard".equals(attributeId)) {
1294 policyAdapter.setGuard(value);
1296 if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
1297 PolicyController controller = new PolicyController();
1298 String newDate = controller.convertDate(value);
1299 policyAdapter.setTtlDate(newDate);
1302 readFile(policyAdapter, entity);
1315 * @param str the str
1316 * @param split the split
1319 public Map<String, String> convert(String str, String split) {
1320 Map<String, String> map = new HashMap<>();
1321 for (final String entry : str.split(split)) {
1322 String[] parts = entry.split("=");
1323 map.put(parts[0], parts[1]);
1331 * @param policyAdapter the policy adapter
1332 * @param entity the entity
1334 @SuppressWarnings("unchecked")
1335 public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1336 String policyScopeName = null;
1337 ObjectMapper mapper = new ObjectMapper();
1339 DCAEMicroServiceObject msBody =
1340 mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1341 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1342 policyAdapter.setPolicyScope(policyScopeName);
1344 policyAdapter.setPriority(msBody.getPriority());
1346 if (msBody.getVersion() != null) {
1347 policyAdapter.setServiceType(msBody.getService());
1348 policyAdapter.setVersion(msBody.getVersion());
1350 policyAdapter.setServiceType(msBody.getService());
1353 LinkedHashMap<String, ?> content = (LinkedHashMap<String, ?>) msBody.getUiContent();
1354 if (content == null) {
1355 content = (LinkedHashMap<String, ?>) msBody.getContent();
1357 if (content != null) {
1358 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1359 LinkedHashMap<String, ?> map = content;
1360 readRecursivlyJSONContent(map, data);
1361 policyAdapter.setRuleData(data);
1364 } catch (Exception e) {
1370 @SuppressWarnings({"rawtypes", "unchecked"})
1371 public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) {
1372 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1373 Object key = iterator.next();
1374 Object value = map.get(key);
1375 if (value instanceof LinkedHashMap<?, ?>) {
1376 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1377 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1378 for (Entry<String, Object> entry : secondObjec.entrySet()) {
1379 data.put(key + "." + entry.getKey(), entry.getValue());
1381 } else if (value instanceof ArrayList) {
1382 ArrayList<?> jsonArrayVal = (ArrayList<?>) value;
1383 for (int i = 0; i < jsonArrayVal.size(); i++) {
1384 Object arrayvalue = jsonArrayVal.get(i);
1385 if (arrayvalue instanceof LinkedHashMap<?, ?>) {
1386 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1387 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1388 for (Entry<String, Object> entry : newData.entrySet()) {
1389 data.put(key + "@" + i + "." + entry.getKey(), entry.getValue());
1391 } else if (arrayvalue instanceof ArrayList) {
1392 ArrayList<?> jsonArrayVal1 = (ArrayList<?>) value;
1393 for (int j = 0; j < jsonArrayVal1.size(); j++) {
1394 Object arrayvalue1 = jsonArrayVal1.get(i);
1395 data.put(key + "@" + j, arrayvalue1.toString());
1398 data.put(key + "@" + i, arrayvalue.toString());
1402 data.put(key.toString(), value.toString());
1407 public String getPolicyScope(String value) {
1408 List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1409 if (groupList != null && !groupList.isEmpty()) {
1410 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1411 return pScope.getGroupName();
1416 // Convert the map values and set into JSON body
1417 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1418 Map<String, String> attribute = new HashMap<>();
1422 for (Entry<String, String> entry : attributesMap.entrySet()) {
1423 key = entry.getKey();
1424 value = entry.getValue();
1425 attribute.put(key, value);
1427 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1428 key = entryRef.getKey();
1429 value = entryRef.getValue();
1430 attribute.put(key, value);
1432 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1433 key = entryList.getKey();
1434 value = entryList.getValue();
1435 attribute.put(key, value);
1437 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()) {
1438 key = arrayList.getKey();
1440 for (Object textList : arrayList.getValue()) {
1442 temp = new StringBuilder();
1443 temp.append("[" + textList);
1445 temp.append("," + textList);
1448 attribute.put(key, temp + "]");
1455 value = {"/ms_dictionary/set_MSModelData"},
1456 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1457 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
1458 throws IOException, FileUploadException {
1459 modelList = new ArrayList<>();
1460 dirDependencyList = new ArrayList<>();
1461 classMap = new LinkedHashMap<>();
1462 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1463 boolean zip = false;
1464 boolean yml = false;
1465 String errorMsg = "";
1466 for (FileItem item : items) {
1467 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
1468 this.newModel = new MicroServiceModels();
1470 File file = new File(item.getName());
1471 OutputStream outputStream = new FileOutputStream(file);
1472 IOUtils.copy(item.getInputStream(), outputStream);
1473 outputStream.close();
1474 this.newFile = file.toString();
1475 this.newModel.setModelName(this.newFile.split("-v")[0]);
1477 if (this.newFile.contains("-v")) {
1478 if (item.getName().endsWith(".zip")) {
1479 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1481 } else if (item.getName().endsWith(".yml")) {
1482 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1485 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1488 } catch (Exception e) {
1489 LOGGER.error("Upload error : ", e);
1490 errorMsg = "Upload error:" + e.getMessage();
1496 if (!errorMsg.isEmpty()) {
1498 PrintWriter out = response.getWriter();
1500 response.setCharacterEncoding("UTF-8");
1501 response.setContentType("application / json");
1502 request.setCharacterEncoding("UTF-8");
1504 JSONObject j = new JSONObject();
1505 j.put("errorMsg", errorMsg);
1506 out.write(j.toString());
1510 List<File> fileList = new ArrayList<>();
1511 MSModelUtils msMLUtils = new MSModelUtils(commonClassDao);
1512 this.directory = "model";
1514 extractFolder(this.newFile);
1515 fileList = listModelFiles(this.directory);
1517 errorMsg = msMLUtils.parseTosca(this.newFile);
1518 if (errorMsg != null) {
1519 PrintWriter out = response.getWriter();
1520 response.setCharacterEncoding("UTF-8");
1521 response.setContentType("application / json");
1522 request.setCharacterEncoding("UTF-8");
1523 JSONObject j = new JSONObject();
1524 j.put("errorMsg", errorMsg);
1525 out.write(j.toString());
1530 File file = new File(this.newFile);
1533 String modelType = "";
1536 // Process Main Model file first
1537 classMap = new LinkedHashMap<>();
1538 for (File file : fileList) {
1539 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
1540 retreiveDependency(file.toString(), true);
1544 modelList = createList();
1546 cleanUp(this.newFile);
1550 modelList.add(this.newModel.getModelName());
1551 String className = this.newModel.getModelName();
1552 MSAttributeObject msAttributes = new MSAttributeObject();
1553 msAttributes.setClassName(className);
1555 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
1556 returnAttributeList.put(className, msMLUtils.getAttributeString());
1557 msAttributes.setAttribute(returnAttributeList);
1559 msAttributes.setSubClass(msMLUtils.getRetmap());
1561 msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
1563 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
1565 returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
1566 msAttributes.setRefAttribute(returnReferenceList);
1568 if (msMLUtils.getListConstraints() != "") {
1569 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
1570 String[] listArray = msMLUtils.getListConstraints().split("#");
1571 for (String str : listArray) {
1572 String[] strArr = str.split("=");
1573 if (strArr.length > 1) {
1574 enumList.put(strArr[0], strArr[1]);
1577 msAttributes.setEnumType(enumList);
1580 classMap = new LinkedHashMap<>();
1581 classMap.put(className, msAttributes);
1585 PrintWriter out = response.getWriter();
1587 response.setCharacterEncoding("UTF-8");
1588 response.setContentType("application / json");
1589 request.setCharacterEncoding("UTF-8");
1591 ObjectMapper mapper = new ObjectMapper();
1592 JSONObject j = new JSONObject();
1593 j.put("classListDatas", modelList);
1594 j.put("modelDatas", mapper.writeValueAsString(classMap));
1595 j.put("modelType", modelType);
1596 j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
1597 j.put("ruleFormation", msMLUtils.getJsonRuleFormation());
1599 out.write(j.toString());
1603 * Unzip file and store in the model directory for processing
1605 @SuppressWarnings("rawtypes")
1606 private void extractFolder(String zipFile) {
1608 File file = new File(zipFile);
1610 try (ZipFile zip = new ZipFile(file)) {
1611 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1612 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1613 checkZipDirectory(this.directory);
1614 new File(newPath).mkdir();
1615 Enumeration zipFileEntries = zip.entries();
1617 // Process each entry
1618 while (zipFileEntries.hasMoreElements()) {
1619 // grab a zip file entry
1620 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1621 String currentEntry = entry.getName();
1622 File destFile = new File("model" + File.separator + currentEntry);
1623 File destinationParent = destFile.getParentFile();
1625 destinationParent.mkdirs();
1627 if (!entry.isDirectory()) {
1628 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1630 byte[] data = new byte[BUFFER];
1631 try (FileOutputStream fos = new FileOutputStream(destFile);
1632 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
1633 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1634 dest.write(data, 0, currentByte);
1637 } catch (IOException e) {
1638 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1640 // PLD should I throw e?
1646 if (currentEntry.endsWith(".zip")) {
1647 extractFolder(destFile.getAbsolutePath());
1650 } catch (IOException e) {
1651 LOGGER.error("Failed to unzip model file " + zipFile, e);
1655 private void retreiveDependency(String workingFile, Boolean modelClass) {
1657 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1658 Map<String, MSAttributeObject> tempMap;
1660 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1662 classMap.putAll(tempMap);
1663 LOGGER.info(tempMap);
1669 private List<File> listModelFiles(String directoryName) {
1670 File fileDirectory = new File(directoryName);
1671 List<File> resultList = new ArrayList<>();
1672 File[] fList = fileDirectory.listFiles();
1673 for (File file : fList) {
1674 if (file.isFile()) {
1675 resultList.add(file);
1676 } else if (file.isDirectory()) {
1677 dirDependencyList.add(file.getName());
1678 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1684 public void cleanUp(String path) {
1687 FileUtils.forceDelete(new File(path));
1688 } catch (IOException e) {
1689 LOGGER.error("Failed to delete folder " + path, e);
1694 public void checkZipDirectory(String zipDirectory) {
1695 Path path = Paths.get(zipDirectory);
1697 if (Files.exists(path)) {
1698 cleanUp(zipDirectory);
1702 private List<String> createList() {
1703 List<String> list = new ArrayList<>();
1704 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
1705 if (cMap.getValue().isPolicyTempalate()) {
1706 list.add(cMap.getKey());
1711 if (list.isEmpty()) {
1712 if (classMap.containsKey(this.newModel.getModelName())) {
1713 list.add(this.newModel.getModelName());
1721 public Map<String, String> getAttributesListRefMap() {
1722 return attributesListRefMap;
1725 public Map<String, LinkedList<String>> getArrayTextList() {
1726 return arrayTextList;
1729 public Map<String, String> getSigRules() {
1733 public void setSigRules(Map<String, String> sigRules) {
1734 this.sigRules = sigRules;
1740 class DCAEMicroServiceObject {
1742 private String service;
1743 private String location;
1744 private String uuid;
1745 private String policyName;
1746 private String description;
1747 private String configName;
1748 private String templateVersion;
1749 private String version;
1750 private String priority;
1751 private String policyScope;
1752 private String riskType;
1753 private String riskLevel;
1754 private String guard = null;
1755 private Object uiContent;
1757 public String getGuard() {
1761 public void setGuard(String guard) {
1765 public String getRiskType() {
1769 public void setRiskType(String riskType) {
1770 this.riskType = riskType;
1773 public String getRiskLevel() {
1777 public void setRiskLevel(String riskLevel) {
1778 this.riskLevel = riskLevel;
1781 public String getPolicyScope() {
1785 public void setPolicyScope(String policyScope) {
1786 this.policyScope = policyScope;
1789 public String getPriority() {
1793 public void setPriority(String priority) {
1794 this.priority = priority;
1797 public String getVersion() {
1801 public void setVersion(String version) {
1802 this.version = version;
1805 private Object content;
1807 public String getPolicyName() {
1811 public void setPolicyName(String policyName) {
1812 this.policyName = policyName;
1815 public String getDescription() {
1819 public void setDescription(String description) {
1820 this.description = description;
1823 public String getConfigName() {
1827 public void setConfigName(String configName) {
1828 this.configName = configName;
1831 public Object getContent() {
1835 public void setContent(Object content) {
1836 this.content = content;
1839 public String getService() {
1843 public void setService(String service) {
1844 this.service = service;
1847 public String getLocation() {
1851 public void setLocation(String location) {
1852 this.location = location;
1855 public String getUuid() {
1859 public void setUuid(String uuid) {
1863 public String getTemplateVersion() {
1864 return templateVersion;
1867 public void setTemplateVersion(String templateVersion) {
1868 this.templateVersion = templateVersion;
1871 public Object getUiContent() {
1875 public void setUiContent(Object uiContent) {
1876 this.uiContent = uiContent;