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;
24 import com.att.research.xacml.util.XACMLProperties;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.DeserializationFeature;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.fasterxml.jackson.databind.ObjectWriter;
30 import com.fasterxml.jackson.databind.node.ArrayNode;
31 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
32 import com.fasterxml.jackson.databind.node.ObjectNode;
33 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;
62 import javax.json.Json;
63 import javax.json.JsonArray;
64 import javax.json.JsonArrayBuilder;
65 import javax.json.JsonObject;
66 import javax.json.JsonObjectBuilder;
67 import javax.json.JsonReader;
68 import javax.json.JsonValue;
69 import javax.servlet.http.HttpServletRequest;
70 import javax.servlet.http.HttpServletResponse;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
78 import org.apache.commons.compress.utils.IOUtils;
79 import org.apache.commons.fileupload.FileItem;
80 import org.apache.commons.fileupload.FileUploadException;
81 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
82 import org.apache.commons.fileupload.servlet.ServletFileUpload;
83 import org.apache.commons.io.FileUtils;
84 import org.apache.commons.lang.StringUtils;
85 import org.json.JSONArray;
86 import org.json.JSONObject;
87 import org.onap.policy.common.logging.flexlogger.FlexLogger;
88 import org.onap.policy.common.logging.flexlogger.Logger;
89 import org.onap.policy.rest.XACMLRestProperties;
90 import org.onap.policy.rest.adapter.PolicyRestAdapter;
91 import org.onap.policy.rest.dao.CommonClassDao;
92 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
93 import org.onap.policy.rest.jpa.MicroServiceModels;
94 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
95 import org.onap.policy.rest.jpa.PolicyEntity;
96 import org.onap.policy.rest.util.MSAttributeObject;
97 import org.onap.policy.rest.util.MSModelUtils;
98 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
99 import org.onap.portalsdk.core.controller.RestrictedBaseController;
100 import org.onap.portalsdk.core.web.support.JsonMessage;
101 import org.springframework.beans.factory.annotation.Autowired;
102 import org.springframework.http.MediaType;
103 import org.springframework.stereotype.Controller;
104 import org.springframework.web.bind.annotation.RequestMapping;
105 import org.springframework.web.servlet.ModelAndView;
109 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
110 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
112 private static CommonClassDao commonClassDao;
114 public static CommonClassDao getCommonClassDao() {
115 return commonClassDao;
118 public static void setCommonClassDao(CommonClassDao commonClassDao) {
119 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
122 private MicroServiceModels newModel;
123 private String newFile;
124 private String directory;
125 private List<String> modelList = new ArrayList<>();
126 private List<String> dirDependencyList = new ArrayList<>();
127 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
128 String referenceAttributes;
129 String attributeString;
130 Set<String> allManyTrueKeys = null;
131 private Map<String, String> sigRules = null;
133 public static final String DATATYPE = "data_types.policy.data.";
134 public static final String PROPERTIES = ".properties.";
135 public static final String TYPE = ".type";
136 public static final String STRING = "string";
137 public static final String INTEGER = "integer";
138 public static final String LIST = "list";
139 public static final String DEFAULT = ".default";
140 public static final String REQUIRED = ".required";
141 public static final String MATCHABLE = ".matchable";
142 public static final String MANYFALSE = ":MANY-false";
143 private static final Pattern PATTERN = Pattern.compile("[A][0-9]");
144 private static final String POLICYJSON = "policyJSON";
147 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) {
148 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
151 public CreateDcaeMicroServiceController() {
155 protected PolicyRestAdapter policyAdapter = null;
156 private int priorityCount;
157 private Map<String, String> attributesListRefMap = new HashMap<>();
158 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
159 private Map<String, String> jsonStringValues = new HashMap<>();
161 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
163 String jsonContent = null;
165 LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
167 String tempJson = root.get(POLICYJSON).toString();
168 JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString());
169 if (policyJSON != null) {
170 tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString();
172 // ---replace empty value with the value below before calling decodeContent method.
173 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
174 LOGGER.info("dummyValue:" + dummyValue);
176 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
177 ObjectMapper mapper = new ObjectMapper();
178 JsonNode tempJsonNode = mapper.readTree(tempJson);
179 jsonContent = decodeContent(tempJsonNode).toString();
180 constructJson(policyData, jsonContent, dummyValue);
181 } catch (Exception e) {
182 LOGGER.error("Error while decoding microservice content", e);
185 // ----Here is the final step to reset the original value back.
186 if (policyData.getJsonBody() != null && jsonStringValues.size() > 0) {
187 String contentBody = policyData.getJsonBody();
188 JSONObject contentJson = new JSONObject(contentBody);
189 JSONObject content = contentJson.getJSONObject("content");
190 content = setOriginalJsonObject(content, jsonStringValues);
191 contentJson.put("content", content);
192 policyData.setJsonBody(contentJson.toString());
198 private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
199 for (Object key : jsonObj.keySet()) {
200 String keyStr = (String) key;
201 Object keyvalue = jsonObj.get(keyStr);
202 if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) {
203 jsonStringValues.put(keyStr, keyvalue.toString());
204 // --- set default value
205 jsonObj.put(keyStr, "JSON_STRING");
208 // for nested objects iteration if required
209 if (keyvalue instanceof JSONObject) {
210 saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
211 // --- set default value
212 jsonObj.put(keyStr, "JSON_STRING");
215 if (keyvalue instanceof JSONArray) {
216 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
217 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
218 saveOriginalJsonObject(temp, jsonStringValues);
226 private JSONObject setOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
227 for (Object key : jsonObj.keySet()) {
228 String keyStr = (String) key;
229 Object keyvalue = jsonObj.get(keyStr);
230 String originalValue = getOriginalValue(keyStr);
231 if (originalValue != null) {
232 jsonObj.put(keyStr, originalValue);
235 // for nested objects iteration if required
236 if (keyvalue instanceof JSONObject) {
237 setOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
238 jsonObj.put(keyStr, originalValue);
241 if (keyvalue instanceof JSONArray) {
242 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
243 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
244 setOriginalJsonObject(temp, jsonStringValues);
252 private GroupPolicyScopeList getPolicyObject(String policyScope) {
253 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
256 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue)
258 ObjectWriter om = new ObjectMapper().writer();
260 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
261 MicroServiceModels returnModel = new MicroServiceModels();
262 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
263 if (policyAdapter.getServiceType() != null) {
264 microServiceObject.setService(policyAdapter.getServiceType());
265 microServiceObject.setVersion(policyAdapter.getVersion());
266 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
268 if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) {
269 if (policyAdapter.getUuid() != null) {
270 microServiceObject.setUuid(policyAdapter.getUuid());
272 if (policyAdapter.getLocation() != null) {
273 microServiceObject.setLocation(policyAdapter.getLocation());
275 if (policyAdapter.getConfigName() != null) {
276 microServiceObject.setConfigName(policyAdapter.getConfigName());
278 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
279 if (policyScopeValue != null) {
280 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
284 if (policyAdapter.getPolicyName() != null) {
285 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
287 if (policyAdapter.getPolicyDescription() != null) {
288 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
290 if (policyAdapter.getPriority() != null) {
291 microServiceObject.setPriority(policyAdapter.getPriority());
293 microServiceObject.setPriority("9999");
296 if (policyAdapter.getRiskLevel() != null) {
297 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
299 if (policyAdapter.getRiskType() != null) {
300 microServiceObject.setRiskType(policyAdapter.getRiskType());
302 if (policyAdapter.getGuard() != null) {
303 microServiceObject.setGuard(policyAdapter.getGuard());
305 microServiceObject.setContent(jsonContent);
306 String modelName = policyAdapter.getServiceType();
307 String versionName = policyAdapter.getVersion();
308 List<Object> triggerData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version",
309 modelName + ":" + versionName);
310 MicroServiceModels model = null;
311 boolean ruleCheck = false;
312 boolean SymptomRuleCheck = false;
313 if (!triggerData.isEmpty()) {
314 model = (MicroServiceModels) triggerData.get(0);
315 if (model.getRuleFormation() != null) {
316 microServiceObject.setUiContent(jsonContent);
318 if (model.getRuleFormation().contains("@")) {
319 SymptomRuleCheck = true;
324 json = om.writeValueAsString(microServiceObject);
325 } catch (JsonProcessingException e) {
326 LOGGER.error("Error writing out the object", e);
328 LOGGER.info("input json: " + json);
329 LOGGER.info("input jsonContent: " + jsonContent);
330 String cleanJson = cleanUPJson(json);
331 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
333 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
334 LOGGER.info("tempJson: " + tempJson);
335 cleanJson = removeNullAttributes(tempJson);
336 if (cleanJson.contains("\\")) {
337 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\"}, new String[] {""});
339 policyAdapter.setJsonBody(cleanJson);
341 ObjectMapper mapper = new ObjectMapper();
342 JsonNode tempJsonNode = mapper.readTree(cleanJson);
344 // JsonNode tempJsonNode = mapper.readTree(cleanJson);
345 ObjectNode finalJson = (ObjectNode) tempJsonNode;
346 JsonNode object = tempJsonNode.get("content");
347 String primaryKey1 = model.getRuleFormation();
348 String[] primaryKeyForSignatures = primaryKey1.split("@");
349 for (String primaryKeyForSignature : primaryKeyForSignatures) {
350 String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
351 JsonNode triggerSig = object.get(primarykeyAlarm);
352 sigRules = new HashMap<>();
353 String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
354 StringBuilder sb = null;
355 if (triggerSig instanceof ArrayNode) {
356 for (int i = 0; i < triggerSig.size(); i++) {
357 sb = new StringBuilder();
358 parseData(triggerSig.get(i), parseKey);
360 List<?> keyList = new ArrayList<>(sigRules.keySet());
361 for (int j = keyList.size() - 1; j >= 0; j--) {
362 String key = (String) keyList.get(j);
363 String jsonNode = sigRules.get(key);
364 constructRule(sb, jsonNode, sigRules);
366 sb.append(")").toString();
367 putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
368 sigRules = new HashMap<>();
371 sb = new StringBuilder();
372 parseData(triggerSig, parseKey);
375 policyAdapter.setJsonBody(finalJson.toString());
377 return policyAdapter;
380 private JsonNode putRuletoJson(JsonNode tmpJsonNode, int item, StringBuilder sb, String parseKey,
382 JsonNode tmp = tmpJsonNode;
383 ObjectNode objectNode = (ObjectNode) tmp;
384 JsonNode jsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
385 JsonNode tempRuleJsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
386 String[] tempSt = parseKey.split("\\.");
387 for (String value : tempSt) {
388 if (value.contains("[")) {
389 if (tempRuleJsonNode instanceof ArrayNode) {
390 JsonNode tempRuleNode = tempRuleJsonNode.get(item);
391 ((ArrayNode) tempRuleJsonNode).removeAll();
392 ((ArrayNode) tempRuleJsonNode).add(tempRuleNode);
393 objectNode = (ObjectNode) tempRuleJsonNode.get(item);
395 String key = value.substring(0, value.indexOf('['));
396 objectNode.remove(key);
397 objectNode.put(key, sb.toString());
400 jsonNode = jsonNode.get(value);
401 if (jsonNode instanceof ArrayNode) {
402 tempRuleJsonNode = jsonNode;
403 jsonNode = jsonNode.get(item);
410 public boolean checkPattern(String patternString) {
411 return PATTERN.matcher(patternString).find();
418 * @param jsonNode the json node
419 * @param sigRules2 the sig rules 2
421 public void constructRule(StringBuilder sb, String jsonNode, Map<String, String> sigRules2) {
423 String cleanJsonNode = jsonNode.replace("\"\"", " ");
424 cleanJsonNode = cleanJsonNode.replaceAll("\"", "");
425 cleanJsonNode = cleanJsonNode.replaceAll("\\(", "");
426 cleanJsonNode = cleanJsonNode.replaceAll("\\)", "");
427 boolean flag = false;
428 if (cleanJsonNode.contains("OR")) {
432 for (String rowValue : cleanJsonNode.split(" ")) {
433 if (checkPattern(rowValue)) {
434 String value = sigRules2.get(rowValue);
435 LOGGER.info(" Value is:" + value);
436 constructRule(sb, value, sigRules2);
438 if ((count == 0) && (!("AND").equals(rowValue)) && (!("OR").equals(rowValue))) {
442 LOGGER.info(" " + rowValue + " ");
443 sb.append(" " + rowValue + " ");
444 if (count % 3 == 0) {
458 * @param jsonNode the json node
459 * @param string the string
461 public void parseData(JsonNode jsonNode, String string) {
462 if (string.contains(".")) {
463 String firstIndex = string.substring(0, string.indexOf('.'));
464 JsonNode signtures = jsonNode.get(firstIndex);
465 String subIndex = string.substring(firstIndex.length() + 1);
466 if (signtures instanceof ArrayNode) {
467 for (int i = 0; i < signtures.size(); i++) {
468 parseData(signtures.get(i), subIndex);
471 parseData(signtures, subIndex);
474 if (string.contains("[")) {
475 String ruleIndex = string.substring(0, string.indexOf('['));
476 String[] keys = string.substring(string.indexOf('[') + 1, string.lastIndexOf(']')).split(",");
477 String key = "A" + Integer.valueOf(sigRules.size() + 1);
478 JsonNode node = jsonNode.get(ruleIndex);
479 StringBuilder sb = new StringBuilder("(");
480 for (int i = 0; i < keys.length; i++) {
481 sb.append(node.get(keys[i].trim()));
484 sigRules.put(key, sb.toString());
489 public String removeNullAttributes(String cleanJson) {
490 ObjectMapper mapper = new ObjectMapper();
493 JsonNode rootNode = mapper.readTree(cleanJson);
494 JsonNode returnNode = mapper.readTree(cleanJson);
495 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
496 boolean remove = false;
497 JsonObject removed = null;
498 boolean contentChanged = false;
499 while (fieldsIterator.hasNext()) {
500 Map.Entry<String, JsonNode> field = fieldsIterator.next();
501 final String key = field.getKey();
502 final JsonNode value = field.getValue();
503 if ("content".equalsIgnoreCase(key)) {
504 String contentStr = value.toString();
505 try (JsonReader reader = Json.createReader(new StringReader(contentStr))) {
506 JsonObject jsonContent = reader.readObject();
507 removed = removeNull(jsonContent);
508 if (!jsonContent.toString().equals(removed.toString())) {
509 contentChanged = true;
513 if (value == null || value.isNull()) {
514 ((ObjectNode) returnNode).remove(key);
519 cleanJson = returnNode.toString();
521 if (value == null || value.isNull()) {
522 ((ObjectNode) returnNode).remove(key);
527 cleanJson = returnNode.toString();
530 if (contentChanged) {
531 // set modified content to cleanJson
532 JSONObject jObject = new JSONObject(cleanJson);
533 jObject.put("content", removed.toString());
534 cleanJson = cleanUPJson(jObject.toString());
537 } catch (IOException e) {
538 LOGGER.error("Error writing out the JsonNode", e);
544 * To verify if it is a JSON string. If it is, then return its original value.
546 * @param key holds the values
549 private String getOriginalValue(String key) {
550 for (String k : jsonStringValues.keySet()) {
551 if (k.contains("@")) {
552 String[] arrOfKeys = k.split("@");
553 for (int i = 0; i < arrOfKeys.length; i++) {
554 if (arrOfKeys[i].contains(".")) {
555 arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
556 if (arrOfKeys[i].equals(key)) {
557 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
558 new String[] {"\\\""});
563 if (k.endsWith(key)) {
564 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
571 public JsonArray removeNull(JsonArray array) {
572 JsonArrayBuilder builder = Json.createArrayBuilder();
574 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
575 JsonValue value = it.next();
576 switch (value.getValueType()) {
578 JsonArray a = removeNull(array.getJsonArray(i));
583 JsonObject object = removeNull(array.getJsonObject(i));
584 if (!object.isEmpty())
588 String s = array.getString(i);
589 if (s != null && !s.isEmpty())
593 builder.add(array.getJsonNumber(i));
597 builder.add(array.getBoolean(i));
603 return builder.build();
606 public JsonObject removeNull(JsonObject obj) {
607 JsonObjectBuilder builder = Json.createObjectBuilder();
608 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
609 Entry<String, JsonValue> e = it.next();
610 String key = e.getKey();
611 JsonValue value = e.getValue();
612 switch (value.getValueType()) {
614 JsonArray array = removeNull(obj.getJsonArray(key));
615 if (!array.isEmpty())
616 builder.add(key, array);
619 JsonObject object = removeNull(obj.getJsonObject(key));
620 if (!object.isEmpty()) {
621 if (!jsonStringValues.isEmpty()) {
622 String originalValue = getOriginalValue(key);
623 if (originalValue != null) {
624 builder.add(key, object.toString());
628 builder.add(key, object);
632 String s = obj.getString(key);
633 if (s != null && !s.isEmpty()) {
634 if (!jsonStringValues.isEmpty()) {
635 String originalValue = getOriginalValue(key);
636 if (originalValue != null) {
637 s = getOriginalValue(key);
644 builder.add(key, obj.getJsonNumber(key));
648 builder.add(key, obj.getBoolean(key));
654 return builder.build();
657 public String cleanUPJson(String json) {
658 String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
659 new String[] {"\\", "\\", "\\"});
660 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
662 StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"});
664 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""},
665 new String[] {"\"", "\"", "[{", "}]"});
666 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[{", "}]\""}, new String[] {"[{", "}]"});
667 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
668 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"{", "}\""}, 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[] {"[", "]"});
678 public JSONObject decodeContent(JsonNode jsonNode) {
679 Iterator<JsonNode> jsonElements = jsonNode.elements();
680 Iterator<String> jsonKeys = jsonNode.fieldNames();
681 Map<String, String> element = new TreeMap<>();
682 while (jsonElements.hasNext() && jsonKeys.hasNext()) {
683 element.put(jsonKeys.next(), jsonElements.next().toString());
685 JSONObject jsonResult = new JSONObject();
686 JSONArray jsonArray = null;
687 String oldValue = null;
688 String nodeKey = null;
689 String arryKey = null;
690 Boolean isArray = false;
691 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
692 ObjectNode node = nodeFactory.objectNode();
693 String prevKey = null;
695 for (Entry<String, String> entry : element.entrySet()) {
696 String key = entry.getKey();
697 String value = entry.getValue();
698 if (key.contains(".")) {
699 presKey = key.substring(0, key.indexOf('.'));
700 } else if (key.contains("@")) {
701 presKey = key.substring(0, key.indexOf('@'));
705 // first check if we are different from old.
706 LOGGER.info(key + "\n");
707 if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".")
708 && oldValue != null) {
709 if (!oldValue.equals(key.substring(0, key.indexOf('@')))) {
710 jsonResult.put(oldValue, jsonArray);
711 jsonArray = new JSONArray();
713 } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) {
714 jsonResult.put(oldValue, jsonArray);
716 jsonArray = new JSONArray();
721 if (key.contains(".")) {
722 if (nodeKey == null) {
723 nodeKey = key.substring(0, key.indexOf('.'));
725 if (nodeKey.equals(key.substring(0, key.indexOf('.')))) {
726 node.put(key.substring(key.indexOf('.') + 1), value);
728 if (node.size() != 0) {
729 if (nodeKey.contains("@")) {
730 if (arryKey == null) {
731 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
733 if (nodeKey.endsWith("@0")) {
735 jsonArray = new JSONArray();
737 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
738 jsonArray.put(decodeContent(node));
740 if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@'))))
741 || !key.contains("@")) {
742 jsonResult.put(arryKey, jsonArray);
743 jsonArray = new JSONArray();
745 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
748 jsonResult.put(nodeKey, decodeContent(node));
750 node = nodeFactory.objectNode();
752 nodeKey = key.substring(0, key.indexOf('.'));
753 if (nodeKey.contains("@")) {
754 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
756 node.put(key.substring(key.indexOf('.') + 1), value);
759 if (node.size() != 0) {
760 if (nodeKey.contains("@")) {
761 if (arryKey == null) {
762 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
764 if (nodeKey.endsWith("@0")) {
766 jsonArray = new JSONArray();
768 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
769 jsonArray.put(decodeContent(node));
771 jsonResult.put(arryKey, jsonArray);
772 jsonArray = new JSONArray();
773 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
776 jsonResult.put(nodeKey, decodeContent(node));
778 node = nodeFactory.objectNode();
780 if (key.contains("@")) {
782 if (key.endsWith("@0") || jsonArray == null) {
783 jsonArray = new JSONArray();
785 } else if (!key.contains("@")) {
789 if (oldValue == null) {
790 oldValue = key.substring(0, key.indexOf('@'));
792 if (oldValue != prevKey) {
793 oldValue = key.substring(0, key.indexOf('@'));
795 if (oldValue.equals(key.substring(0, key.indexOf('@')))) {
796 jsonArray.put(value);
798 jsonResult.put(oldValue, jsonArray);
799 jsonArray = new JSONArray();
801 oldValue = key.substring(0, key.indexOf('@'));
803 jsonResult.put(key, value);
807 if (node.size() > 0) {
808 if (nodeKey.contains("@")) {
809 if (jsonArray == null) {
810 jsonArray = new JSONArray();
812 if (arryKey == null) {
813 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
815 jsonArray.put(decodeContent(node));
816 jsonResult.put(arryKey, jsonArray);
819 jsonResult.put(nodeKey, decodeContent(node));
822 if (isArray && jsonArray.length() > 0) {
823 jsonResult.put(oldValue, jsonArray);
828 @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"},
829 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
830 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
832 // TreeSet is used to ensure that individual items appear before their containing collection.
833 allManyTrueKeys = new TreeSet<>();
834 ObjectMapper mapper = new ObjectMapper();
835 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
836 JsonNode root = mapper.readTree(request.getReader());
838 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
839 String servicename = value.split("-v")[0];
840 String version = null;
841 if (value.contains("-v")) {
842 version = value.split("-v")[1];
844 MicroServiceModels returnModel = getAttributeObject(servicename, version);
846 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
847 JSONObject jsonHdDefaultObj = null;
848 if (returnHeaderDefauls != null) {
849 jsonHdDefaultObj = new JSONObject();
850 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
851 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
852 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
853 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
854 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
856 String headDefautlsData = "";
857 if (jsonHdDefaultObj != null) {
858 headDefautlsData = jsonHdDefaultObj.toString();
860 headDefautlsData = "null";
863 // Get all keys with "MANY-true" defined in their value from subAttribute
864 Set<String> allkeys = null;
865 if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
866 JSONObject json = new JSONObject(returnModel.getSub_attributes());
868 allkeys = allManyTrueKeys;
869 allManyTrueKeys = new TreeSet<>();
870 LOGGER.info("allkeys : " + allkeys);
873 // Get element order info
874 String dataOrderInfo = returnModel.getDataOrderInfo();
875 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
876 dataOrderInfo = "\"" + dataOrderInfo + "\"";
878 LOGGER.info("dataOrderInfo : " + dataOrderInfo);
880 String allMnyTrueKeys = "";
881 if (allkeys != null) {
882 allMnyTrueKeys = allkeys.toString();
885 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
887 JSONObject jsonObject = new JSONObject(jsonModel);
889 JSONObject finalJsonObject = null;
890 if (allkeys != null) {
891 Iterator<String> iter = allkeys.iterator();
892 while (iter.hasNext()) {
893 // Convert to array values for MANY-true keys
894 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
895 jsonObject = finalJsonObject;
899 if (finalJsonObject != null) {
900 LOGGER.info(finalJsonObject.toString());
901 jsonModel = finalJsonObject.toString();
904 // get all properties with "MANY-true" defined in Ref_attributes
905 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
906 if (manyTrueProperties != null) {
907 JSONObject jsonObj = new JSONObject(jsonModel);
908 for (String s : manyTrueProperties) {
910 // convert to array element for MANY-true properties
911 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
912 jsonObj = finalJsonObject;
915 if (finalJsonObject != null) {
916 LOGGER.info(finalJsonObject.toString());
917 jsonModel = finalJsonObject.toString();
921 response.setCharacterEncoding("UTF-8");
922 response.setContentType("application / json");
923 request.setCharacterEncoding("UTF-8");
924 List<Object> list = new ArrayList<>();
925 PrintWriter out = response.getWriter();
926 String responseString = mapper.writeValueAsString(returnModel);
930 if ("".equals(allMnyTrueKeys)) {
931 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
932 + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
934 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
935 + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
939 out.write(list.toString());
943 @SuppressWarnings({"unchecked", "rawtypes"})
944 private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
945 Map<String, String> attributeMap = new HashMap<>();
946 Map<String, String> refAttributeMap = new HashMap<>();
947 String attribute = returnModel.getAttributes();
948 if (attribute != null) {
949 attribute = attribute.trim();
951 String refAttribute = returnModel.getRef_attributes();
952 if (refAttribute != null) {
953 refAttribute = refAttribute.trim();
955 String enumAttribute = returnModel.getEnumValues();
956 if (enumAttribute != null) {
957 enumAttribute = enumAttribute.trim();
959 if (!StringUtils.isEmpty(attribute)) {
960 attributeMap = convert(attribute, ",");
962 if (!StringUtils.isEmpty(refAttribute)) {
963 refAttributeMap = convert(refAttribute, ",");
966 Gson gson = new Gson();
968 String subAttributes = returnModel.getSub_attributes();
969 if (subAttributes != null) {
970 subAttributes = subAttributes.trim();
975 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
977 JSONObject object = new JSONObject();
978 JSONArray array = new JSONArray();
980 for (Entry<String, String> keySet : attributeMap.entrySet()) {
981 array = new JSONArray();
982 String value = keySet.getValue();
983 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
985 object.put(keySet.getKey().trim(), array);
987 object.put(keySet.getKey().trim(), value.trim());
991 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
992 array = new JSONArray();
993 String value = keySet.getValue().split(":")[0];
994 if (gsonObject.containsKey(value)) {
995 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
996 array.put(recursiveReference(value, gsonObject, enumAttribute));
997 object.put(keySet.getKey().trim(), array);
999 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1002 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1003 array.put(value.trim());
1004 object.put(keySet.getKey().trim(), array);
1006 object.put(keySet.getKey().trim(), value.trim());
1011 return object.toString();
1014 @SuppressWarnings("unchecked")
1015 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
1016 JSONObject object = new JSONObject();
1017 Map<String, String> map;
1018 Object returnClass = subAttributeMap.get(name);
1019 map = (Map<String, String>) returnClass;
1022 for (Entry<String, String> m : map.entrySet()) {
1023 String[] splitValue = m.getValue().split(":");
1024 array = new JSONArray();
1025 if (subAttributeMap.containsKey(splitValue[0])) {
1026 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1027 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1028 object.put(m.getKey().trim(), array);
1030 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1033 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1034 array.put(splitValue[0].trim());
1035 object.put(m.getKey().trim(), array);
1037 object.put(m.getKey().trim(), splitValue[0].trim());
1046 public JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1047 return convertToArrayElement(json, new HashSet<>(), keyValue);
1050 private JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1051 for (String key : json.keySet()) {
1052 Object obj = json.get(key);
1053 if (key.equals(keyValue.trim())) {
1054 if (!(obj instanceof JSONArray)) {
1055 JSONArray newJsonArray = new JSONArray();
1056 newJsonArray.put(obj);
1057 json.put(key, newJsonArray);
1059 LOGGER.info("key : " + key);
1060 LOGGER.info("obj : " + obj);
1061 LOGGER.info("json.get(key) : " + json.get(key));
1062 LOGGER.info("keyValue : " + keyValue);
1063 keys.addAll(json.keySet());
1068 if (obj instanceof JSONObject) {
1069 convertToArrayElement(json.getJSONObject(key), keyValue);
1072 if (obj instanceof JSONArray) {
1073 convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
1080 // call this method to get all MANY-true properties
1081 public Set<String> getManyTrueProperties(String referAttributes) {
1082 LOGGER.info("referAttributes : " + referAttributes);
1083 Set<String> manyTrueProperties = new HashSet<>();
1085 if (referAttributes != null) {
1086 String[] referAarray = referAttributes.split(",");
1087 String[] element = null;
1088 for (int i = 0; i < referAarray.length; i++) {
1089 element = referAarray[i].split("=");
1090 if (element.length > 1 && element[1].contains("MANY-true")) {
1091 manyTrueProperties.add(element[0]);
1096 return manyTrueProperties;
1099 // call this method to start the recursive
1100 private Set<String> getAllKeys(JSONObject json) {
1101 return getAllKeys(json, new HashSet<>());
1104 private Set<String> getAllKeys(JSONArray arr) {
1105 return getAllKeys(arr, new HashSet<>());
1108 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1109 for (int i = 0; i < arr.length(); i++) {
1110 Object obj = arr.get(i);
1111 if (obj instanceof JSONObject)
1112 keys.addAll(getAllKeys(arr.getJSONObject(i)));
1113 if (obj instanceof JSONArray)
1114 keys.addAll(getAllKeys(arr.getJSONArray(i)));
1120 // this method returns a set of keys with "MANY-true" defined in their value.
1121 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1122 for (String key : json.keySet()) {
1123 Object obj = json.get(key);
1124 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
1125 LOGGER.info("key : " + key);
1126 LOGGER.info("obj : " + obj);
1127 allManyTrueKeys.add(key);
1129 if (obj instanceof JSONObject)
1130 keys.addAll(getAllKeys(json.getJSONObject(key)));
1131 if (obj instanceof JSONArray)
1132 keys.addAll(getAllKeys(json.getJSONArray(key)));
1139 @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"},
1140 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1141 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
1142 throws IOException {
1143 ObjectMapper mapper = new ObjectMapper();
1144 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1145 JsonNode root = mapper.readTree(request.getReader());
1147 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1148 String servicename = value.split("-v")[0];
1149 Set<String> returnList = getVersionList(servicename);
1151 response.setCharacterEncoding("UTF-8");
1152 response.setContentType("application / json");
1153 request.setCharacterEncoding("UTF-8");
1154 List<Object> list = new ArrayList<>();
1155 PrintWriter out = response.getWriter();
1156 String responseString = mapper.writeValueAsString(returnList);
1157 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}");
1159 out.write(list.toString());
1163 private Set<String> getVersionList(String name) {
1164 MicroServiceModels workingModel;
1165 Set<String> list = new HashSet<>();
1166 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1167 for (int i = 0; i < microServiceModelsData.size(); i++) {
1168 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1169 if (workingModel.getVersion() != null) {
1170 list.add(workingModel.getVersion());
1172 list.add("Default");
1178 private MicroServiceModels getAttributeObject(String name, String version) {
1179 MicroServiceModels workingModel = new MicroServiceModels();
1180 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1181 for (int i = 0; i < microServiceModelsData.size(); i++) {
1182 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1183 if (version != null) {
1184 if (workingModel.getVersion() != null) {
1185 if (workingModel.getVersion().equals(version)) {
1186 return workingModel;
1189 return workingModel;
1192 return workingModel;
1196 return workingModel;
1199 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
1200 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName",
1204 @RequestMapping(value = {"/get_DCAEPriorityValues"},
1205 method = {org.springframework.web.bind.annotation.RequestMethod.GET},
1206 produces = MediaType.APPLICATION_JSON_VALUE)
1207 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
1209 Map<String, Object> model = new HashMap<>();
1210 ObjectMapper mapper = new ObjectMapper();
1211 List<String> priorityList = new ArrayList<>();
1213 for (int i = 1; i < priorityCount; i++) {
1214 priorityList.add(String.valueOf(i));
1216 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1217 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1218 JSONObject j = new JSONObject(msg);
1219 response.getWriter().write(j.toString());
1220 } catch (Exception e) {
1225 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1226 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1227 Object policyData = policyAdapter.getPolicyData();
1228 PolicyType policy = (PolicyType) policyData;
1229 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1230 String policyNameValue =
1231 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
1232 policyAdapter.setPolicyName(policyNameValue);
1233 String description = "";
1235 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1236 } catch (Exception e) {
1237 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
1238 description = policy.getDescription();
1240 policyAdapter.setPolicyDescription(description);
1241 // Get the target data under policy.
1242 TargetType target = policy.getTarget();
1243 if (target != null) {
1244 // Under target we have AnyOFType
1245 List<AnyOfType> anyOfList = target.getAnyOf();
1246 if (anyOfList != null) {
1247 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1248 while (iterAnyOf.hasNext()) {
1249 AnyOfType anyOf = iterAnyOf.next();
1250 // Under AnyOFType we have AllOFType
1251 List<AllOfType> allOfList = anyOf.getAllOf();
1252 if (allOfList != null) {
1253 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1254 while (iterAllOf.hasNext()) {
1255 AllOfType allOf = iterAllOf.next();
1256 // Under AllOFType we have Match
1257 List<MatchType> matchList = allOf.getMatch();
1258 if (matchList != null) {
1259 Iterator<MatchType> iterMatch = matchList.iterator();
1260 while (matchList.size() > 1 && iterMatch.hasNext()) {
1261 MatchType match = iterMatch.next();
1263 // Under the match we have attribute value and
1264 // attributeDesignator. So,finally down to the actual attribute.
1266 AttributeValueType attributeValue = match.getAttributeValue();
1267 String value = (String) attributeValue.getContent().get(0);
1268 AttributeDesignatorType designator = match.getAttributeDesignator();
1269 String attributeId = designator.getAttributeId();
1270 // First match in the target is OnapName, so set that value.
1271 if ("ONAPName".equals(attributeId)) {
1272 policyAdapter.setOnapName(value);
1274 if ("ConfigName".equals(attributeId)) {
1275 policyAdapter.setConfigName(value);
1277 if ("uuid".equals(attributeId)) {
1278 policyAdapter.setUuid(value);
1280 if ("location".equals(attributeId)) {
1281 policyAdapter.setLocation(value);
1283 if ("RiskType".equals(attributeId)) {
1284 policyAdapter.setRiskType(value);
1286 if ("RiskLevel".equals(attributeId)) {
1287 policyAdapter.setRiskLevel(value);
1289 if ("guard".equals(attributeId)) {
1290 policyAdapter.setGuard(value);
1292 if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
1293 PolicyController controller = new PolicyController();
1294 String newDate = controller.convertDate(value);
1295 policyAdapter.setTtlDate(newDate);
1298 readFile(policyAdapter, entity);
1311 * @param str the str
1312 * @param split the split
1315 public Map<String, String> convert(String str, String split) {
1316 Map<String, String> map = new HashMap<>();
1317 for (final String entry : str.split(split)) {
1318 String[] parts = entry.split("=");
1319 map.put(parts[0], parts[1]);
1328 * @param policyAdapter the policy adapter
1329 * @param entity the entity
1331 @SuppressWarnings("unchecked")
1332 public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1333 String policyScopeName = null;
1334 ObjectMapper mapper = new ObjectMapper();
1336 DCAEMicroServiceObject msBody =
1337 mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1338 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1339 policyAdapter.setPolicyScope(policyScopeName);
1341 policyAdapter.setPriority(msBody.getPriority());
1343 if (msBody.getVersion() != null) {
1344 policyAdapter.setServiceType(msBody.getService());
1345 policyAdapter.setVersion(msBody.getVersion());
1347 policyAdapter.setServiceType(msBody.getService());
1350 LinkedHashMap<String, ?> content = (LinkedHashMap<String, ?>) msBody.getUiContent();
1351 if (content == null) {
1352 content = (LinkedHashMap<String, ?>) msBody.getContent();
1354 if (content != null) {
1355 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1356 LinkedHashMap<String, ?> map = content;
1357 readRecursivlyJSONContent(map, data);
1358 policyAdapter.setRuleData(data);
1361 } catch (Exception e) {
1367 @SuppressWarnings({"rawtypes", "unchecked"})
1368 public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) {
1369 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1370 Object key = iterator.next();
1371 Object value = map.get(key);
1372 if (value instanceof LinkedHashMap<?, ?>) {
1373 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1374 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1375 for (Entry<String, Object> entry : secondObjec.entrySet()) {
1376 data.put(key + "." + entry.getKey(), entry.getValue());
1378 } else if (value instanceof ArrayList) {
1379 ArrayList<?> jsonArrayVal = (ArrayList<?>) value;
1380 for (int i = 0; i < jsonArrayVal.size(); i++) {
1381 Object arrayvalue = jsonArrayVal.get(i);
1382 if (arrayvalue instanceof LinkedHashMap<?, ?>) {
1383 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1384 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1385 for (Entry<String, Object> entry : newData.entrySet()) {
1386 data.put(key + "@" + i + "." + entry.getKey(), entry.getValue());
1388 } else if (arrayvalue instanceof ArrayList) {
1389 ArrayList<?> jsonArrayVal1 = (ArrayList<?>) value;
1390 for (int j = 0; j < jsonArrayVal1.size(); j++) {
1391 Object arrayvalue1 = jsonArrayVal1.get(i);
1392 data.put(key + "@" + j, arrayvalue1.toString());
1395 data.put(key + "@" + i, arrayvalue.toString());
1399 data.put(key.toString(), value.toString());
1404 public String getPolicyScope(String value) {
1405 List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1406 if (groupList != null && !groupList.isEmpty()) {
1407 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1408 return pScope.getGroupName();
1413 // Convert the map values and set into JSON body
1414 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1415 Map<String, String> attribute = new HashMap<>();
1419 for (Entry<String, String> entry : attributesMap.entrySet()) {
1420 key = entry.getKey();
1421 value = entry.getValue();
1422 attribute.put(key, value);
1424 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1425 key = entryRef.getKey();
1426 value = entryRef.getValue();
1427 attribute.put(key, value);
1429 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1430 key = entryList.getKey();
1431 value = entryList.getValue();
1432 attribute.put(key, value);
1434 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()) {
1435 key = arrayList.getKey();
1437 for (Object textList : arrayList.getValue()) {
1439 temp = new StringBuilder();
1440 temp.append("[" + textList);
1442 temp.append("," + textList);
1445 attribute.put(key, temp + "]");
1451 @RequestMapping(value = {"/ms_dictionary/set_MSModelData"},
1452 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1453 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
1454 throws IOException, FileUploadException {
1455 modelList = new ArrayList<>();
1456 dirDependencyList = new ArrayList<>();
1457 classMap = new LinkedHashMap<>();
1458 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1459 boolean zip = false;
1460 boolean yml = false;
1461 String errorMsg = "";
1462 for (FileItem item : items) {
1463 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
1464 this.newModel = new MicroServiceModels();
1466 File file = new File(item.getName());
1467 OutputStream outputStream = new FileOutputStream(file);
1468 IOUtils.copy(item.getInputStream(), outputStream);
1469 outputStream.close();
1470 this.newFile = file.toString();
1471 this.newModel.setModelName(this.newFile.split("-v")[0]);
1473 if (this.newFile.contains("-v")) {
1474 if (item.getName().endsWith(".zip")) {
1475 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1477 } else if (item.getName().endsWith(".yml")) {
1478 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1481 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1484 } catch (Exception e) {
1485 LOGGER.error("Upload error : ", e);
1486 errorMsg = "Upload error:" + e.getMessage();
1492 if (!errorMsg.isEmpty()) {
1494 PrintWriter out = response.getWriter();
1496 response.setCharacterEncoding("UTF-8");
1497 response.setContentType("application / json");
1498 request.setCharacterEncoding("UTF-8");
1500 JSONObject j = new JSONObject();
1501 j.put("errorMsg", errorMsg);
1502 out.write(j.toString());
1506 List<File> fileList = new ArrayList<>();
1507 MSModelUtils msMLUtils = new MSModelUtils(commonClassDao);
1508 this.directory = "model";
1510 extractFolder(this.newFile);
1511 fileList = listModelFiles(this.directory);
1513 errorMsg = msMLUtils.parseTosca(this.newFile);
1514 if (errorMsg != null) {
1515 PrintWriter out = response.getWriter();
1516 response.setCharacterEncoding("UTF-8");
1517 response.setContentType("application / json");
1518 request.setCharacterEncoding("UTF-8");
1519 JSONObject j = new JSONObject();
1520 j.put("errorMsg", errorMsg);
1521 out.write(j.toString());
1526 File file = new File(this.newFile);
1529 String modelType = "";
1532 // Process Main Model file first
1533 classMap = new LinkedHashMap<>();
1534 for (File file : fileList) {
1535 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
1536 retreiveDependency(file.toString(), true);
1540 modelList = createList();
1542 cleanUp(this.newFile);
1546 modelList.add(this.newModel.getModelName());
1547 String className = this.newModel.getModelName();
1548 MSAttributeObject msAttributes = new MSAttributeObject();
1549 msAttributes.setClassName(className);
1551 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
1552 returnAttributeList.put(className, msMLUtils.getAttributeString());
1553 msAttributes.setAttribute(returnAttributeList);
1555 msAttributes.setSubClass(msMLUtils.getRetmap());
1557 msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
1559 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
1561 returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
1562 msAttributes.setRefAttribute(returnReferenceList);
1564 if (msMLUtils.getListConstraints() != "") {
1565 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
1566 String[] listArray = msMLUtils.getListConstraints().split("#");
1567 for (String str : listArray) {
1568 String[] strArr = str.split("=");
1569 if (strArr.length > 1) {
1570 enumList.put(strArr[0], strArr[1]);
1573 msAttributes.setEnumType(enumList);
1576 classMap = new LinkedHashMap<>();
1577 classMap.put(className, msAttributes);
1581 PrintWriter out = response.getWriter();
1583 response.setCharacterEncoding("UTF-8");
1584 response.setContentType("application / json");
1585 request.setCharacterEncoding("UTF-8");
1587 ObjectMapper mapper = new ObjectMapper();
1588 JSONObject j = new JSONObject();
1589 j.put("classListDatas", modelList);
1590 j.put("modelDatas", mapper.writeValueAsString(classMap));
1591 j.put("modelType", modelType);
1592 j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
1593 j.put("ruleFormation", msMLUtils.getJsonRuleFormation());
1595 out.write(j.toString());
1599 * Unzip file and store in the model directory for processing
1601 @SuppressWarnings("rawtypes")
1602 private void extractFolder(String zipFile) {
1604 File file = new File(zipFile);
1606 try (ZipFile zip = new ZipFile(file)) {
1607 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1608 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1609 checkZipDirectory(this.directory);
1610 new File(newPath).mkdir();
1611 Enumeration zipFileEntries = zip.entries();
1613 // Process each entry
1614 while (zipFileEntries.hasMoreElements()) {
1615 // grab a zip file entry
1616 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1617 String currentEntry = entry.getName();
1618 File destFile = new File("model" + File.separator + currentEntry);
1619 File destinationParent = destFile.getParentFile();
1621 destinationParent.mkdirs();
1623 if (!entry.isDirectory()) {
1624 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1626 byte[] data = new byte[BUFFER];
1627 try (FileOutputStream fos = new FileOutputStream(destFile);
1628 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
1629 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1630 dest.write(data, 0, currentByte);
1633 } catch (IOException e) {
1634 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1636 // PLD should I throw e?
1642 if (currentEntry.endsWith(".zip")) {
1643 extractFolder(destFile.getAbsolutePath());
1646 } catch (IOException e) {
1647 LOGGER.error("Failed to unzip model file " + zipFile, e);
1651 private void retreiveDependency(String workingFile, Boolean modelClass) {
1653 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1654 Map<String, MSAttributeObject> tempMap;
1656 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1658 classMap.putAll(tempMap);
1659 LOGGER.info(tempMap);
1665 private List<File> listModelFiles(String directoryName) {
1666 File fileDirectory = new File(directoryName);
1667 List<File> resultList = new ArrayList<>();
1668 File[] fList = fileDirectory.listFiles();
1669 for (File file : fList) {
1670 if (file.isFile()) {
1671 resultList.add(file);
1672 } else if (file.isDirectory()) {
1673 dirDependencyList.add(file.getName());
1674 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1680 public void cleanUp(String path) {
1683 FileUtils.forceDelete(new File(path));
1684 } catch (IOException e) {
1685 LOGGER.error("Failed to delete folder " + path, e);
1690 public void checkZipDirectory(String zipDirectory) {
1691 Path path = Paths.get(zipDirectory);
1693 if (Files.exists(path)) {
1694 cleanUp(zipDirectory);
1698 private List<String> createList() {
1699 List<String> list = new ArrayList<>();
1700 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
1701 if (cMap.getValue().isPolicyTempalate()) {
1702 list.add(cMap.getKey());
1707 if (list.isEmpty()) {
1708 if (classMap.containsKey(this.newModel.getModelName())) {
1709 list.add(this.newModel.getModelName());
1717 public Map<String, String> getAttributesListRefMap() {
1718 return attributesListRefMap;
1721 public Map<String, LinkedList<String>> getArrayTextList() {
1722 return arrayTextList;
1725 public Map<String, String> getSigRules() {
1729 public void setSigRules(Map<String, String> sigRules) {
1730 this.sigRules = sigRules;
1736 class DCAEMicroServiceObject {
1738 private String service;
1739 private String location;
1740 private String uuid;
1741 private String policyName;
1742 private String description;
1743 private String configName;
1744 private String templateVersion;
1745 private String version;
1746 private String priority;
1747 private String policyScope;
1748 private String riskType;
1749 private String riskLevel;
1750 private String guard = null;
1751 private Object uiContent;
1753 public String getGuard() {
1757 public void setGuard(String guard) {
1761 public String getRiskType() {
1765 public void setRiskType(String riskType) {
1766 this.riskType = riskType;
1769 public String getRiskLevel() {
1773 public void setRiskLevel(String riskLevel) {
1774 this.riskLevel = riskLevel;
1777 public String getPolicyScope() {
1781 public void setPolicyScope(String policyScope) {
1782 this.policyScope = policyScope;
1785 public String getPriority() {
1789 public void setPriority(String priority) {
1790 this.priority = priority;
1793 public String getVersion() {
1797 public void setVersion(String version) {
1798 this.version = version;
1801 private Object content;
1804 public String getPolicyName() {
1808 public void setPolicyName(String policyName) {
1809 this.policyName = policyName;
1812 public String getDescription() {
1816 public void setDescription(String description) {
1817 this.description = description;
1820 public String getConfigName() {
1824 public void setConfigName(String configName) {
1825 this.configName = configName;
1828 public Object getContent() {
1832 public void setContent(Object content) {
1833 this.content = content;
1836 public String getService() {
1840 public void setService(String service) {
1841 this.service = service;
1844 public String getLocation() {
1848 public void setLocation(String location) {
1849 this.location = location;
1852 public String getUuid() {
1856 public void setUuid(String uuid) {
1860 public String getTemplateVersion() {
1861 return templateVersion;
1864 public void setTemplateVersion(String templateVersion) {
1865 this.templateVersion = templateVersion;
1868 public Object getUiContent() {
1872 public void setUiContent(Object uiContent) {
1873 this.uiContent = uiContent;