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;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
82 import org.apache.commons.compress.utils.IOUtils;
83 import org.apache.commons.fileupload.FileItem;
84 import org.apache.commons.fileupload.FileUploadException;
85 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
86 import org.apache.commons.fileupload.servlet.ServletFileUpload;
87 import org.apache.commons.io.FileUtils;
88 import org.apache.commons.lang.StringUtils;
89 import org.json.JSONArray;
90 import org.json.JSONObject;
91 import org.onap.policy.common.logging.flexlogger.FlexLogger;
92 import org.onap.policy.common.logging.flexlogger.Logger;
93 import org.onap.policy.rest.XACMLRestProperties;
94 import org.onap.policy.rest.adapter.PolicyRestAdapter;
95 import org.onap.policy.rest.dao.CommonClassDao;
96 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
97 import org.onap.policy.rest.jpa.MicroServiceModels;
98 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
99 import org.onap.policy.rest.jpa.PolicyEntity;
100 import org.onap.policy.rest.util.MSAttributeObject;
101 import org.onap.policy.rest.util.MSModelUtils;
102 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
103 import org.onap.portalsdk.core.controller.RestrictedBaseController;
104 import org.onap.portalsdk.core.web.support.JsonMessage;
105 import org.springframework.beans.factory.annotation.Autowired;
106 import org.springframework.http.MediaType;
107 import org.springframework.stereotype.Controller;
108 import org.springframework.web.bind.annotation.RequestMapping;
109 import org.springframework.web.servlet.ModelAndView;
113 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
114 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
116 private static CommonClassDao commonClassDao;
118 public static CommonClassDao getCommonClassDao() {
119 return commonClassDao;
122 public static void setCommonClassDao(CommonClassDao commonClassDao) {
123 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
126 private MicroServiceModels newModel;
127 private String newFile;
128 private String directory;
129 private List<String> modelList = new ArrayList<>();
130 private List<String> dirDependencyList = new ArrayList<>();
131 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
132 String referenceAttributes;
133 String attributeString;
134 Set<String> allManyTrueKeys = null;
135 private Map<String, String> sigRules = null;
137 public static final String DATATYPE = "data_types.policy.data.";
138 public static final String PROPERTIES = ".properties.";
139 public static final String TYPE = ".type";
140 public static final String STRING = "string";
141 public static final String INTEGER = "integer";
142 public static final String LIST = "list";
143 public static final String DEFAULT = ".default";
144 public static final String REQUIRED = ".required";
145 public static final String MATCHABLE = ".matchable";
146 public static final String MANYFALSE = ":MANY-false";
147 private static final Pattern PATTERN = Pattern.compile("[A][0-9]");
148 private static final String POLICYJSON = "policyJSON";
151 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) {
152 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
155 public CreateDcaeMicroServiceController() {
159 protected PolicyRestAdapter policyAdapter = null;
160 private int priorityCount;
161 private Map<String, String> attributesListRefMap = new HashMap<>();
162 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
163 private Map<String, String> jsonStringValues = new HashMap<>();
165 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
167 String jsonContent = null;
169 LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
171 String tempJson = root.get(POLICYJSON).toString();
172 JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString());
173 if (policyJSON != null) {
174 tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString();
176 // ---replace empty value with the value below before calling decodeContent method.
177 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
178 LOGGER.info("dummyValue:" + dummyValue);
180 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
181 ObjectMapper mapper = new ObjectMapper();
182 JsonNode tempJsonNode = mapper.readTree(tempJson);
183 jsonContent = decodeContent(tempJsonNode).toString();
184 constructJson(policyData, jsonContent, dummyValue);
185 } catch (Exception e) {
186 LOGGER.error("Error while decoding microservice content", e);
189 // ----Here is the final step to reset the original value back.
190 if (policyData.getJsonBody() != null && jsonStringValues.size() > 0) {
191 String contentBody = policyData.getJsonBody();
192 JSONObject contentJson = new JSONObject(contentBody);
193 JSONObject content = contentJson.getJSONObject("content");
194 content = setOriginalJsonObject(content, jsonStringValues);
195 contentJson.put("content", content);
196 policyData.setJsonBody(contentJson.toString());
202 private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
203 for (Object key : jsonObj.keySet()) {
204 String keyStr = (String) key;
205 Object keyvalue = jsonObj.get(keyStr);
206 if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) {
207 jsonStringValues.put(keyStr, keyvalue.toString());
208 // --- set default value
209 jsonObj.put(keyStr, "JSON_STRING");
212 // for nested objects iteration if required
213 if (keyvalue instanceof JSONObject) {
214 saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
215 // --- set default value
216 jsonObj.put(keyStr, "JSON_STRING");
219 if (keyvalue instanceof JSONArray) {
220 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
221 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
222 saveOriginalJsonObject(temp, jsonStringValues);
230 private JSONObject setOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
231 for (Object key : jsonObj.keySet()) {
232 String keyStr = (String) key;
233 Object keyvalue = jsonObj.get(keyStr);
234 String originalValue = getOriginalValue(keyStr);
235 if (originalValue != null) {
236 jsonObj.put(keyStr, originalValue);
239 // for nested objects iteration if required
240 if (keyvalue instanceof JSONObject) {
241 setOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
242 jsonObj.put(keyStr, originalValue);
245 if (keyvalue instanceof JSONArray) {
246 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
247 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
248 setOriginalJsonObject(temp, jsonStringValues);
256 private GroupPolicyScopeList getPolicyObject(String policyScope) {
257 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
260 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue)
262 ObjectWriter om = new ObjectMapper().writer();
264 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
265 MicroServiceModels returnModel = new MicroServiceModels();
266 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
267 if (policyAdapter.getServiceType() != null) {
268 microServiceObject.setService(policyAdapter.getServiceType());
269 microServiceObject.setVersion(policyAdapter.getVersion());
270 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
272 if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) {
273 if (policyAdapter.getUuid() != null) {
274 microServiceObject.setUuid(policyAdapter.getUuid());
276 if (policyAdapter.getLocation() != null) {
277 microServiceObject.setLocation(policyAdapter.getLocation());
279 if (policyAdapter.getConfigName() != null) {
280 microServiceObject.setConfigName(policyAdapter.getConfigName());
282 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
283 if (policyScopeValue != null) {
284 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
288 if (policyAdapter.getPolicyName() != null) {
289 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
291 if (policyAdapter.getPolicyDescription() != null) {
292 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
294 if (policyAdapter.getPriority() != null) {
295 microServiceObject.setPriority(policyAdapter.getPriority());
297 microServiceObject.setPriority("9999");
300 if (policyAdapter.getRiskLevel() != null) {
301 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
303 if (policyAdapter.getRiskType() != null) {
304 microServiceObject.setRiskType(policyAdapter.getRiskType());
306 if (policyAdapter.getGuard() != null) {
307 microServiceObject.setGuard(policyAdapter.getGuard());
309 microServiceObject.setContent(jsonContent);
310 String modelName = policyAdapter.getServiceType();
311 String versionName = policyAdapter.getVersion();
312 List<Object> triggerData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version",
313 modelName + ":" + versionName);
314 MicroServiceModels model = null;
315 boolean ruleCheck = false;
316 boolean SymptomRuleCheck = false;
317 if (!triggerData.isEmpty()) {
318 model = (MicroServiceModels) triggerData.get(0);
319 if (model.getRuleFormation() != null) {
320 microServiceObject.setUiContent(jsonContent);
322 if (model.getRuleFormation().contains("@")) {
323 SymptomRuleCheck = true;
328 json = om.writeValueAsString(microServiceObject);
329 } catch (JsonProcessingException e) {
330 LOGGER.error("Error writing out the object", e);
332 LOGGER.info("input json: " + json);
333 LOGGER.info("input jsonContent: " + jsonContent);
334 String cleanJson = cleanUPJson(json);
335 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
337 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
338 LOGGER.info("tempJson: " + tempJson);
339 cleanJson = removeNullAttributes(tempJson);
340 if (cleanJson.contains("\\")) {
341 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\"}, new String[] {""});
343 policyAdapter.setJsonBody(cleanJson);
345 ObjectMapper mapper = new ObjectMapper();
346 JsonNode tempJsonNode = mapper.readTree(cleanJson);
348 // JsonNode tempJsonNode = mapper.readTree(cleanJson);
349 ObjectNode finalJson = (ObjectNode) tempJsonNode;
350 JsonNode object = tempJsonNode.get("content");
351 String primaryKey1 = model.getRuleFormation();
352 String[] primaryKeyForSignatures = primaryKey1.split("@");
353 for (String primaryKeyForSignature : primaryKeyForSignatures) {
354 String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
355 JsonNode triggerSig = object.get(primarykeyAlarm);
356 sigRules = new HashMap<>();
357 String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
358 StringBuilder sb = null;
359 if (triggerSig instanceof ArrayNode) {
360 for (int i = 0; i < triggerSig.size(); i++) {
361 sb = new StringBuilder();
362 parseData(triggerSig.get(i), parseKey);
364 List<?> keyList = new ArrayList<>(sigRules.keySet());
365 for (int j = keyList.size() - 1; j >= 0; j--) {
366 String key = (String) keyList.get(j);
367 String jsonNode = sigRules.get(key);
368 constructRule(sb, jsonNode, sigRules);
370 sb.append(")").toString();
371 putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
372 sigRules = new HashMap<>();
375 sb = new StringBuilder();
376 parseData(triggerSig, parseKey);
379 policyAdapter.setJsonBody(finalJson.toString());
381 return policyAdapter;
384 private JsonNode putRuletoJson(JsonNode tmpJsonNode, int item, StringBuilder sb, String parseKey,
386 JsonNode tmp = tmpJsonNode;
387 ObjectNode objectNode = (ObjectNode) tmp;
388 JsonNode jsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
389 JsonNode tempRuleJsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
390 String[] tempSt = parseKey.split("\\.");
391 for (String value : tempSt) {
392 if (value.contains("[")) {
393 if (tempRuleJsonNode instanceof ArrayNode) {
394 JsonNode tempRuleNode = tempRuleJsonNode.get(item);
395 ((ArrayNode) tempRuleJsonNode).removeAll();
396 ((ArrayNode) tempRuleJsonNode).add(tempRuleNode);
397 objectNode = (ObjectNode) tempRuleJsonNode.get(item);
399 String key = value.substring(0, value.indexOf('['));
400 objectNode.remove(key);
401 objectNode.put(key, sb.toString());
404 jsonNode = jsonNode.get(value);
405 if (jsonNode instanceof ArrayNode) {
406 tempRuleJsonNode = jsonNode;
407 jsonNode = jsonNode.get(item);
414 public boolean checkPattern(String patternString) {
415 return PATTERN.matcher(patternString).find();
422 * @param jsonNode the json node
423 * @param sigRules2 the sig rules 2
425 public void constructRule(StringBuilder sb, String jsonNode, Map<String, String> sigRules2) {
427 String cleanJsonNode = jsonNode.replace("\"\"", " ");
428 cleanJsonNode = cleanJsonNode.replaceAll("\"", "");
429 cleanJsonNode = cleanJsonNode.replaceAll("\\(", "");
430 cleanJsonNode = cleanJsonNode.replaceAll("\\)", "");
431 boolean flag = false;
432 if (cleanJsonNode.contains("OR")) {
436 for (String rowValue : cleanJsonNode.split(" ")) {
437 if (checkPattern(rowValue)) {
438 String value = sigRules2.get(rowValue);
439 LOGGER.info(" Value is:" + value);
440 constructRule(sb, value, sigRules2);
442 if ((count == 0) && (!("AND").equals(rowValue)) && (!("OR").equals(rowValue))) {
446 LOGGER.info(" " + rowValue + " ");
447 sb.append(" " + rowValue + " ");
448 if (count % 3 == 0) {
462 * @param jsonNode the json node
463 * @param string the string
465 public void parseData(JsonNode jsonNode, String string) {
466 if (string.contains(".")) {
467 String firstIndex = string.substring(0, string.indexOf('.'));
468 JsonNode signtures = jsonNode.get(firstIndex);
469 String subIndex = string.substring(firstIndex.length() + 1);
470 if (signtures instanceof ArrayNode) {
471 for (int i = 0; i < signtures.size(); i++) {
472 parseData(signtures.get(i), subIndex);
475 parseData(signtures, subIndex);
478 if (string.contains("[")) {
479 String ruleIndex = string.substring(0, string.indexOf('['));
480 String[] keys = string.substring(string.indexOf('[') + 1, string.lastIndexOf(']')).split(",");
481 String key = "A" + Integer.valueOf(sigRules.size() + 1);
482 JsonNode node = jsonNode.get(ruleIndex);
483 StringBuilder sb = new StringBuilder("(");
484 for (int i = 0; i < keys.length; i++) {
485 sb.append(node.get(keys[i].trim()));
488 sigRules.put(key, sb.toString());
493 public String removeNullAttributes(String cleanJson) {
494 ObjectMapper mapper = new ObjectMapper();
497 JsonNode rootNode = mapper.readTree(cleanJson);
498 JsonNode returnNode = mapper.readTree(cleanJson);
499 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
500 boolean remove = false;
501 JsonObject removed = null;
502 boolean contentChanged = false;
503 while (fieldsIterator.hasNext()) {
504 Map.Entry<String, JsonNode> field = fieldsIterator.next();
505 final String key = field.getKey();
506 final JsonNode value = field.getValue();
507 if ("content".equalsIgnoreCase(key)) {
508 String contentStr = value.toString();
509 try (JsonReader reader = Json.createReader(new StringReader(contentStr))) {
510 JsonObject jsonContent = reader.readObject();
511 removed = removeNull(jsonContent);
512 if (!jsonContent.toString().equals(removed.toString())) {
513 contentChanged = true;
517 if (value == null || value.isNull()) {
518 ((ObjectNode) returnNode).remove(key);
523 cleanJson = returnNode.toString();
525 if (value == null || value.isNull()) {
526 ((ObjectNode) returnNode).remove(key);
531 cleanJson = returnNode.toString();
534 if (contentChanged) {
535 // set modified content to cleanJson
536 JSONObject jObject = new JSONObject(cleanJson);
537 jObject.put("content", removed.toString());
538 cleanJson = cleanUPJson(jObject.toString());
541 } catch (IOException e) {
542 LOGGER.error("Error writing out the JsonNode", e);
548 * To verify if it is a JSON string. If it is, then return its original value.
550 * @param key holds the values
553 private String getOriginalValue(String key) {
554 for (String k : jsonStringValues.keySet()) {
555 if (k.contains("@")) {
556 String[] arrOfKeys = k.split("@");
557 for (int i = 0; i < arrOfKeys.length; i++) {
558 if (arrOfKeys[i].contains(".")) {
559 arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
560 if (arrOfKeys[i].equals(key)) {
561 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
562 new String[] {"\\\""});
567 if (k.endsWith(key)) {
568 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
575 public JsonArray removeNull(JsonArray array) {
576 JsonArrayBuilder builder = Json.createArrayBuilder();
578 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
579 JsonValue value = it.next();
580 switch (value.getValueType()) {
582 JsonArray a = removeNull(array.getJsonArray(i));
587 JsonObject object = removeNull(array.getJsonObject(i));
588 if (!object.isEmpty())
592 String s = array.getString(i);
593 if (s != null && !s.isEmpty())
597 builder.add(array.getJsonNumber(i));
601 builder.add(array.getBoolean(i));
607 return builder.build();
610 public JsonObject removeNull(JsonObject obj) {
611 JsonObjectBuilder builder = Json.createObjectBuilder();
612 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
613 Entry<String, JsonValue> e = it.next();
614 String key = e.getKey();
615 JsonValue value = e.getValue();
616 switch (value.getValueType()) {
618 JsonArray array = removeNull(obj.getJsonArray(key));
619 if (!array.isEmpty())
620 builder.add(key, array);
623 JsonObject object = removeNull(obj.getJsonObject(key));
624 if (!object.isEmpty()) {
625 if (!jsonStringValues.isEmpty()) {
626 String originalValue = getOriginalValue(key);
627 if (originalValue != null) {
628 builder.add(key, object.toString());
632 builder.add(key, object);
636 String s = obj.getString(key);
637 if (s != null && !s.isEmpty()) {
638 if (!jsonStringValues.isEmpty()) {
639 String originalValue = getOriginalValue(key);
640 if (originalValue != null) {
641 s = getOriginalValue(key);
648 builder.add(key, obj.getJsonNumber(key));
652 builder.add(key, obj.getBoolean(key));
658 return builder.build();
661 public String cleanUPJson(String json) {
662 String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
663 new String[] {"\\", "\\", "\\"});
664 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
666 StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"});
668 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""},
669 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[] {"\""});
678 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
682 public JSONObject decodeContent(JsonNode jsonNode) {
683 Iterator<JsonNode> jsonElements = jsonNode.elements();
684 Iterator<String> jsonKeys = jsonNode.fieldNames();
685 Map<String, String> element = new TreeMap<>();
686 while (jsonElements.hasNext() && jsonKeys.hasNext()) {
687 element.put(jsonKeys.next(), jsonElements.next().toString());
689 JSONObject jsonResult = new JSONObject();
690 JSONArray jsonArray = null;
691 String oldValue = null;
692 String nodeKey = null;
693 String arryKey = null;
694 Boolean isArray = false;
695 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
696 ObjectNode node = nodeFactory.objectNode();
697 String prevKey = null;
699 for (Entry<String, String> entry : element.entrySet()) {
700 String key = entry.getKey();
701 String value = entry.getValue();
702 if (key.contains(".")) {
703 presKey = key.substring(0, key.indexOf('.'));
704 } else if (key.contains("@")) {
705 presKey = key.substring(0, key.indexOf('@'));
709 // first check if we are different from old.
710 LOGGER.info(key + "\n");
711 if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".")
712 && oldValue != null) {
713 if (!oldValue.equals(key.substring(0, key.indexOf('@')))) {
714 jsonResult.put(oldValue, jsonArray);
715 jsonArray = new JSONArray();
717 } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) {
718 jsonResult.put(oldValue, jsonArray);
720 jsonArray = new JSONArray();
725 if (key.contains(".")) {
726 if (nodeKey == null) {
727 nodeKey = key.substring(0, key.indexOf('.'));
729 if (nodeKey.equals(key.substring(0, key.indexOf('.')))) {
730 node.put(key.substring(key.indexOf('.') + 1), value);
732 if (node.size() != 0) {
733 if (nodeKey.contains("@")) {
734 if (arryKey == null) {
735 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
737 if (nodeKey.endsWith("@0")) {
739 jsonArray = new JSONArray();
741 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
742 jsonArray.put(decodeContent(node));
744 if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@'))))
745 || !key.contains("@")) {
746 jsonResult.put(arryKey, jsonArray);
747 jsonArray = new JSONArray();
749 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
752 jsonResult.put(nodeKey, decodeContent(node));
754 node = nodeFactory.objectNode();
756 nodeKey = key.substring(0, key.indexOf('.'));
757 if (nodeKey.contains("@")) {
758 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
760 node.put(key.substring(key.indexOf('.') + 1), value);
763 if (node.size() != 0) {
764 if (nodeKey.contains("@")) {
765 if (arryKey == null) {
766 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
768 if (nodeKey.endsWith("@0")) {
770 jsonArray = new JSONArray();
772 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
773 jsonArray.put(decodeContent(node));
775 jsonResult.put(arryKey, jsonArray);
776 jsonArray = new JSONArray();
777 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
780 jsonResult.put(nodeKey, decodeContent(node));
782 node = nodeFactory.objectNode();
784 if (key.contains("@")) {
786 if (key.endsWith("@0") || jsonArray == null) {
787 jsonArray = new JSONArray();
789 } else if (!key.contains("@")) {
793 if (oldValue == null) {
794 oldValue = key.substring(0, key.indexOf('@'));
796 if (oldValue != prevKey) {
797 oldValue = key.substring(0, key.indexOf('@'));
799 if (oldValue.equals(key.substring(0, key.indexOf('@')))) {
800 jsonArray.put(value);
802 jsonResult.put(oldValue, jsonArray);
803 jsonArray = new JSONArray();
805 oldValue = key.substring(0, key.indexOf('@'));
807 jsonResult.put(key, value);
811 if (node.size() > 0) {
812 if (nodeKey.contains("@")) {
813 if (jsonArray == null) {
814 jsonArray = new JSONArray();
816 if (arryKey == null) {
817 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
819 jsonArray.put(decodeContent(node));
820 jsonResult.put(arryKey, jsonArray);
823 jsonResult.put(nodeKey, decodeContent(node));
826 if (isArray && jsonArray.length() > 0) {
827 jsonResult.put(oldValue, jsonArray);
833 value = {"/policyController/getDCAEMSTemplateData.htm"},
834 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
835 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
837 // TreeSet is used to ensure that individual items appear before their containing collection.
838 allManyTrueKeys = new TreeSet<>();
839 ObjectMapper mapper = new ObjectMapper();
840 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
841 JsonNode root = mapper.readTree(request.getReader());
843 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
844 String servicename = value.split("-v")[0];
845 String version = null;
846 if (value.contains("-v")) {
847 version = value.split("-v")[1];
849 MicroServiceModels returnModel = getAttributeObject(servicename, version);
851 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
852 JSONObject jsonHdDefaultObj = null;
853 if (returnHeaderDefauls != null) {
854 jsonHdDefaultObj = new JSONObject();
855 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
856 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
857 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
858 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
859 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
861 String headDefautlsData = "";
862 if (jsonHdDefaultObj != null) {
863 headDefautlsData = jsonHdDefaultObj.toString();
865 headDefautlsData = "null";
868 // Get all keys with "MANY-true" defined in their value from subAttribute
869 Set<String> allkeys = null;
870 if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
871 JSONObject json = new JSONObject(returnModel.getSub_attributes());
873 allkeys = allManyTrueKeys;
874 allManyTrueKeys = new TreeSet<>();
875 LOGGER.info("allkeys : " + allkeys);
878 // Get element order info
879 String dataOrderInfo = returnModel.getDataOrderInfo();
880 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
881 dataOrderInfo = "\"" + dataOrderInfo + "\"";
883 LOGGER.info("dataOrderInfo : " + dataOrderInfo);
885 String allMnyTrueKeys = "";
886 if (allkeys != null) {
887 allMnyTrueKeys = allkeys.toString();
890 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
892 JSONObject jsonObject = new JSONObject(jsonModel);
894 JSONObject finalJsonObject = null;
895 if (allkeys != null) {
896 Iterator<String> iter = allkeys.iterator();
897 while (iter.hasNext()) {
898 // Convert to array values for MANY-true keys
899 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
900 jsonObject = finalJsonObject;
904 if (finalJsonObject != null) {
905 LOGGER.info(finalJsonObject.toString());
906 jsonModel = finalJsonObject.toString();
909 // get all properties with "MANY-true" defined in Ref_attributes
910 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
911 if (manyTrueProperties != null) {
912 JSONObject jsonObj = new JSONObject(jsonModel);
913 for (String s : manyTrueProperties) {
915 // convert to array element for MANY-true properties
916 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
917 jsonObj = finalJsonObject;
920 if (finalJsonObject != null) {
921 LOGGER.info(finalJsonObject.toString());
922 jsonModel = finalJsonObject.toString();
926 response.setCharacterEncoding("UTF-8");
927 response.setContentType("application / json");
928 request.setCharacterEncoding("UTF-8");
929 List<Object> list = new ArrayList<>();
930 PrintWriter out = response.getWriter();
931 String responseString = mapper.writeValueAsString(returnModel);
935 if ("".equals(allMnyTrueKeys)) {
936 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
937 + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
939 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
940 + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
944 out.write(list.toString());
948 @SuppressWarnings({"unchecked", "rawtypes"})
949 private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
950 Map<String, String> attributeMap = new HashMap<>();
951 Map<String, String> refAttributeMap = new HashMap<>();
952 String attribute = returnModel.getAttributes();
953 if (attribute != null) {
954 attribute = attribute.trim();
956 String refAttribute = returnModel.getRef_attributes();
957 if (refAttribute != null) {
958 refAttribute = refAttribute.trim();
960 String enumAttribute = returnModel.getEnumValues();
961 if (enumAttribute != null) {
962 enumAttribute = enumAttribute.trim();
964 if (!StringUtils.isEmpty(attribute)) {
965 attributeMap = convert(attribute, ",");
967 if (!StringUtils.isEmpty(refAttribute)) {
968 refAttributeMap = convert(refAttribute, ",");
971 Gson gson = new Gson();
973 String subAttributes = returnModel.getSub_attributes();
974 if (subAttributes != null) {
975 subAttributes = subAttributes.trim();
980 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
982 JSONObject object = new JSONObject();
983 JSONArray array = new JSONArray();
985 for (Entry<String, String> keySet : attributeMap.entrySet()) {
986 array = new JSONArray();
987 String value = keySet.getValue();
988 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
990 object.put(keySet.getKey().trim(), array);
992 object.put(keySet.getKey().trim(), value.trim());
996 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
997 array = new JSONArray();
998 String value = keySet.getValue().split(":")[0];
999 if (gsonObject.containsKey(value)) {
1000 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1001 array.put(recursiveReference(value, gsonObject, enumAttribute));
1002 object.put(keySet.getKey().trim(), array);
1004 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1007 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1008 array.put(value.trim());
1009 object.put(keySet.getKey().trim(), array);
1011 object.put(keySet.getKey().trim(), value.trim());
1016 return object.toString();
1019 @SuppressWarnings("unchecked")
1020 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
1021 JSONObject object = new JSONObject();
1022 Map<String, String> map;
1023 Object returnClass = subAttributeMap.get(name);
1024 map = (Map<String, String>) returnClass;
1027 for (Entry<String, String> m : map.entrySet()) {
1028 String[] splitValue = m.getValue().split(":");
1029 array = new JSONArray();
1030 if (subAttributeMap.containsKey(splitValue[0])) {
1031 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1032 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1033 object.put(m.getKey().trim(), array);
1035 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1038 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1039 array.put(splitValue[0].trim());
1040 object.put(m.getKey().trim(), array);
1042 object.put(m.getKey().trim(), splitValue[0].trim());
1050 public JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1051 return convertToArrayElement(json, new HashSet<>(), keyValue);
1054 private JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1055 for (String key : json.keySet()) {
1056 Object obj = json.get(key);
1057 if (key.equals(keyValue.trim())) {
1058 if (!(obj instanceof JSONArray)) {
1059 JSONArray newJsonArray = new JSONArray();
1060 newJsonArray.put(obj);
1061 json.put(key, newJsonArray);
1063 LOGGER.info("key : " + key);
1064 LOGGER.info("obj : " + obj);
1065 LOGGER.info("json.get(key) : " + json.get(key));
1066 LOGGER.info("keyValue : " + keyValue);
1067 keys.addAll(json.keySet());
1072 if (obj instanceof JSONObject) {
1073 convertToArrayElement(json.getJSONObject(key), keyValue);
1076 if (obj instanceof JSONArray) {
1077 convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
1084 // call this method to get all MANY-true properties
1085 public Set<String> getManyTrueProperties(String referAttributes) {
1086 LOGGER.info("referAttributes : " + referAttributes);
1087 Set<String> manyTrueProperties = new HashSet<>();
1089 if (referAttributes != null) {
1090 String[] referAarray = referAttributes.split(",");
1091 String[] element = null;
1092 for (int i = 0; i < referAarray.length; i++) {
1093 element = referAarray[i].split("=");
1094 if (element.length > 1 && element[1].contains("MANY-true")) {
1095 manyTrueProperties.add(element[0]);
1100 return manyTrueProperties;
1103 // call this method to start the recursive
1104 private Set<String> getAllKeys(JSONObject json) {
1105 return getAllKeys(json, new HashSet<>());
1108 private Set<String> getAllKeys(JSONArray arr) {
1109 return getAllKeys(arr, new HashSet<>());
1112 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1113 for (int i = 0; i < arr.length(); i++) {
1114 Object obj = arr.get(i);
1115 if (obj instanceof JSONObject)
1116 keys.addAll(getAllKeys(arr.getJSONObject(i)));
1117 if (obj instanceof JSONArray)
1118 keys.addAll(getAllKeys(arr.getJSONArray(i)));
1124 // this method returns a set of keys with "MANY-true" defined in their value.
1125 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1126 for (String key : json.keySet()) {
1127 Object obj = json.get(key);
1128 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
1129 LOGGER.info("key : " + key);
1130 LOGGER.info("obj : " + obj);
1131 allManyTrueKeys.add(key);
1133 if (obj instanceof JSONObject)
1134 keys.addAll(getAllKeys(json.getJSONObject(key)));
1135 if (obj instanceof JSONArray)
1136 keys.addAll(getAllKeys(json.getJSONArray(key)));
1143 value = {"/policyController/getModelServiceVersioneData.htm"},
1144 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1145 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
1146 throws IOException {
1147 ObjectMapper mapper = new ObjectMapper();
1148 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1149 JsonNode root = mapper.readTree(request.getReader());
1151 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
1152 String servicename = value.split("-v")[0];
1153 Set<String> returnList = getVersionList(servicename);
1155 response.setCharacterEncoding("UTF-8");
1156 response.setContentType("application / json");
1157 request.setCharacterEncoding("UTF-8");
1158 List<Object> list = new ArrayList<>();
1159 PrintWriter out = response.getWriter();
1160 String responseString = mapper.writeValueAsString(returnList);
1161 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}");
1163 out.write(list.toString());
1167 private Set<String> getVersionList(String name) {
1168 MicroServiceModels workingModel;
1169 Set<String> list = new HashSet<>();
1170 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1171 for (int i = 0; i < microServiceModelsData.size(); i++) {
1172 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1173 if (workingModel.getVersion() != null) {
1174 list.add(workingModel.getVersion());
1176 list.add("Default");
1182 private MicroServiceModels getAttributeObject(String name, String version) {
1183 MicroServiceModels workingModel = new MicroServiceModels();
1184 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1185 for (int i = 0; i < microServiceModelsData.size(); i++) {
1186 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1187 if (version != null) {
1188 if (workingModel.getVersion() != null) {
1189 if (workingModel.getVersion().equals(version)) {
1190 return workingModel;
1193 return workingModel;
1196 return workingModel;
1200 return workingModel;
1203 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
1204 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName",
1209 value = {"/get_DCAEPriorityValues"},
1210 method = {org.springframework.web.bind.annotation.RequestMethod.GET},
1211 produces = MediaType.APPLICATION_JSON_VALUE)
1212 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
1214 Map<String, Object> model = new HashMap<>();
1215 ObjectMapper mapper = new ObjectMapper();
1216 List<String> priorityList = new ArrayList<>();
1218 for (int i = 1; i < priorityCount; i++) {
1219 priorityList.add(String.valueOf(i));
1221 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1222 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1223 JSONObject j = new JSONObject(msg);
1224 response.getWriter().write(j.toString());
1225 } catch (Exception e) {
1230 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1231 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1232 Object policyData = policyAdapter.getPolicyData();
1233 PolicyType policy = (PolicyType) policyData;
1234 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1235 String policyNameValue =
1236 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
1237 policyAdapter.setPolicyName(policyNameValue);
1238 String description = "";
1240 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1241 } catch (Exception e) {
1242 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
1243 description = policy.getDescription();
1245 policyAdapter.setPolicyDescription(description);
1246 // Get the target data under policy.
1247 TargetType target = policy.getTarget();
1248 if (target != null) {
1249 // Under target we have AnyOFType
1250 List<AnyOfType> anyOfList = target.getAnyOf();
1251 if (anyOfList != null) {
1252 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1253 while (iterAnyOf.hasNext()) {
1254 AnyOfType anyOf = iterAnyOf.next();
1255 // Under AnyOFType we have AllOFType
1256 List<AllOfType> allOfList = anyOf.getAllOf();
1257 if (allOfList != null) {
1258 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1259 while (iterAllOf.hasNext()) {
1260 AllOfType allOf = iterAllOf.next();
1261 // Under AllOFType we have Match
1262 List<MatchType> matchList = allOf.getMatch();
1263 if (matchList != null) {
1264 Iterator<MatchType> iterMatch = matchList.iterator();
1265 while (matchList.size() > 1 && iterMatch.hasNext()) {
1266 MatchType match = iterMatch.next();
1268 // Under the match we have attribute value and
1269 // attributeDesignator. So,finally down to the actual attribute.
1271 AttributeValueType attributeValue = match.getAttributeValue();
1272 String value = (String) attributeValue.getContent().get(0);
1273 AttributeDesignatorType designator = match.getAttributeDesignator();
1274 String attributeId = designator.getAttributeId();
1275 // First match in the target is OnapName, so set that value.
1276 if ("ONAPName".equals(attributeId)) {
1277 policyAdapter.setOnapName(value);
1279 if ("ConfigName".equals(attributeId)) {
1280 policyAdapter.setConfigName(value);
1282 if ("uuid".equals(attributeId)) {
1283 policyAdapter.setUuid(value);
1285 if ("location".equals(attributeId)) {
1286 policyAdapter.setLocation(value);
1288 if ("RiskType".equals(attributeId)) {
1289 policyAdapter.setRiskType(value);
1291 if ("RiskLevel".equals(attributeId)) {
1292 policyAdapter.setRiskLevel(value);
1294 if ("guard".equals(attributeId)) {
1295 policyAdapter.setGuard(value);
1297 if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
1298 PolicyController controller = new PolicyController();
1299 String newDate = controller.convertDate(value);
1300 policyAdapter.setTtlDate(newDate);
1303 readFile(policyAdapter, entity);
1316 * @param str the str
1317 * @param split the split
1320 public Map<String, String> convert(String str, String split) {
1321 Map<String, String> map = new HashMap<>();
1322 for (final String entry : str.split(split)) {
1323 String[] parts = entry.split("=");
1324 map.put(parts[0], parts[1]);
1332 * @param policyAdapter the policy adapter
1333 * @param entity the entity
1335 @SuppressWarnings("unchecked")
1336 public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1337 String policyScopeName = null;
1338 ObjectMapper mapper = new ObjectMapper();
1340 DCAEMicroServiceObject msBody =
1341 mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1342 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1343 policyAdapter.setPolicyScope(policyScopeName);
1345 policyAdapter.setPriority(msBody.getPriority());
1347 if (msBody.getVersion() != null) {
1348 policyAdapter.setServiceType(msBody.getService());
1349 policyAdapter.setVersion(msBody.getVersion());
1351 policyAdapter.setServiceType(msBody.getService());
1354 LinkedHashMap<String, ?> content = (LinkedHashMap<String, ?>) msBody.getUiContent();
1355 if (content == null) {
1356 content = (LinkedHashMap<String, ?>) msBody.getContent();
1358 if (content != null) {
1359 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1360 LinkedHashMap<String, ?> map = content;
1361 readRecursivlyJSONContent(map, data);
1362 policyAdapter.setRuleData(data);
1365 } catch (Exception e) {
1371 @SuppressWarnings({"rawtypes", "unchecked"})
1372 public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) {
1373 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1374 Object key = iterator.next();
1375 Object value = map.get(key);
1376 if (value instanceof LinkedHashMap<?, ?>) {
1377 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1378 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1379 for (Entry<String, Object> entry : secondObjec.entrySet()) {
1380 data.put(key + "." + entry.getKey(), entry.getValue());
1382 } else if (value instanceof ArrayList) {
1383 ArrayList<?> jsonArrayVal = (ArrayList<?>) value;
1384 for (int i = 0; i < jsonArrayVal.size(); i++) {
1385 Object arrayvalue = jsonArrayVal.get(i);
1386 if (arrayvalue instanceof LinkedHashMap<?, ?>) {
1387 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1388 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1389 for (Entry<String, Object> entry : newData.entrySet()) {
1390 data.put(key + "@" + i + "." + entry.getKey(), entry.getValue());
1392 } else if (arrayvalue instanceof ArrayList) {
1393 ArrayList<?> jsonArrayVal1 = (ArrayList<?>) value;
1394 for (int j = 0; j < jsonArrayVal1.size(); j++) {
1395 Object arrayvalue1 = jsonArrayVal1.get(i);
1396 data.put(key + "@" + j, arrayvalue1.toString());
1399 data.put(key + "@" + i, arrayvalue.toString());
1403 data.put(key.toString(), value.toString());
1408 public String getPolicyScope(String value) {
1409 List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1410 if (groupList != null && !groupList.isEmpty()) {
1411 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1412 return pScope.getGroupName();
1417 // Convert the map values and set into JSON body
1418 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1419 Map<String, String> attribute = new HashMap<>();
1423 for (Entry<String, String> entry : attributesMap.entrySet()) {
1424 key = entry.getKey();
1425 value = entry.getValue();
1426 attribute.put(key, value);
1428 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1429 key = entryRef.getKey();
1430 value = entryRef.getValue();
1431 attribute.put(key, value);
1433 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1434 key = entryList.getKey();
1435 value = entryList.getValue();
1436 attribute.put(key, value);
1438 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()) {
1439 key = arrayList.getKey();
1441 for (Object textList : arrayList.getValue()) {
1443 temp = new StringBuilder();
1444 temp.append("[" + textList);
1446 temp.append("," + textList);
1449 attribute.put(key, temp + "]");
1456 value = {"/ms_dictionary/set_MSModelData"},
1457 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1458 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
1459 throws IOException, FileUploadException {
1460 modelList = new ArrayList<>();
1461 dirDependencyList = new ArrayList<>();
1462 classMap = new LinkedHashMap<>();
1463 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1464 boolean zip = false;
1465 boolean yml = false;
1466 String errorMsg = "";
1467 for (FileItem item : items) {
1468 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
1469 this.newModel = new MicroServiceModels();
1471 File file = new File(item.getName());
1472 OutputStream outputStream = new FileOutputStream(file);
1473 IOUtils.copy(item.getInputStream(), outputStream);
1474 outputStream.close();
1475 this.newFile = file.toString();
1476 this.newModel.setModelName(this.newFile.split("-v")[0]);
1478 if (this.newFile.contains("-v")) {
1479 if (item.getName().endsWith(".zip")) {
1480 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1482 } else if (item.getName().endsWith(".yml")) {
1483 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1486 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1489 } catch (Exception e) {
1490 LOGGER.error("Upload error : ", e);
1491 errorMsg = "Upload error:" + e.getMessage();
1497 if (!errorMsg.isEmpty()) {
1499 PrintWriter out = response.getWriter();
1501 response.setCharacterEncoding("UTF-8");
1502 response.setContentType("application / json");
1503 request.setCharacterEncoding("UTF-8");
1505 JSONObject j = new JSONObject();
1506 j.put("errorMsg", errorMsg);
1507 out.write(j.toString());
1511 List<File> fileList = new ArrayList<>();
1512 MSModelUtils msMLUtils = new MSModelUtils(commonClassDao);
1513 this.directory = "model";
1515 extractFolder(this.newFile);
1516 fileList = listModelFiles(this.directory);
1518 errorMsg = msMLUtils.parseTosca(this.newFile);
1519 if (errorMsg != null) {
1520 PrintWriter out = response.getWriter();
1521 response.setCharacterEncoding("UTF-8");
1522 response.setContentType("application / json");
1523 request.setCharacterEncoding("UTF-8");
1524 JSONObject j = new JSONObject();
1525 j.put("errorMsg", errorMsg);
1526 out.write(j.toString());
1531 File file = new File(this.newFile);
1534 String modelType = "";
1537 // Process Main Model file first
1538 classMap = new LinkedHashMap<>();
1539 for (File file : fileList) {
1540 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
1541 retreiveDependency(file.toString(), true);
1545 modelList = createList();
1547 cleanUp(this.newFile);
1551 modelList.add(this.newModel.getModelName());
1552 String className = this.newModel.getModelName();
1553 MSAttributeObject msAttributes = new MSAttributeObject();
1554 msAttributes.setClassName(className);
1556 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
1557 returnAttributeList.put(className, msMLUtils.getAttributeString());
1558 msAttributes.setAttribute(returnAttributeList);
1560 msAttributes.setSubClass(msMLUtils.getRetmap());
1562 msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
1564 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
1566 returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
1567 msAttributes.setRefAttribute(returnReferenceList);
1569 if (msMLUtils.getListConstraints() != "") {
1570 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
1571 String[] listArray = msMLUtils.getListConstraints().split("#");
1572 for (String str : listArray) {
1573 String[] strArr = str.split("=");
1574 if (strArr.length > 1) {
1575 enumList.put(strArr[0], strArr[1]);
1578 msAttributes.setEnumType(enumList);
1581 classMap = new LinkedHashMap<>();
1582 classMap.put(className, msAttributes);
1586 PrintWriter out = response.getWriter();
1588 response.setCharacterEncoding("UTF-8");
1589 response.setContentType("application / json");
1590 request.setCharacterEncoding("UTF-8");
1592 ObjectMapper mapper = new ObjectMapper();
1593 JSONObject j = new JSONObject();
1594 j.put("classListDatas", modelList);
1595 j.put("modelDatas", mapper.writeValueAsString(classMap));
1596 j.put("modelType", modelType);
1597 j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
1598 j.put("ruleFormation", msMLUtils.getJsonRuleFormation());
1600 out.write(j.toString());
1604 * Unzip file and store in the model directory for processing
1606 @SuppressWarnings("rawtypes")
1607 private void extractFolder(String zipFile) {
1609 File file = new File(zipFile);
1611 try (ZipFile zip = new ZipFile(file)) {
1612 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1613 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1614 checkZipDirectory(this.directory);
1615 new File(newPath).mkdir();
1616 Enumeration zipFileEntries = zip.entries();
1618 // Process each entry
1619 while (zipFileEntries.hasMoreElements()) {
1620 // grab a zip file entry
1621 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1622 String currentEntry = entry.getName();
1623 File destFile = new File("model" + File.separator + currentEntry);
1624 File destinationParent = destFile.getParentFile();
1626 destinationParent.mkdirs();
1628 if (!entry.isDirectory()) {
1629 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1631 byte[] data = new byte[BUFFER];
1632 try (FileOutputStream fos = new FileOutputStream(destFile);
1633 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
1634 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1635 dest.write(data, 0, currentByte);
1638 } catch (IOException e) {
1639 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1641 // PLD should I throw e?
1647 if (currentEntry.endsWith(".zip")) {
1648 extractFolder(destFile.getAbsolutePath());
1651 } catch (IOException e) {
1652 LOGGER.error("Failed to unzip model file " + zipFile, e);
1656 private void retreiveDependency(String workingFile, Boolean modelClass) {
1658 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1659 Map<String, MSAttributeObject> tempMap;
1661 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1663 classMap.putAll(tempMap);
1664 LOGGER.info(tempMap);
1670 private List<File> listModelFiles(String directoryName) {
1671 File fileDirectory = new File(directoryName);
1672 List<File> resultList = new ArrayList<>();
1673 File[] fList = fileDirectory.listFiles();
1674 for (File file : fList) {
1675 if (file.isFile()) {
1676 resultList.add(file);
1677 } else if (file.isDirectory()) {
1678 dirDependencyList.add(file.getName());
1679 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1685 public void cleanUp(String path) {
1688 FileUtils.forceDelete(new File(path));
1689 } catch (IOException e) {
1690 LOGGER.error("Failed to delete folder " + path, e);
1695 public void checkZipDirectory(String zipDirectory) {
1696 Path path = Paths.get(zipDirectory);
1698 if (Files.exists(path)) {
1699 cleanUp(zipDirectory);
1703 private List<String> createList() {
1704 List<String> list = new ArrayList<>();
1705 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
1706 if (cMap.getValue().isPolicyTempalate()) {
1707 list.add(cMap.getKey());
1712 if (list.isEmpty()) {
1713 if (classMap.containsKey(this.newModel.getModelName())) {
1714 list.add(this.newModel.getModelName());
1722 public Map<String, String> getAttributesListRefMap() {
1723 return attributesListRefMap;
1726 public Map<String, LinkedList<String>> getArrayTextList() {
1727 return arrayTextList;
1730 public Map<String, String> getSigRules() {
1734 public void setSigRules(Map<String, String> sigRules) {
1735 this.sigRules = sigRules;
1743 class DCAEMicroServiceObject {
1745 private String service;
1746 private String location;
1747 private String uuid;
1748 private String policyName;
1749 private String description;
1750 private String configName;
1751 private String templateVersion;
1752 private String version;
1753 private String priority;
1754 private String policyScope;
1755 private String riskType;
1756 private String riskLevel;
1757 private String guard = null;
1758 private Object uiContent;
1759 private Object content;