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.StringReader;
41 import java.nio.file.Files;
42 import java.nio.file.Path;
43 import java.nio.file.Paths;
44 import java.util.ArrayList;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.Iterator;
49 import java.util.LinkedHashMap;
50 import java.util.LinkedList;
51 import java.util.List;
53 import java.util.Map.Entry;
55 import java.util.TreeMap;
56 import java.util.TreeSet;
57 import java.util.UUID;
58 import java.util.regex.Pattern;
59 import java.util.zip.ZipEntry;
60 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;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
81 import org.apache.commons.compress.utils.IOUtils;
82 import org.apache.commons.fileupload.FileItem;
83 import org.apache.commons.fileupload.FileUploadException;
84 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
85 import org.apache.commons.fileupload.servlet.ServletFileUpload;
86 import org.apache.commons.io.FileUtils;
87 import org.apache.commons.lang.StringUtils;
88 import org.json.JSONArray;
89 import org.json.JSONObject;
90 import org.onap.policy.common.logging.flexlogger.FlexLogger;
91 import org.onap.policy.common.logging.flexlogger.Logger;
92 import org.onap.policy.rest.XACMLRestProperties;
93 import org.onap.policy.rest.adapter.PolicyRestAdapter;
94 import org.onap.policy.rest.dao.CommonClassDao;
95 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
96 import org.onap.policy.rest.jpa.MicroServiceModels;
97 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
98 import org.onap.policy.rest.jpa.PolicyEntity;
99 import org.onap.policy.rest.util.MSAttributeObject;
100 import org.onap.policy.rest.util.MSModelUtils;
101 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
102 import org.onap.portalsdk.core.controller.RestrictedBaseController;
103 import org.onap.portalsdk.core.web.support.JsonMessage;
104 import org.springframework.beans.factory.annotation.Autowired;
105 import org.springframework.http.MediaType;
106 import org.springframework.stereotype.Controller;
107 import org.springframework.web.bind.annotation.RequestMapping;
108 import org.springframework.web.servlet.ModelAndView;
112 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
113 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
115 private static CommonClassDao commonClassDao;
117 public static CommonClassDao getCommonClassDao() {
118 return commonClassDao;
121 public static void setCommonClassDao(CommonClassDao commonClassDao) {
122 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
125 private MicroServiceModels newModel;
126 private String newFile;
127 private String directory;
128 private List<String> modelList = new ArrayList<>();
129 private List<String> dirDependencyList = new ArrayList<>();
130 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
131 String referenceAttributes;
132 String attributeString;
133 Set<String> allManyTrueKeys = null;
134 private Map<String, String> sigRules = null;
136 public static final String DATATYPE = "data_types.policy.data.";
137 public static final String PROPERTIES = ".properties.";
138 public static final String TYPE = ".type";
139 public static final String STRING = "string";
140 public static final String INTEGER = "integer";
141 public static final String LIST = "list";
142 public static final String DEFAULT = ".default";
143 public static final String REQUIRED = ".required";
144 public static final String MATCHABLE = ".matchable";
145 public static final String MANYFALSE = ":MANY-false";
146 private static final Pattern PATTERN = Pattern.compile("[A][0-9]");
147 private static final String POLICYJSON = "policyJSON";
150 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) {
151 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
154 public CreateDcaeMicroServiceController() {
158 protected PolicyRestAdapter policyAdapter = null;
159 private int priorityCount;
160 private Map<String, String> attributesListRefMap = new HashMap<>();
161 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
162 private Map<String, String> jsonStringValues = new HashMap<>();
165 * setDataToPolicyRestAdapter.
167 * @param policyData PolicyRestAdapter
168 * @param root JsonNode
169 * @return PolicyRestAdapter
171 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
173 String jsonContent = null;
175 LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
177 String tempJson = root.get(POLICYJSON).toString();
178 JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString());
179 if (policyJson != null) {
180 tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString();
182 // ---replace empty value with the value below before calling decodeContent method.
183 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
184 LOGGER.info("dummyValue:" + dummyValue);
186 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
187 ObjectMapper mapper = new ObjectMapper();
188 JsonNode tempJsonNode = mapper.readTree(tempJson);
189 jsonContent = decodeContent(tempJsonNode).toString();
190 constructJson(policyData, jsonContent, dummyValue);
191 } catch (Exception e) {
192 LOGGER.error("Error while decoding microservice content", e);
195 // ----Here is the final step to reset the original value back.
196 if (policyData.getJsonBody() != null && jsonStringValues.size() > 0) {
197 String contentBody = policyData.getJsonBody();
198 JSONObject contentJson = new JSONObject(contentBody);
199 JSONObject content = contentJson.getJSONObject("content");
200 content = setOriginalJsonObject(content, jsonStringValues);
201 contentJson.put("content", content);
202 policyData.setJsonBody(contentJson.toString());
208 private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
209 for (Object key : jsonObj.keySet()) {
210 String keyStr = (String) key;
211 Object keyvalue = jsonObj.get(keyStr);
212 if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) {
213 jsonStringValues.put(keyStr, keyvalue.toString());
214 // --- set default value
215 jsonObj.put(keyStr, "JSON_STRING");
218 // for nested objects iteration if required
219 if (keyvalue instanceof JSONObject) {
220 saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
221 // --- set default value
222 jsonObj.put(keyStr, "JSON_STRING");
225 if (keyvalue instanceof JSONArray) {
226 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
227 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
228 saveOriginalJsonObject(temp, jsonStringValues);
236 private JSONObject setOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
237 for (Object key : jsonObj.keySet()) {
238 String keyStr = (String) key;
239 Object keyvalue = jsonObj.get(keyStr);
240 String originalValue = getOriginalValue(keyStr);
241 if (originalValue != null) {
242 jsonObj.put(keyStr, originalValue);
245 // for nested objects iteration if required
246 if (keyvalue instanceof JSONObject) {
247 setOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
248 jsonObj.put(keyStr, originalValue);
251 if (keyvalue instanceof JSONArray) {
252 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
253 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
254 setOriginalJsonObject(temp, jsonStringValues);
262 private GroupPolicyScopeList getPolicyObject(String policyScope) {
263 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
266 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue)
268 ObjectWriter om = new ObjectMapper().writer();
270 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
271 MicroServiceModels returnModel = new MicroServiceModels();
272 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
273 if (policyAdapter.getServiceType() != null) {
274 microServiceObject.setService(policyAdapter.getServiceType());
275 microServiceObject.setVersion(policyAdapter.getVersion());
276 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
278 if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) {
279 if (policyAdapter.getUuid() != null) {
280 microServiceObject.setUuid(policyAdapter.getUuid());
282 if (policyAdapter.getLocation() != null) {
283 microServiceObject.setLocation(policyAdapter.getLocation());
285 if (policyAdapter.getConfigName() != null) {
286 microServiceObject.setConfigName(policyAdapter.getConfigName());
288 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
289 if (policyScopeValue != null) {
290 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
294 if (policyAdapter.getPolicyName() != null) {
295 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
297 if (policyAdapter.getPolicyDescription() != null) {
298 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
300 if (policyAdapter.getPriority() != null) {
301 microServiceObject.setPriority(policyAdapter.getPriority());
303 microServiceObject.setPriority("9999");
306 if (policyAdapter.getRiskLevel() != null) {
307 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
309 if (policyAdapter.getRiskType() != null) {
310 microServiceObject.setRiskType(policyAdapter.getRiskType());
312 if (policyAdapter.getGuard() != null) {
313 microServiceObject.setGuard(policyAdapter.getGuard());
315 microServiceObject.setContent(jsonContent);
316 String modelName = policyAdapter.getServiceType();
317 String versionName = policyAdapter.getVersion();
318 List<Object> triggerData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version",
319 modelName + ":" + versionName);
320 MicroServiceModels model = null;
321 boolean ruleCheck = false;
322 if (!triggerData.isEmpty()) {
323 model = (MicroServiceModels) triggerData.get(0);
324 if (model.getRuleFormation() != null) {
325 microServiceObject.setUiContent(jsonContent);
330 json = om.writeValueAsString(microServiceObject);
331 } catch (JsonProcessingException e) {
332 LOGGER.error("Error writing out the object", e);
334 LOGGER.info("input json: " + json);
335 LOGGER.info("input jsonContent: " + jsonContent);
336 String cleanJson = cleanUpJson(json);
337 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
339 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
340 LOGGER.info("tempJson: " + tempJson);
341 cleanJson = removeNullAttributes(tempJson);
342 if (cleanJson.contains("\\")) {
343 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\"}, new String[] {""});
345 policyAdapter.setJsonBody(cleanJson);
347 ObjectMapper mapper = new ObjectMapper();
348 JsonNode tempJsonNode = mapper.readTree(cleanJson);
350 return policyAdapter;
352 ObjectNode finalJson = (ObjectNode) tempJsonNode;
353 JsonNode object = tempJsonNode.get("content");
354 String primaryKey1 = model.getRuleFormation();
355 String[] primaryKeyForSignatures = primaryKey1.split("@");
356 for (String primaryKeyForSignature : primaryKeyForSignatures) {
357 String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
358 JsonNode triggerSig = object.get(primarykeyAlarm);
359 sigRules = new HashMap<>();
360 String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
361 StringBuilder sb = null;
362 if (triggerSig instanceof ArrayNode) {
363 for (int i = 0; i < triggerSig.size(); i++) {
364 sb = new StringBuilder();
365 parseData(triggerSig.get(i), parseKey);
367 List<?> keyList = new ArrayList<>(sigRules.keySet());
368 for (int j = keyList.size() - 1; j >= 0; j--) {
369 String key = (String) keyList.get(j);
370 String jsonNode = sigRules.get(key);
371 constructRule(sb, jsonNode, sigRules);
373 sb.append(")").toString();
374 putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
375 sigRules = new HashMap<>();
378 parseData(triggerSig, parseKey);
381 policyAdapter.setJsonBody(finalJson.toString());
382 return policyAdapter;
385 private JsonNode putRuletoJson(JsonNode tmpJsonNode, int item, StringBuilder sb, String parseKey,
387 JsonNode tmp = tmpJsonNode;
388 ObjectNode objectNode = (ObjectNode) tmp;
389 JsonNode jsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
390 JsonNode tempRuleJsonNode = tmpJsonNode.get("content").get(primaryKey).get(item);
391 String[] tempSt = parseKey.split("\\.");
392 for (String value : tempSt) {
393 if (value.contains("[")) {
394 if (tempRuleJsonNode instanceof ArrayNode) {
395 JsonNode tempRuleNode = tempRuleJsonNode.get(item);
396 ((ArrayNode) tempRuleJsonNode).removeAll();
397 ((ArrayNode) tempRuleJsonNode).add(tempRuleNode);
398 objectNode = (ObjectNode) tempRuleJsonNode.get(item);
400 String key = value.substring(0, value.indexOf('['));
401 objectNode.remove(key);
402 objectNode.put(key, sb.toString());
405 jsonNode = jsonNode.get(value);
406 if (jsonNode instanceof ArrayNode) {
407 tempRuleJsonNode = jsonNode;
408 jsonNode = jsonNode.get(item);
415 public boolean checkPattern(String patternString) {
416 return PATTERN.matcher(patternString).find();
423 * @param jsonNode the json node
424 * @param sigRules2 the sig rules 2
426 public void constructRule(StringBuilder sb, String jsonNode, Map<String, String> sigRules2) {
428 String cleanJsonNode = jsonNode.replace("\"\"", " ");
429 cleanJsonNode = cleanJsonNode.replaceAll("\"", "");
430 cleanJsonNode = cleanJsonNode.replaceAll("\\(", "");
431 cleanJsonNode = cleanJsonNode.replaceAll("\\)", "");
432 boolean flag = false;
433 if (cleanJsonNode.contains("OR")) {
437 for (String rowValue : cleanJsonNode.split(" ")) {
438 if (checkPattern(rowValue)) {
439 String value = sigRules2.get(rowValue);
440 LOGGER.info(" Value is:" + value);
441 constructRule(sb, value, sigRules2);
443 if ((count == 0) && (!("AND").equals(rowValue)) && (!("OR").equals(rowValue))) {
447 LOGGER.info(" " + rowValue + " ");
448 sb.append(" " + rowValue + " ");
449 if (count % 3 == 0) {
463 * @param jsonNode the json node
464 * @param string the string
466 public void parseData(JsonNode jsonNode, String string) {
467 if (string.contains(".")) {
468 String firstIndex = string.substring(0, string.indexOf('.'));
469 JsonNode signtures = jsonNode.get(firstIndex);
470 String subIndex = string.substring(firstIndex.length() + 1);
471 if (signtures instanceof ArrayNode) {
472 for (int i = 0; i < signtures.size(); i++) {
473 parseData(signtures.get(i), subIndex);
476 parseData(signtures, subIndex);
479 if (string.contains("[")) {
480 String ruleIndex = string.substring(0, string.indexOf('['));
481 String[] keys = string.substring(string.indexOf('[') + 1, string.lastIndexOf(']')).split(",");
482 String key = "A" + Integer.valueOf(sigRules.size() + 1);
483 JsonNode node = jsonNode.get(ruleIndex);
484 StringBuilder sb = new StringBuilder("(");
485 for (int i = 0; i < keys.length; i++) {
486 sb.append(node.get(keys[i].trim()));
489 sigRules.put(key, sb.toString());
495 * removeNullAttributes.
497 * @param cleanJson String
500 public String removeNullAttributes(String cleanJson) {
501 ObjectMapper mapper = new ObjectMapper();
504 JsonNode rootNode = mapper.readTree(cleanJson);
505 JsonNode returnNode = mapper.readTree(cleanJson);
506 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
507 boolean remove = false;
508 JsonObject removed = null;
509 boolean contentChanged = false;
510 while (fieldsIterator.hasNext()) {
511 Map.Entry<String, JsonNode> field = fieldsIterator.next();
512 final String key = field.getKey();
513 final JsonNode value = field.getValue();
514 if ("content".equalsIgnoreCase(key)) {
515 String contentStr = value.toString();
516 try (JsonReader reader = Json.createReader(new StringReader(contentStr))) {
517 JsonObject jsonContent = reader.readObject();
518 removed = removeNull(jsonContent);
519 if (!jsonContent.toString().equals(removed.toString())) {
520 contentChanged = true;
524 if (value == null || value.isNull()) {
525 ((ObjectNode) returnNode).remove(key);
530 cleanJson = returnNode.toString();
532 if (value == null || value.isNull()) {
533 ((ObjectNode) returnNode).remove(key);
538 cleanJson = returnNode.toString();
541 if (contentChanged) {
542 // set modified content to cleanJson
543 JSONObject jsonObject = new JSONObject(cleanJson);
544 jsonObject.put("content", removed.toString());
545 cleanJson = cleanUpJson(jsonObject.toString());
548 } catch (IOException e) {
549 LOGGER.error("Error writing out the JsonNode", e);
555 * To verify if it is a JSON string. If it is, then return its original value.
557 * @param key holds the values
560 private String getOriginalValue(String key) {
561 for (String k : jsonStringValues.keySet()) {
562 if (k.contains("@")) {
563 String[] arrOfKeys = k.split("@");
564 for (int i = 0; i < arrOfKeys.length; i++) {
565 if (arrOfKeys[i].contains(".")) {
566 arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
567 if (arrOfKeys[i].equals(key)) {
568 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
569 new String[] {"\\\""});
574 if (k.endsWith(key)) {
575 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
585 * @param array JsonArray
588 public JsonArray removeNull(JsonArray array) {
589 JsonArrayBuilder builder = Json.createArrayBuilder();
591 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++index) {
592 JsonValue value = it.next();
593 switch (value.getValueType()) {
595 JsonArray tempArray = removeNull(array.getJsonArray(index));
596 if (!tempArray.isEmpty()) {
597 builder.add(tempArray);
601 JsonObject object = removeNull(array.getJsonObject(index));
602 if (!object.isEmpty()) {
607 String str = array.getString(index);
608 if (str != null && !str.isEmpty()) {
613 builder.add(array.getJsonNumber(index));
617 builder.add(array.getBoolean(index));
624 return builder.build();
630 * @param obj JsonObject
633 public JsonObject removeNull(JsonObject obj) {
634 JsonObjectBuilder builder = Json.createObjectBuilder();
635 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
636 Entry<String, JsonValue> entry = it.next();
637 String key = entry.getKey();
638 JsonValue value = entry.getValue();
639 switch (value.getValueType()) {
641 JsonArray array = removeNull(obj.getJsonArray(key));
642 if (!array.isEmpty()) {
643 builder.add(key, array);
647 JsonObject object = removeNull(obj.getJsonObject(key));
648 if (!object.isEmpty()) {
649 if (!jsonStringValues.isEmpty()) {
650 String originalValue = getOriginalValue(key);
651 if (originalValue != null) {
652 builder.add(key, object.toString());
656 builder.add(key, object);
660 String str = obj.getString(key);
661 if (str != null && !str.isEmpty()) {
662 if (!jsonStringValues.isEmpty()) {
663 String originalValue = getOriginalValue(key);
664 if (originalValue != null) {
665 str = getOriginalValue(key);
668 builder.add(key, str);
672 builder.add(key, obj.getJsonNumber(key));
676 builder.add(key, obj.getBoolean(key));
683 return builder.build();
692 public String cleanUpJson(String json) {
693 String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
694 new String[] {"\\", "\\", "\\"});
695 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
697 StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"});
699 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""},
700 new String[] {"\"", "\"", "[{", "}]"});
701 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[{", "}]\""}, new String[] {"[{", "}]"});
702 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
703 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"{", "}\""}, new String[] {"{", "}"});
704 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\"\"", "\"\""}, new String[] {"\"", "\""});
705 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\""}, new String[] {""});
706 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\""}, new String[] {"\""});
707 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\\\\\\"}, new String[] {"\""});
708 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\\""}, new String[] {"\""});
709 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
716 * @param jsonNode JsonNode
719 public JSONObject decodeContent(JsonNode jsonNode) {
720 Iterator<JsonNode> jsonElements = jsonNode.elements();
721 Iterator<String> jsonKeys = jsonNode.fieldNames();
722 Map<String, String> element = new TreeMap<>();
723 while (jsonElements.hasNext() && jsonKeys.hasNext()) {
724 element.put(jsonKeys.next(), jsonElements.next().toString());
726 JSONObject jsonResult = new JSONObject();
727 JSONArray jsonArray = null;
728 String oldValue = null;
729 String nodeKey = null;
730 String arryKey = null;
731 Boolean isArray = false;
732 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
733 ObjectNode node = nodeFactory.objectNode();
734 String prevKey = null;
736 for (Entry<String, String> entry : element.entrySet()) {
737 String key = entry.getKey();
738 String value = entry.getValue();
739 if (key.contains(".")) {
740 presKey = key.substring(0, key.indexOf('.'));
741 } else if (key.contains("@")) {
742 presKey = key.substring(0, key.indexOf('@'));
746 // first check if we are different from old.
747 LOGGER.info(key + "\n");
748 if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".")
749 && oldValue != null) {
750 if (!oldValue.equals(key.substring(0, key.indexOf('@')))) {
751 jsonResult.put(oldValue, jsonArray);
752 jsonArray = new JSONArray();
754 } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) {
755 jsonResult.put(oldValue, jsonArray);
757 jsonArray = new JSONArray();
762 if (key.contains(".")) {
763 if (nodeKey == null) {
764 nodeKey = key.substring(0, key.indexOf('.'));
766 if (nodeKey.equals(key.substring(0, key.indexOf('.')))) {
767 node.put(key.substring(key.indexOf('.') + 1), value);
769 if (node.size() != 0) {
770 if (nodeKey.contains("@")) {
771 if (arryKey == null) {
772 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
774 if (nodeKey.endsWith("@0")) {
776 jsonArray = new JSONArray();
778 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
779 jsonArray.put(decodeContent(node));
781 if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@'))))
782 || !key.contains("@")) {
783 jsonResult.put(arryKey, jsonArray);
784 jsonArray = new JSONArray();
786 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
789 jsonResult.put(nodeKey, decodeContent(node));
791 node = nodeFactory.objectNode();
793 nodeKey = key.substring(0, key.indexOf('.'));
794 if (nodeKey.contains("@")) {
795 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
797 node.put(key.substring(key.indexOf('.') + 1), value);
800 if (node.size() != 0) {
801 if (nodeKey.contains("@")) {
802 if (arryKey == null) {
803 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
805 if (nodeKey.endsWith("@0")) {
807 jsonArray = new JSONArray();
809 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
810 jsonArray.put(decodeContent(node));
812 jsonResult.put(arryKey, jsonArray);
813 jsonArray = new JSONArray();
814 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
817 jsonResult.put(nodeKey, decodeContent(node));
819 node = nodeFactory.objectNode();
821 if (key.contains("@")) {
823 if (key.endsWith("@0") || jsonArray == null) {
824 jsonArray = new JSONArray();
826 } else if (!key.contains("@")) {
830 if (oldValue == null) {
831 oldValue = key.substring(0, key.indexOf('@'));
833 if (oldValue != prevKey) {
834 oldValue = key.substring(0, key.indexOf('@'));
836 if (oldValue.equals(key.substring(0, key.indexOf('@')))) {
837 jsonArray.put(value);
839 jsonResult.put(oldValue, jsonArray);
840 jsonArray = new JSONArray();
842 oldValue = key.substring(0, key.indexOf('@'));
844 jsonResult.put(key, value);
848 if (node.size() > 0) {
849 if (nodeKey.contains("@")) {
850 if (jsonArray == null) {
851 jsonArray = new JSONArray();
853 if (arryKey == null) {
854 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
856 jsonArray.put(decodeContent(node));
857 jsonResult.put(arryKey, jsonArray);
860 jsonResult.put(nodeKey, decodeContent(node));
863 if (isArray && jsonArray.length() > 0) {
864 jsonResult.put(oldValue, jsonArray);
870 value = {"/policyController/getDCAEMSTemplateData.htm"},
871 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
872 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
874 // TreeSet is used to ensure that individual items appear before their containing collection.
875 allManyTrueKeys = new TreeSet<>();
876 ObjectMapper mapper = new ObjectMapper();
877 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
878 JsonNode root = mapper.readTree(request.getReader());
880 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
881 String servicename = value.split("-v")[0];
882 String version = null;
883 if (value.contains("-v")) {
884 version = value.split("-v")[1];
886 MicroServiceModels returnModel = getAttributeObject(servicename, version);
888 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
889 JSONObject jsonHdDefaultObj = null;
890 if (returnHeaderDefauls != null) {
891 jsonHdDefaultObj = new JSONObject();
892 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
893 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
894 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
895 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
896 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
898 String headDefautlsData = "";
899 if (jsonHdDefaultObj != null) {
900 headDefautlsData = jsonHdDefaultObj.toString();
902 headDefautlsData = "null";
905 // Get all keys with "MANY-true" defined in their value from subAttribute
906 Set<String> allkeys = null;
907 if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
908 JSONObject json = new JSONObject(returnModel.getSub_attributes());
910 allkeys = allManyTrueKeys;
911 allManyTrueKeys = new TreeSet<>();
912 LOGGER.info("allkeys : " + allkeys);
915 // Get element order info
916 String dataOrderInfo = returnModel.getDataOrderInfo();
917 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
918 dataOrderInfo = "\"" + dataOrderInfo + "\"";
920 LOGGER.info("dataOrderInfo : " + dataOrderInfo);
922 String allMnyTrueKeys = "";
923 if (allkeys != null) {
924 allMnyTrueKeys = allkeys.toString();
927 String jsonModel = createMicroSeriveJson(returnModel);
929 JSONObject jsonObject = new JSONObject(jsonModel);
931 JSONObject finalJsonObject = null;
932 if (allkeys != null) {
933 Iterator<String> iter = allkeys.iterator();
934 while (iter.hasNext()) {
935 // Convert to array values for MANY-true keys
936 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
937 jsonObject = finalJsonObject;
941 if (finalJsonObject != null) {
942 LOGGER.info(finalJsonObject.toString());
943 jsonModel = finalJsonObject.toString();
946 // get all properties with "MANY-true" defined in Ref_attributes
947 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
948 if (manyTrueProperties != null) {
949 JSONObject jsonObj = new JSONObject(jsonModel);
950 for (String s : manyTrueProperties) {
952 // convert to array element for MANY-true properties
953 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
954 jsonObj = finalJsonObject;
957 if (finalJsonObject != null) {
958 LOGGER.info(finalJsonObject.toString());
959 jsonModel = finalJsonObject.toString();
963 response.setCharacterEncoding("UTF-8");
964 response.setContentType("application / json");
965 request.setCharacterEncoding("UTF-8");
966 List<Object> list = new ArrayList<>();
967 String responseString = mapper.writeValueAsString(returnModel);
969 JSONObject json = null;
971 if ("".equals(allMnyTrueKeys)) {
972 json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
973 + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
975 json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel
976 + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
977 + headDefautlsData + "}");
980 response.getWriter().write(list.toString());
984 @SuppressWarnings({"unchecked", "rawtypes"})
985 private String createMicroSeriveJson(MicroServiceModels returnModel) {
986 Map<String, String> attributeMap = new HashMap<>();
987 Map<String, String> refAttributeMap = new HashMap<>();
988 String attribute = returnModel.getAttributes();
989 if (attribute != null) {
990 attribute = attribute.trim();
992 String refAttribute = returnModel.getRef_attributes();
993 if (refAttribute != null) {
994 refAttribute = refAttribute.trim();
996 String enumAttribute = returnModel.getEnumValues();
997 if (enumAttribute != null) {
998 enumAttribute = enumAttribute.trim();
1000 if (!StringUtils.isEmpty(attribute)) {
1001 attributeMap = convert(attribute, ",");
1003 if (!StringUtils.isEmpty(refAttribute)) {
1004 refAttributeMap = convert(refAttribute, ",");
1007 Gson gson = new Gson();
1009 String subAttributes = returnModel.getSub_attributes();
1010 if (subAttributes != null) {
1011 subAttributes = subAttributes.trim();
1016 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1018 JSONObject object = new JSONObject();
1020 for (Entry<String, String> keySet : attributeMap.entrySet()) {
1021 JSONArray array = new JSONArray();
1022 String value = keySet.getValue();
1023 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1025 object.put(keySet.getKey().trim(), array);
1027 object.put(keySet.getKey().trim(), value.trim());
1031 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
1032 JSONArray array = new JSONArray();
1033 String value = keySet.getValue().split(":")[0];
1034 if (gsonObject.containsKey(value)) {
1035 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1036 array.put(recursiveReference(value, gsonObject, enumAttribute));
1037 object.put(keySet.getKey().trim(), array);
1039 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1042 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1043 array.put(value.trim());
1044 object.put(keySet.getKey().trim(), array);
1046 object.put(keySet.getKey().trim(), value.trim());
1051 return object.toString();
1054 @SuppressWarnings("unchecked")
1055 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
1056 JSONObject object = new JSONObject();
1057 Map<String, String> map;
1058 Object returnClass = subAttributeMap.get(name);
1059 map = (Map<String, String>) returnClass;
1062 for (Entry<String, String> m : map.entrySet()) {
1063 String[] splitValue = m.getValue().split(":");
1064 array = new JSONArray();
1065 if (subAttributeMap.containsKey(splitValue[0])) {
1066 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1067 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1068 object.put(m.getKey().trim(), array);
1070 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1073 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1074 array.put(splitValue[0].trim());
1075 object.put(m.getKey().trim(), array);
1077 object.put(m.getKey().trim(), splitValue[0].trim());
1085 public JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1086 return convertToArrayElement(json, new HashSet<>(), keyValue);
1089 private JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1090 for (String key : json.keySet()) {
1091 Object obj = json.get(key);
1092 if (key.equals(keyValue.trim())) {
1093 if (!(obj instanceof JSONArray)) {
1094 JSONArray newJsonArray = new JSONArray();
1095 newJsonArray.put(obj);
1096 json.put(key, newJsonArray);
1098 LOGGER.info("key : " + key);
1099 LOGGER.info("obj : " + obj);
1100 LOGGER.info("json.get(key) : " + json.get(key));
1101 LOGGER.info("keyValue : " + keyValue);
1102 keys.addAll(json.keySet());
1107 if (obj instanceof JSONObject) {
1108 convertToArrayElement(json.getJSONObject(key), keyValue);
1111 if (obj instanceof JSONArray) {
1112 convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
1120 * getManyTrueProperties.
1122 * @param referAttributes String
1123 * @return a Set of String
1125 public Set<String> getManyTrueProperties(String referAttributes) {
1126 LOGGER.info("referAttributes : " + referAttributes);
1127 Set<String> manyTrueProperties = new HashSet<>();
1129 if (referAttributes != null) {
1130 String[] referAarray = referAttributes.split(",");
1131 String[] element = null;
1132 for (int i = 0; i < referAarray.length; i++) {
1133 element = referAarray[i].split("=");
1134 if (element.length > 1 && element[1].contains("MANY-true")) {
1135 manyTrueProperties.add(element[0]);
1140 return manyTrueProperties;
1143 // call this method to start the recursive
1144 private Set<String> getAllKeys(JSONObject json) {
1145 return getAllKeys(json, new HashSet<>());
1148 private Set<String> getAllKeys(JSONArray arr) {
1149 return getAllKeys(arr, new HashSet<>());
1152 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1153 for (int i = 0; i < arr.length(); i++) {
1154 Object obj = arr.get(i);
1155 if (obj instanceof JSONObject) {
1156 keys.addAll(getAllKeys(arr.getJSONObject(i)));
1158 if (obj instanceof JSONArray) {
1159 keys.addAll(getAllKeys(arr.getJSONArray(i)));
1166 // this method returns a set of keys with "MANY-true" defined in their value.
1167 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1168 for (String key : json.keySet()) {
1169 Object obj = json.get(key);
1170 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
1171 LOGGER.info("key : " + key);
1172 LOGGER.info("obj : " + obj);
1173 allManyTrueKeys.add(key);
1175 if (obj instanceof JSONObject) {
1176 keys.addAll(getAllKeys(json.getJSONObject(key)));
1178 if (obj instanceof JSONArray) {
1179 keys.addAll(getAllKeys(json.getJSONArray(key)));
1187 value = {"/policyController/getModelServiceVersioneData.htm"},
1188 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1189 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
1190 throws IOException {
1191 ObjectMapper mapper = new ObjectMapper();
1192 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1194 response.setCharacterEncoding("UTF-8");
1195 response.setContentType("application / json");
1196 request.setCharacterEncoding("UTF-8");
1197 List<Object> list = new ArrayList<>();
1198 String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", "");
1199 String servicename = value.split("-v")[0];
1200 Set<String> returnList = getVersionList(servicename);
1201 list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}"));
1202 response.getWriter().write(list.toString());
1206 private Set<String> getVersionList(String name) {
1207 MicroServiceModels workingModel;
1208 Set<String> list = new HashSet<>();
1209 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1210 for (int i = 0; i < microServiceModelsData.size(); i++) {
1211 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1212 if (workingModel.getVersion() != null) {
1213 list.add(workingModel.getVersion());
1215 list.add("Default");
1221 private MicroServiceModels getAttributeObject(String name, String version) {
1222 MicroServiceModels workingModel = new MicroServiceModels();
1223 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1224 for (int i = 0; i < microServiceModelsData.size(); i++) {
1225 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1226 if (version != null) {
1227 if (workingModel.getVersion() != null) {
1228 if (workingModel.getVersion().equals(version)) {
1229 return workingModel;
1232 return workingModel;
1235 return workingModel;
1239 return workingModel;
1242 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
1243 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName",
1248 value = {"/get_DCAEPriorityValues"},
1249 method = {org.springframework.web.bind.annotation.RequestMethod.GET},
1250 produces = MediaType.APPLICATION_JSON_VALUE)
1251 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
1253 Map<String, Object> model = new HashMap<>();
1254 ObjectMapper mapper = new ObjectMapper();
1255 List<String> priorityList = new ArrayList<>();
1257 for (int i = 1; i < priorityCount; i++) {
1258 priorityList.add(String.valueOf(i));
1260 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1261 response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
1262 } catch (Exception e) {
1268 * prePopulateDCAEMSPolicyData.
1270 * @param policyAdapter PolicyRestAdapter
1271 * @param entity PolicyEntity
1273 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1274 if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
1277 Object policyData = policyAdapter.getPolicyData();
1278 PolicyType policy = (PolicyType) policyData;
1279 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1280 String policyNameValue =
1281 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
1282 policyAdapter.setPolicyName(policyNameValue);
1283 String description = "";
1285 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1286 } catch (Exception e) {
1287 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
1288 description = policy.getDescription();
1290 policyAdapter.setPolicyDescription(description);
1291 // Get the target data under policy.
1292 TargetType target = policy.getTarget();
1293 if (target == null) {
1296 for (AnyOfType anyOf : target.getAnyOf()) {
1297 for (AllOfType allOf : anyOf.getAllOf()) {
1298 // Under AllOFType we have Match
1299 List<MatchType> matchList = allOf.getMatch();
1300 if (matchList == null) {
1303 Iterator<MatchType> iterMatch = matchList.iterator();
1305 // Can someone please explain why the matchList MUST have
1306 // more than 1 matches???
1308 while (matchList.size() > 1 && iterMatch.hasNext()) {
1309 MatchType match = iterMatch.next();
1311 // Under the match we have attribute value and
1312 // attributeDesignator. So,finally down to the actual attribute.
1314 AttributeValueType attributeValue = match.getAttributeValue();
1315 String value = (String) attributeValue.getContent().get(0);
1316 AttributeDesignatorType designator = match.getAttributeDesignator();
1317 String attributeId = designator.getAttributeId();
1318 // First match in the target is OnapName, so set that value.
1319 if ("ONAPName".equals(attributeId)) {
1320 policyAdapter.setOnapName(value);
1321 } else if ("ConfigName".equals(attributeId)) {
1322 policyAdapter.setConfigName(value);
1323 } else if ("uuid".equals(attributeId)) {
1324 policyAdapter.setUuid(value);
1325 } else if ("location".equals(attributeId)) {
1326 policyAdapter.setLocation(value);
1327 } else if ("RiskType".equals(attributeId)) {
1328 policyAdapter.setRiskType(value);
1329 } else if ("RiskLevel".equals(attributeId)) {
1330 policyAdapter.setRiskLevel(value);
1331 } else if ("guard".equals(attributeId)) {
1332 policyAdapter.setGuard(value);
1333 } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
1334 String newDate = new PolicyController().convertDate(value);
1335 policyAdapter.setTtlDate(newDate);
1338 readFile(policyAdapter, entity);
1346 * @param str the str
1347 * @param split the split
1350 public Map<String, String> convert(String str, String split) {
1351 Map<String, String> map = new HashMap<>();
1352 for (final String entry : str.split(split)) {
1353 String[] parts = entry.split("=");
1354 map.put(parts[0], parts[1]);
1362 * @param policyAdapter the policy adapter
1363 * @param entity the entity
1365 @SuppressWarnings("unchecked")
1366 public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1368 DCAEMicroServiceObject msBody =
1369 new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
1370 DCAEMicroServiceObject.class);
1371 String policyScopeName = getPolicyScope(msBody.getPolicyScope());
1372 policyAdapter.setPolicyScope(policyScopeName);
1374 policyAdapter.setPriority(msBody.getPriority());
1376 if (msBody.getVersion() != null) {
1377 policyAdapter.setServiceType(msBody.getService());
1378 policyAdapter.setVersion(msBody.getVersion());
1380 policyAdapter.setServiceType(msBody.getService());
1383 LinkedHashMap<String, ?> content = (LinkedHashMap<String, ?>) msBody.getUiContent();
1384 if (content == null) {
1385 content = (LinkedHashMap<String, ?>) msBody.getContent();
1387 if (content != null) {
1388 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1389 LinkedHashMap<String, ?> map = content;
1390 readRecursivlyJSONContent(map, data);
1391 policyAdapter.setRuleData(data);
1394 } catch (Exception e) {
1400 @SuppressWarnings({"rawtypes", "unchecked"})
1401 public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) {
1402 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1403 Object key = iterator.next();
1404 Object value = map.get(key);
1405 if (value instanceof LinkedHashMap<?, ?>) {
1406 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1407 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1408 for (Entry<String, Object> entry : secondObjec.entrySet()) {
1409 data.put(key + "." + entry.getKey(), entry.getValue());
1411 } else if (value instanceof ArrayList) {
1412 ArrayList<?> jsonArrayVal = (ArrayList<?>) value;
1413 for (int i = 0; i < jsonArrayVal.size(); i++) {
1414 Object arrayvalue = jsonArrayVal.get(i);
1415 if (arrayvalue instanceof LinkedHashMap<?, ?>) {
1416 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1417 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1418 for (Entry<String, Object> entry : newData.entrySet()) {
1419 data.put(key + "@" + i + "." + entry.getKey(), entry.getValue());
1421 } else if (arrayvalue instanceof ArrayList) {
1422 ArrayList<?> jsonArrayVal1 = (ArrayList<?>) value;
1423 for (int j = 0; j < jsonArrayVal1.size(); j++) {
1424 Object arrayvalue1 = jsonArrayVal1.get(i);
1425 data.put(key + "@" + j, arrayvalue1.toString());
1428 data.put(key + "@" + i, arrayvalue.toString());
1432 data.put(key.toString(), value.toString());
1440 * @param value String
1443 public String getPolicyScope(String value) {
1444 List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1445 if (groupList != null && !groupList.isEmpty()) {
1446 return ((GroupPolicyScopeList) groupList.get(0)).getGroupName();
1452 * Convert the map values and set into JSON body.
1454 * @param attributesMap Map of attributes
1455 * @param attributesRefMap Map of attribute references
1458 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1459 Map<String, String> attribute = new HashMap<>();
1463 for (Entry<String, String> entry : attributesMap.entrySet()) {
1464 key = entry.getKey();
1465 value = entry.getValue();
1466 attribute.put(key, value);
1468 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1469 key = entryRef.getKey();
1470 value = entryRef.getValue();
1471 attribute.put(key, value);
1473 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1474 key = entryList.getKey();
1475 value = entryList.getValue();
1476 attribute.put(key, value);
1478 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()) {
1479 key = arrayList.getKey();
1481 for (Object textList : arrayList.getValue()) {
1483 temp = new StringBuilder();
1484 temp.append("[" + textList);
1486 temp.append("," + textList);
1489 attribute.put(key, temp + "]");
1496 value = {"/ms_dictionary/set_MSModelData"},
1497 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1498 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
1499 throws IOException, FileUploadException {
1500 modelList = new ArrayList<>();
1501 dirDependencyList = new ArrayList<>();
1502 classMap = new LinkedHashMap<>();
1503 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1504 boolean zip = false;
1505 boolean yml = false;
1506 String errorMsg = "";
1507 for (FileItem item : items) {
1508 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
1509 this.newModel = new MicroServiceModels();
1511 File file = new File(item.getName());
1512 OutputStream outputStream = new FileOutputStream(file);
1513 IOUtils.copy(item.getInputStream(), outputStream);
1514 outputStream.close();
1515 this.newFile = file.toString();
1516 this.newModel.setModelName(this.newFile.split("-v")[0]);
1518 if (this.newFile.contains("-v")) {
1519 if (item.getName().endsWith(".zip")) {
1520 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1522 } else if (item.getName().endsWith(".yml")) {
1523 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1526 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1529 } catch (Exception e) {
1530 LOGGER.error("Upload error : ", e);
1531 errorMsg = "Upload error:" + e.getMessage();
1537 if (!errorMsg.isEmpty()) {
1538 response.setCharacterEncoding("UTF-8");
1539 response.setContentType("application / json");
1540 request.setCharacterEncoding("UTF-8");
1542 JSONObject json = new JSONObject();
1543 json.put("errorMsg", errorMsg);
1544 response.getWriter().write(json.toString());
1548 List<File> fileList = new ArrayList<>();
1549 MSModelUtils msModelUtils = new MSModelUtils(commonClassDao);
1550 this.directory = "model";
1552 extractFolder(this.newFile);
1553 fileList = listModelFiles(this.directory);
1555 errorMsg = msModelUtils.parseTosca(this.newFile);
1556 if (errorMsg != null) {
1557 response.setCharacterEncoding("UTF-8");
1558 response.setContentType("application / json");
1559 request.setCharacterEncoding("UTF-8");
1560 JSONObject json = new JSONObject();
1561 json.put("errorMsg", errorMsg);
1562 response.getWriter().write(json.toString());
1567 File file = new File(this.newFile);
1570 String modelType = "";
1573 // Process Main Model file first
1574 classMap = new LinkedHashMap<>();
1575 for (File file : fileList) {
1576 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
1577 retrieveDependency(file.toString());
1581 modelList = createList();
1583 cleanUp(this.newFile);
1587 modelList.add(this.newModel.getModelName());
1588 String className = this.newModel.getModelName();
1589 MSAttributeObject msAttributes = new MSAttributeObject();
1590 msAttributes.setClassName(className);
1592 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
1593 returnAttributeList.put(className, msModelUtils.getAttributeString());
1594 msAttributes.setAttribute(returnAttributeList);
1596 msAttributes.setSubClass(msModelUtils.getRetmap());
1598 msAttributes.setMatchingSet(msModelUtils.getMatchableValues());
1600 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
1602 returnReferenceList.put(className, msModelUtils.getReferenceAttributes());
1603 msAttributes.setRefAttribute(returnReferenceList);
1605 if (msModelUtils.getListConstraints() != "") {
1606 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
1607 String[] listArray = msModelUtils.getListConstraints().split("#");
1608 for (String str : listArray) {
1609 String[] strArr = str.split("=");
1610 if (strArr.length > 1) {
1611 enumList.put(strArr[0], strArr[1]);
1614 msAttributes.setEnumType(enumList);
1617 classMap = new LinkedHashMap<>();
1618 classMap.put(className, msAttributes);
1621 response.setCharacterEncoding("UTF-8");
1622 response.setContentType("application / json");
1623 request.setCharacterEncoding("UTF-8");
1625 ObjectMapper mapper = new ObjectMapper();
1626 JSONObject json = new JSONObject();
1627 json.put("classListDatas", modelList);
1628 json.put("modelDatas", mapper.writeValueAsString(classMap));
1629 json.put("modelType", modelType);
1630 json.put("dataOrderInfo", msModelUtils.getDataOrderInfo());
1631 json.put("ruleFormation", msModelUtils.getJsonRuleFormation());
1633 response.getWriter().write(json.toString());
1637 * Unzip file and store in the model directory for processing
1639 @SuppressWarnings("rawtypes")
1640 private void extractFolder(String zipFile) {
1641 final int buffer = 2048;
1642 File file = new File(zipFile);
1644 try (ZipFile zip = new ZipFile(file)) {
1645 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1646 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1647 checkZipDirectory(this.directory);
1648 new File(newPath).mkdir();
1649 Enumeration zipFileEntries = zip.entries();
1651 // Process each entry
1652 while (zipFileEntries.hasMoreElements()) {
1653 // grab a zip file entry
1654 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1655 String currentEntry = entry.getName();
1656 File destFile = new File("model" + File.separator + currentEntry);
1657 File destinationParent = destFile.getParentFile();
1659 destinationParent.mkdirs();
1661 if (!entry.isDirectory()) {
1662 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1664 byte[] data = new byte[buffer];
1665 try (FileOutputStream fos = new FileOutputStream(destFile);
1666 BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
1667 while ((currentByte = is.read(data, 0, buffer)) != -1) {
1668 dest.write(data, 0, currentByte);
1671 } catch (IOException e) {
1672 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1674 // PLD should I throw e?
1680 if (currentEntry.endsWith(".zip")) {
1681 extractFolder(destFile.getAbsolutePath());
1684 } catch (IOException e) {
1685 LOGGER.error("Failed to unzip model file " + zipFile, e);
1689 private void retrieveDependency(String workingFile) {
1691 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1692 Map<String, MSAttributeObject> tempMap;
1694 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1696 classMap.putAll(tempMap);
1697 LOGGER.info(tempMap);
1700 private List<File> listModelFiles(String directoryName) {
1701 File fileDirectory = new File(directoryName);
1702 List<File> resultList = new ArrayList<>();
1703 for (File file : fileDirectory.listFiles()) {
1704 if (file.isFile()) {
1705 resultList.add(file);
1706 } else if (file.isDirectory()) {
1707 dirDependencyList.add(file.getName());
1708 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1717 * @param path String
1719 public void cleanUp(String path) {
1722 FileUtils.forceDelete(new File(path));
1723 } catch (IOException e) {
1724 LOGGER.error("Failed to delete folder " + path, e);
1730 * checkZipDirectory.
1732 * @param zipDirectory String
1734 public void checkZipDirectory(String zipDirectory) {
1735 Path path = Paths.get(zipDirectory);
1737 if (Files.exists(path)) {
1738 cleanUp(zipDirectory);
1742 private List<String> createList() {
1743 List<String> list = new ArrayList<>();
1744 for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
1745 if (entrySet.getValue().isPolicyTempalate()) {
1746 list.add(entrySet.getKey());
1751 if (list.isEmpty()) {
1752 if (classMap.containsKey(this.newModel.getModelName())) {
1753 list.add(this.newModel.getModelName());
1761 public Map<String, String> getAttributesListRefMap() {
1762 return attributesListRefMap;
1765 public Map<String, LinkedList<String>> getArrayTextList() {
1766 return arrayTextList;
1769 public Map<String, String> getSigRules() {
1773 public void setSigRules(Map<String, String> sigRules) {
1774 this.sigRules = sigRules;
1781 class DCAEMicroServiceObject {
1783 private String service;
1784 private String location;
1785 private String uuid;
1786 private String policyName;
1787 private String description;
1788 private String configName;
1789 private String templateVersion;
1790 private String version;
1791 private String priority;
1792 private String policyScope;
1793 private String riskType;
1794 private String riskLevel;
1795 private String guard = null;
1796 private Object uiContent;
1797 private Object content;