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.MatchType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
79 import org.apache.commons.compress.utils.IOUtils;
80 import org.apache.commons.fileupload.FileItem;
81 import org.apache.commons.fileupload.FileUploadException;
82 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
83 import org.apache.commons.fileupload.servlet.ServletFileUpload;
84 import org.apache.commons.io.FileUtils;
85 import org.apache.commons.lang.StringUtils;
86 import org.json.JSONArray;
87 import org.json.JSONObject;
88 import org.onap.policy.common.logging.flexlogger.FlexLogger;
89 import org.onap.policy.common.logging.flexlogger.Logger;
90 import org.onap.policy.rest.XACMLRestProperties;
91 import org.onap.policy.rest.adapter.PolicyRestAdapter;
92 import org.onap.policy.rest.dao.CommonClassDao;
93 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
94 import org.onap.policy.rest.jpa.MicroServiceModels;
95 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
96 import org.onap.policy.rest.jpa.PolicyEntity;
97 import org.onap.policy.rest.util.MSAttributeObject;
98 import org.onap.policy.rest.util.MSModelUtils;
99 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
100 import org.onap.policy.utils.PolicyUtils;
101 import org.onap.portalsdk.core.controller.RestrictedBaseController;
102 import org.onap.portalsdk.core.web.support.JsonMessage;
103 import org.springframework.beans.factory.annotation.Autowired;
104 import org.springframework.http.MediaType;
105 import org.springframework.stereotype.Controller;
106 import org.springframework.web.bind.annotation.RequestMapping;
107 import org.springframework.web.servlet.ModelAndView;
111 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
112 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
114 private static CommonClassDao commonClassDao;
116 public static CommonClassDao getCommonClassDao() {
117 return commonClassDao;
120 public static void setCommonClassDao(CommonClassDao commonClassDao) {
121 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
124 private MicroServiceModels newModel;
125 private String newFile;
126 private String directory;
127 private List<String> modelList = new ArrayList<>();
128 private List<String> dirDependencyList = new ArrayList<>();
129 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
130 String referenceAttributes;
131 String attributeString;
132 Set<String> allManyTrueKeys = null;
133 private Map<String, String> sigRules = null;
135 public static final String DATATYPE = "data_types.policy.data.";
136 public static final String PROPERTIES = ".properties.";
137 public static final String TYPE = ".type";
138 public static final String STRING = "string";
139 public static final String INTEGER = "integer";
140 public static final String LIST = "list";
141 public static final String DEFAULT = ".default";
142 public static final String REQUIRED = ".required";
143 public static final String MATCHABLE = ".matchable";
144 public static final String MANYFALSE = ":MANY-false";
145 private static final Pattern PATTERN = Pattern.compile("[A][0-9]");
146 private static final String POLICYJSON = "policyJSON";
149 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) {
150 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
153 public CreateDcaeMicroServiceController() {
157 protected PolicyRestAdapter policyAdapter = null;
158 private int priorityCount;
159 private Map<String, String> attributesListRefMap = new HashMap<>();
160 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
161 private Map<String, String> jsonStringValues = new HashMap<>();
164 * setDataToPolicyRestAdapter.
166 * @param policyData PolicyRestAdapter
167 * @param root JsonNode
168 * @return PolicyRestAdapter
170 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
172 String jsonContent = null;
174 LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
176 String tempJson = root.get(POLICYJSON).toString();
177 JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString());
178 if (policyJson != null) {
179 tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString();
181 // ---replace empty value with the value below before calling decodeContent method.
182 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
183 LOGGER.info("dummyValue:" + dummyValue);
185 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
186 ObjectMapper mapper = new ObjectMapper();
187 JsonNode tempJsonNode = mapper.readTree(tempJson);
188 jsonContent = decodeContent(tempJsonNode).toString();
189 constructJson(policyData, jsonContent, dummyValue);
190 } catch (Exception e) {
191 LOGGER.error("Error while decoding microservice content", e);
194 // ----Here is the final step to reset the original value back.
195 if (policyData.getJsonBody() != null && jsonStringValues.size() > 0) {
196 String contentBody = policyData.getJsonBody();
197 JSONObject contentJson = new JSONObject(contentBody);
198 JSONObject content = contentJson.getJSONObject("content");
199 content = setOriginalJsonObject(content, jsonStringValues);
200 contentJson.put("content", content);
201 policyData.setJsonBody(contentJson.toString());
207 private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
208 for (Object key : jsonObj.keySet()) {
209 String keyStr = (String) key;
210 Object keyvalue = jsonObj.get(keyStr);
211 if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) {
212 jsonStringValues.put(keyStr, keyvalue.toString());
213 // --- set default value
214 jsonObj.put(keyStr, "JSON_STRING");
217 // for nested objects iteration if required
218 if (keyvalue instanceof JSONObject) {
219 saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
220 // --- set default value
221 jsonObj.put(keyStr, "JSON_STRING");
224 if (keyvalue instanceof JSONArray) {
225 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
226 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
227 saveOriginalJsonObject(temp, jsonStringValues);
235 private JSONObject setOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
236 for (Object key : jsonObj.keySet()) {
237 String keyStr = (String) key;
238 Object keyvalue = jsonObj.get(keyStr);
239 String originalValue = getOriginalValue(keyStr);
240 if (originalValue != null) {
241 jsonObj.put(keyStr, originalValue);
244 // for nested objects iteration if required
245 if (keyvalue instanceof JSONObject) {
246 setOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
247 jsonObj.put(keyStr, originalValue);
250 if (keyvalue instanceof JSONArray) {
251 for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) {
252 JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i);
253 setOriginalJsonObject(temp, jsonStringValues);
261 private GroupPolicyScopeList getPolicyObject(String policyScope) {
262 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
265 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue)
267 ObjectWriter om = new ObjectMapper().writer();
269 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
270 MicroServiceModels returnModel = new MicroServiceModels();
271 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
272 if (policyAdapter.getServiceType() != null) {
273 microServiceObject.setService(policyAdapter.getServiceType());
274 microServiceObject.setVersion(policyAdapter.getVersion());
275 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
277 if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) {
278 if (policyAdapter.getUuid() != null) {
279 microServiceObject.setUuid(policyAdapter.getUuid());
281 if (policyAdapter.getLocation() != null) {
282 microServiceObject.setLocation(policyAdapter.getLocation());
284 if (policyAdapter.getConfigName() != null) {
285 microServiceObject.setConfigName(policyAdapter.getConfigName());
287 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
288 if (policyScopeValue != null) {
289 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
293 if (policyAdapter.getPolicyName() != null) {
294 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
296 if (policyAdapter.getPolicyDescription() != null) {
297 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
299 if (policyAdapter.getPriority() != null) {
300 microServiceObject.setPriority(policyAdapter.getPriority());
302 microServiceObject.setPriority("9999");
305 if (policyAdapter.getRiskLevel() != null) {
306 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
308 if (policyAdapter.getRiskType() != null) {
309 microServiceObject.setRiskType(policyAdapter.getRiskType());
311 if (policyAdapter.getGuard() != null) {
312 microServiceObject.setGuard(policyAdapter.getGuard());
314 microServiceObject.setContent(jsonContent);
315 String modelName = policyAdapter.getServiceType();
316 String versionName = policyAdapter.getVersion();
317 List<Object> triggerData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version",
318 modelName + ":" + versionName);
319 MicroServiceModels model = null;
320 boolean ruleCheck = false;
321 if (!triggerData.isEmpty()) {
322 model = (MicroServiceModels) triggerData.get(0);
323 if (model.getRuleFormation() != null) {
324 microServiceObject.setUiContent(jsonContent);
329 json = om.writeValueAsString(microServiceObject);
330 } catch (JsonProcessingException e) {
331 LOGGER.error("Error writing out the object", e);
333 LOGGER.info("input json: " + json);
334 LOGGER.info("input jsonContent: " + jsonContent);
335 String cleanJson = cleanUpJson(json);
336 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
338 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
339 LOGGER.info("tempJson: " + tempJson);
340 cleanJson = removeNullAttributes(tempJson);
341 if (cleanJson.contains("\\")) {
342 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\"}, new String[] {""});
344 policyAdapter.setJsonBody(cleanJson);
346 ObjectMapper mapper = new ObjectMapper();
347 JsonNode tempJsonNode = mapper.readTree(cleanJson);
349 return policyAdapter;
351 ObjectNode finalJson = (ObjectNode) tempJsonNode;
352 JsonNode object = tempJsonNode.get("content");
353 String primaryKey1 = model.getRuleFormation();
354 String[] primaryKeyForSignatures = primaryKey1.split("@");
355 for (String primaryKeyForSignature : primaryKeyForSignatures) {
356 String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
357 JsonNode triggerSig = object.get(primarykeyAlarm);
358 sigRules = new HashMap<>();
359 String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
360 StringBuilder sb = null;
361 if (triggerSig instanceof ArrayNode) {
362 for (int i = 0; i < triggerSig.size(); i++) {
363 sb = new StringBuilder();
364 parseData(triggerSig.get(i), parseKey);
366 List<?> keyList = new ArrayList<>(sigRules.keySet());
367 for (int j = keyList.size() - 1; j >= 0; j--) {
368 String key = (String) keyList.get(j);
369 String jsonNode = sigRules.get(key);
370 constructRule(sb, jsonNode, sigRules);
372 sb.append(")").toString();
373 putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
374 sigRules = new HashMap<>();
377 parseData(triggerSig, parseKey);
380 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());
494 * removeNullAttributes.
496 * @param cleanJson String
499 public String removeNullAttributes(String cleanJson) {
500 ObjectMapper mapper = new ObjectMapper();
503 JsonNode rootNode = mapper.readTree(cleanJson);
504 JsonNode returnNode = mapper.readTree(cleanJson);
505 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
506 boolean remove = false;
507 JsonObject removed = null;
508 boolean contentChanged = false;
509 while (fieldsIterator.hasNext()) {
510 Map.Entry<String, JsonNode> field = fieldsIterator.next();
511 final String key = field.getKey();
512 final JsonNode value = field.getValue();
513 if ("content".equalsIgnoreCase(key)) {
514 String contentStr = value.toString();
515 try (JsonReader reader = Json.createReader(new StringReader(contentStr))) {
516 JsonObject jsonContent = reader.readObject();
517 removed = removeNull(jsonContent);
518 if (!jsonContent.toString().equals(removed.toString())) {
519 contentChanged = true;
523 if (value == null || value.isNull()) {
524 ((ObjectNode) returnNode).remove(key);
529 cleanJson = returnNode.toString();
531 if (value == null || value.isNull()) {
532 ((ObjectNode) returnNode).remove(key);
537 cleanJson = returnNode.toString();
540 if (contentChanged) {
541 // set modified content to cleanJson
542 JSONObject jsonObject = new JSONObject(cleanJson);
543 jsonObject.put("content", removed.toString());
544 cleanJson = cleanUpJson(jsonObject.toString());
547 } catch (IOException e) {
548 LOGGER.error("Error writing out the JsonNode", e);
554 * To verify if it is a JSON string. If it is, then return its original value.
556 * @param key holds the values
559 private String getOriginalValue(String key) {
560 for (String k : jsonStringValues.keySet()) {
561 if (k.contains("@")) {
562 String[] arrOfKeys = k.split("@");
563 for (int i = 0; i < arrOfKeys.length; i++) {
564 if (arrOfKeys[i].contains(".")) {
565 arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
566 if (arrOfKeys[i].equals(key)) {
567 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
568 new String[] {"\\\""});
573 if (k.endsWith(key)) {
574 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
584 * @param array JsonArray
587 public JsonArray removeNull(JsonArray array) {
588 JsonArrayBuilder builder = Json.createArrayBuilder();
590 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++index) {
591 JsonValue value = it.next();
592 switch (value.getValueType()) {
594 JsonArray tempArray = removeNull(array.getJsonArray(index));
595 if (!tempArray.isEmpty()) {
596 builder.add(tempArray);
600 JsonObject object = removeNull(array.getJsonObject(index));
601 if (!object.isEmpty()) {
606 String str = array.getString(index);
607 if (str != null && !str.isEmpty()) {
612 builder.add(array.getJsonNumber(index));
616 builder.add(array.getBoolean(index));
623 return builder.build();
629 * @param obj JsonObject
632 public JsonObject removeNull(JsonObject obj) {
633 JsonObjectBuilder builder = Json.createObjectBuilder();
634 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
635 Entry<String, JsonValue> entry = it.next();
636 String key = entry.getKey();
637 JsonValue value = entry.getValue();
638 switch (value.getValueType()) {
640 JsonArray array = removeNull(obj.getJsonArray(key));
641 if (!array.isEmpty()) {
642 builder.add(key, array);
646 JsonObject object = removeNull(obj.getJsonObject(key));
647 if (!object.isEmpty()) {
648 if (!jsonStringValues.isEmpty()) {
649 String originalValue = getOriginalValue(key);
650 if (originalValue != null) {
651 builder.add(key, object.toString());
655 builder.add(key, object);
659 String str = obj.getString(key);
660 if (str != null && !str.isEmpty()) {
661 if (!jsonStringValues.isEmpty()) {
662 String originalValue = getOriginalValue(key);
663 if (originalValue != null) {
664 str = getOriginalValue(key);
667 builder.add(key, str);
671 builder.add(key, obj.getJsonNumber(key));
675 builder.add(key, obj.getBoolean(key));
682 return builder.build();
691 public String cleanUpJson(String json) {
692 String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
693 new String[] {"\\", "\\", "\\"});
694 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
696 StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"});
698 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""},
699 new String[] {"\"", "\"", "[{", "}]"});
700 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[{", "}]\""}, 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[] {"[", "]"});
715 * @param jsonNode JsonNode
718 public JSONObject decodeContent(JsonNode jsonNode) {
719 Iterator<JsonNode> jsonElements = jsonNode.elements();
720 Iterator<String> jsonKeys = jsonNode.fieldNames();
721 Map<String, String> element = new TreeMap<>();
722 while (jsonElements.hasNext() && jsonKeys.hasNext()) {
723 element.put(jsonKeys.next(), jsonElements.next().toString());
725 JSONObject jsonResult = new JSONObject();
726 JSONArray jsonArray = null;
727 String oldValue = null;
728 String nodeKey = null;
729 String arryKey = null;
730 Boolean isArray = false;
731 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
732 ObjectNode node = nodeFactory.objectNode();
733 String prevKey = null;
735 for (Entry<String, String> entry : element.entrySet()) {
736 String key = entry.getKey();
737 String value = entry.getValue();
738 if (key.contains(".")) {
739 presKey = key.substring(0, key.indexOf('.'));
740 } else if (key.contains("@")) {
741 presKey = key.substring(0, key.indexOf('@'));
745 // first check if we are different from old.
746 LOGGER.info(key + "\n");
747 if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".")
748 && oldValue != null) {
749 if (!oldValue.equals(key.substring(0, key.indexOf('@')))) {
750 jsonResult.put(oldValue, jsonArray);
751 jsonArray = new JSONArray();
753 } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) {
754 jsonResult.put(oldValue, jsonArray);
756 jsonArray = new JSONArray();
761 if (key.contains(".")) {
762 if (nodeKey == null) {
763 nodeKey = key.substring(0, key.indexOf('.'));
765 if (nodeKey.equals(key.substring(0, key.indexOf('.')))) {
766 node.put(key.substring(key.indexOf('.') + 1), value);
768 if (node.size() != 0) {
769 if (nodeKey.contains("@")) {
770 if (arryKey == null) {
771 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
773 if (nodeKey.endsWith("@0")) {
775 jsonArray = new JSONArray();
777 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
778 jsonArray.put(decodeContent(node));
780 if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@'))))
781 || !key.contains("@")) {
782 jsonResult.put(arryKey, jsonArray);
783 jsonArray = new JSONArray();
785 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
788 jsonResult.put(nodeKey, decodeContent(node));
790 node = nodeFactory.objectNode();
792 nodeKey = key.substring(0, key.indexOf('.'));
793 if (nodeKey.contains("@")) {
794 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
796 node.put(key.substring(key.indexOf('.') + 1), value);
799 if (node.size() != 0) {
800 if (nodeKey.contains("@")) {
801 if (arryKey == null) {
802 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
804 if (nodeKey.endsWith("@0")) {
806 jsonArray = new JSONArray();
808 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
809 jsonArray.put(decodeContent(node));
811 jsonResult.put(arryKey, jsonArray);
812 jsonArray = new JSONArray();
813 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
816 jsonResult.put(nodeKey, decodeContent(node));
818 node = nodeFactory.objectNode();
820 if (key.contains("@")) {
822 if (key.endsWith("@0") || jsonArray == null) {
823 jsonArray = new JSONArray();
825 } else if (!key.contains("@")) {
829 if (oldValue == null) {
830 oldValue = key.substring(0, key.indexOf('@'));
832 if (oldValue != prevKey) {
833 oldValue = key.substring(0, key.indexOf('@'));
835 if (oldValue.equals(key.substring(0, key.indexOf('@')))) {
836 jsonArray.put(value);
838 jsonResult.put(oldValue, jsonArray);
839 jsonArray = new JSONArray();
841 oldValue = key.substring(0, key.indexOf('@'));
843 jsonResult.put(key, value);
847 if (node.size() > 0) {
848 if (nodeKey.contains("@")) {
849 if (jsonArray == null) {
850 jsonArray = new JSONArray();
852 if (arryKey == null) {
853 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
855 jsonArray.put(decodeContent(node));
856 jsonResult.put(arryKey, jsonArray);
859 jsonResult.put(nodeKey, decodeContent(node));
862 if (isArray && jsonArray.length() > 0) {
863 jsonResult.put(oldValue, jsonArray);
869 value = {"/policyController/getDCAEMSTemplateData.htm"},
870 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
871 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
873 // TreeSet is used to ensure that individual items appear before their containing collection.
874 allManyTrueKeys = new TreeSet<>();
875 ObjectMapper mapper = new ObjectMapper();
876 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
877 JsonNode root = mapper.readTree(request.getReader());
879 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
880 String servicename = value.split("-v")[0];
881 String version = null;
882 if (value.contains("-v")) {
883 version = value.split("-v")[1];
885 MicroServiceModels returnModel = getAttributeObject(servicename, version);
887 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
888 JSONObject jsonHdDefaultObj = null;
889 if (returnHeaderDefauls != null) {
890 jsonHdDefaultObj = new JSONObject();
891 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
892 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
893 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
894 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
895 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
897 String headDefautlsData = "";
898 if (jsonHdDefaultObj != null) {
899 headDefautlsData = jsonHdDefaultObj.toString();
901 headDefautlsData = "null";
904 // Get all keys with "MANY-true" defined in their value from subAttribute
905 Set<String> allkeys = null;
906 if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
907 JSONObject json = new JSONObject(returnModel.getSub_attributes());
909 allkeys = allManyTrueKeys;
910 allManyTrueKeys = new TreeSet<>();
911 LOGGER.info("allkeys : " + allkeys);
914 // Get element order info
915 String dataOrderInfo = returnModel.getDataOrderInfo();
916 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
917 dataOrderInfo = "\"" + dataOrderInfo + "\"";
919 LOGGER.info("dataOrderInfo : " + dataOrderInfo);
921 String allMnyTrueKeys = "";
922 if (allkeys != null) {
923 allMnyTrueKeys = allkeys.toString();
926 String jsonModel = createMicroSeriveJson(returnModel);
928 JSONObject jsonObject = new JSONObject(jsonModel);
930 JSONObject finalJsonObject = null;
931 if (allkeys != null) {
932 Iterator<String> iter = allkeys.iterator();
933 while (iter.hasNext()) {
934 // Convert to array values for MANY-true keys
935 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
936 jsonObject = finalJsonObject;
940 if (finalJsonObject != null) {
941 LOGGER.info(finalJsonObject.toString());
942 jsonModel = finalJsonObject.toString();
945 // get all properties with "MANY-true" defined in Ref_attributes
946 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
947 if (manyTrueProperties != null) {
948 JSONObject jsonObj = new JSONObject(jsonModel);
949 for (String s : manyTrueProperties) {
951 // convert to array element for MANY-true properties
952 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
953 jsonObj = finalJsonObject;
956 if (finalJsonObject != null) {
957 LOGGER.info(finalJsonObject.toString());
958 jsonModel = finalJsonObject.toString();
962 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
963 response.setContentType(PolicyUtils.APPLICATION_JSON);
964 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
965 List<Object> list = new ArrayList<>();
966 String responseString = mapper.writeValueAsString(returnModel);
968 JSONObject json = null;
970 if ("".equals(allMnyTrueKeys)) {
971 json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
972 + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
974 json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel
975 + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
976 + headDefautlsData + "}");
979 response.getWriter().write(list.toString());
983 @SuppressWarnings({"unchecked", "rawtypes"})
984 private String createMicroSeriveJson(MicroServiceModels returnModel) {
985 Map<String, String> attributeMap = new HashMap<>();
986 Map<String, String> refAttributeMap = new HashMap<>();
987 String attribute = returnModel.getAttributes();
988 if (attribute != null) {
989 attribute = attribute.trim();
991 String refAttribute = returnModel.getRef_attributes();
992 if (refAttribute != null) {
993 refAttribute = refAttribute.trim();
995 String enumAttribute = returnModel.getEnumValues();
996 if (enumAttribute != null) {
997 enumAttribute = enumAttribute.trim();
999 if (!StringUtils.isEmpty(attribute)) {
1000 attributeMap = convert(attribute, ",");
1002 if (!StringUtils.isEmpty(refAttribute)) {
1003 refAttributeMap = convert(refAttribute, ",");
1006 Gson gson = new Gson();
1008 String subAttributes = returnModel.getSub_attributes();
1009 if (subAttributes != null) {
1010 subAttributes = subAttributes.trim();
1015 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
1017 JSONObject object = new JSONObject();
1019 for (Entry<String, String> keySet : attributeMap.entrySet()) {
1020 JSONArray array = new JSONArray();
1021 String value = keySet.getValue();
1022 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1024 object.put(keySet.getKey().trim(), array);
1026 object.put(keySet.getKey().trim(), value.trim());
1030 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
1031 JSONArray array = new JSONArray();
1032 String value = keySet.getValue().split(":")[0];
1033 if (gsonObject.containsKey(value)) {
1034 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1035 array.put(recursiveReference(value, gsonObject, enumAttribute));
1036 object.put(keySet.getKey().trim(), array);
1038 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
1041 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
1042 array.put(value.trim());
1043 object.put(keySet.getKey().trim(), array);
1045 object.put(keySet.getKey().trim(), value.trim());
1050 return object.toString();
1053 @SuppressWarnings("unchecked")
1054 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
1055 JSONObject object = new JSONObject();
1056 Map<String, String> map;
1057 Object returnClass = subAttributeMap.get(name);
1058 map = (Map<String, String>) returnClass;
1061 for (Entry<String, String> m : map.entrySet()) {
1062 String[] splitValue = m.getValue().split(":");
1063 array = new JSONArray();
1064 if (subAttributeMap.containsKey(splitValue[0])) {
1065 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1066 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1067 object.put(m.getKey().trim(), array);
1069 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
1072 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
1073 array.put(splitValue[0].trim());
1074 object.put(m.getKey().trim(), array);
1076 object.put(m.getKey().trim(), splitValue[0].trim());
1084 public JSONObject convertToArrayElement(JSONObject json, String keyValue) {
1085 return convertToArrayElement(json, new HashSet<>(), keyValue);
1088 private JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
1089 for (String key : json.keySet()) {
1090 Object obj = json.get(key);
1091 if (key.equals(keyValue.trim())) {
1092 if (!(obj instanceof JSONArray)) {
1093 JSONArray newJsonArray = new JSONArray();
1094 newJsonArray.put(obj);
1095 json.put(key, newJsonArray);
1097 LOGGER.info("key : " + key);
1098 LOGGER.info("obj : " + obj);
1099 LOGGER.info("json.get(key) : " + json.get(key));
1100 LOGGER.info("keyValue : " + keyValue);
1101 keys.addAll(json.keySet());
1106 if (obj instanceof JSONObject) {
1107 convertToArrayElement(json.getJSONObject(key), keyValue);
1110 if (obj instanceof JSONArray) {
1111 convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
1119 * getManyTrueProperties.
1121 * @param referAttributes String
1122 * @return a Set of String
1124 public Set<String> getManyTrueProperties(String referAttributes) {
1125 LOGGER.info("referAttributes : " + referAttributes);
1126 Set<String> manyTrueProperties = new HashSet<>();
1128 if (referAttributes != null) {
1129 String[] referAarray = referAttributes.split(",");
1130 String[] element = null;
1131 for (int i = 0; i < referAarray.length; i++) {
1132 element = referAarray[i].split("=");
1133 if (element.length > 1 && element[1].contains("MANY-true")) {
1134 manyTrueProperties.add(element[0]);
1139 return manyTrueProperties;
1142 // call this method to start the recursive
1143 private Set<String> getAllKeys(JSONObject json) {
1144 return getAllKeys(json, new HashSet<>());
1147 private Set<String> getAllKeys(JSONArray arr) {
1148 return getAllKeys(arr, new HashSet<>());
1151 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1152 for (int i = 0; i < arr.length(); i++) {
1153 Object obj = arr.get(i);
1154 if (obj instanceof JSONObject) {
1155 keys.addAll(getAllKeys(arr.getJSONObject(i)));
1157 if (obj instanceof JSONArray) {
1158 keys.addAll(getAllKeys(arr.getJSONArray(i)));
1165 // this method returns a set of keys with "MANY-true" defined in their value.
1166 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1167 for (String key : json.keySet()) {
1168 Object obj = json.get(key);
1169 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
1170 LOGGER.info("key : " + key);
1171 LOGGER.info("obj : " + obj);
1172 allManyTrueKeys.add(key);
1174 if (obj instanceof JSONObject) {
1175 keys.addAll(getAllKeys(json.getJSONObject(key)));
1177 if (obj instanceof JSONArray) {
1178 keys.addAll(getAllKeys(json.getJSONArray(key)));
1186 * getModelServiceVersionData.
1188 * @param request HttpServletRequest
1189 * @param response HttpServletResponse
1190 * @return ModelAndView
1191 * @throws IOException IOException
1194 value = {"/policyController/getModelServiceVersioneData.htm"},
1195 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1196 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
1197 throws IOException {
1198 ObjectMapper mapper = new ObjectMapper();
1199 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1201 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
1202 response.setContentType(PolicyUtils.APPLICATION_JSON);
1203 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
1204 List<Object> list = new ArrayList<>();
1205 String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", "");
1206 String servicename = value.split("-v")[0];
1207 Set<String> returnList = getVersionList(servicename);
1208 list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}"));
1209 response.getWriter().write(list.toString());
1213 private Set<String> getVersionList(String name) {
1214 MicroServiceModels workingModel;
1215 Set<String> list = new HashSet<>();
1216 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1217 for (int i = 0; i < microServiceModelsData.size(); i++) {
1218 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1219 if (workingModel.getVersion() != null) {
1220 list.add(workingModel.getVersion());
1222 list.add("Default");
1228 private MicroServiceModels getAttributeObject(String name, String version) {
1229 MicroServiceModels workingModel = new MicroServiceModels();
1230 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1231 for (int i = 0; i < microServiceModelsData.size(); i++) {
1232 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1233 if (version != null) {
1234 if (workingModel.getVersion() != null) {
1235 if (workingModel.getVersion().equals(version)) {
1236 return workingModel;
1239 return workingModel;
1242 return workingModel;
1246 return workingModel;
1249 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
1250 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName",
1255 value = {"/get_DCAEPriorityValues"},
1256 method = {org.springframework.web.bind.annotation.RequestMethod.GET},
1257 produces = MediaType.APPLICATION_JSON_VALUE)
1258 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
1260 Map<String, Object> model = new HashMap<>();
1261 ObjectMapper mapper = new ObjectMapper();
1262 List<String> priorityList = new ArrayList<>();
1264 for (int i = 1; i < priorityCount; i++) {
1265 priorityList.add(String.valueOf(i));
1267 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1268 response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
1269 } catch (Exception e) {
1275 * prePopulateDCAEMSPolicyData.
1277 * @param policyAdapter PolicyRestAdapter
1278 * @param entity PolicyEntity
1280 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1281 if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
1284 Object policyData = policyAdapter.getPolicyData();
1285 PolicyType policy = (PolicyType) policyData;
1286 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1287 String policyNameValue =
1288 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
1289 policyAdapter.setPolicyName(policyNameValue);
1290 String description = "";
1292 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1293 } catch (Exception e) {
1294 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
1295 description = policy.getDescription();
1297 policyAdapter.setPolicyDescription(description);
1298 // Get the target data under policy.
1299 TargetType target = policy.getTarget();
1300 if (target == null) {
1303 for (AnyOfType anyOf : target.getAnyOf()) {
1304 for (AllOfType allOf : anyOf.getAllOf()) {
1305 // Under AllOFType we have Match
1306 List<MatchType> matchList = allOf.getMatch();
1307 if (matchList == null) {
1310 Iterator<MatchType> iterMatch = matchList.iterator();
1312 // Can someone please explain why the matchList MUST have
1313 // more than 1 matches???
1315 while (matchList.size() > 1 && iterMatch.hasNext()) {
1316 MatchType match = iterMatch.next();
1318 // Under the match we have attribute value and
1319 // attributeDesignator. So,finally down to the actual attribute.
1321 // First match in the target is OnapName, so set that value.
1322 policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
1323 (String) match.getAttributeValue().getContent().get(0));
1325 readFile(policyAdapter, entity);
1333 * @param str the str
1334 * @param split the split
1337 public Map<String, String> convert(String str, String split) {
1338 Map<String, String> map = new HashMap<>();
1339 for (final String entry : str.split(split)) {
1340 String[] parts = entry.split("=");
1341 map.put(parts[0], parts[1]);
1349 * @param policyAdapter the policy adapter
1350 * @param entity the entity
1352 @SuppressWarnings("unchecked")
1353 public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1355 DCAEMicroServiceObject msBody =
1356 new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
1357 DCAEMicroServiceObject.class);
1358 String policyScopeName = getPolicyScope(msBody.getPolicyScope());
1359 policyAdapter.setPolicyScope(policyScopeName);
1361 policyAdapter.setPriority(msBody.getPriority());
1363 if (msBody.getVersion() != null) {
1364 policyAdapter.setServiceType(msBody.getService());
1365 policyAdapter.setVersion(msBody.getVersion());
1367 policyAdapter.setServiceType(msBody.getService());
1370 LinkedHashMap<String, ?> content = (LinkedHashMap<String, ?>) msBody.getUiContent();
1371 if (content == null) {
1372 content = (LinkedHashMap<String, ?>) msBody.getContent();
1374 if (content != null) {
1375 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1376 LinkedHashMap<String, ?> map = content;
1377 readRecursivlyJSONContent(map, data);
1378 policyAdapter.setRuleData(data);
1381 } catch (Exception e) {
1388 * readRecursivlyJSONContent.
1390 * @param map Map of String to something
1391 * @param data Map of String to Object
1393 @SuppressWarnings({"rawtypes", "unchecked"})
1394 public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) {
1395 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1396 Object key = iterator.next();
1397 Object value = map.get(key);
1398 if (value instanceof LinkedHashMap<?, ?>) {
1399 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1400 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1401 for (Entry<String, Object> entry : secondObjec.entrySet()) {
1402 data.put(key + "." + entry.getKey(), entry.getValue());
1404 } else if (value instanceof ArrayList) {
1405 ArrayList<?> jsonArrayVal = (ArrayList<?>) value;
1406 for (int i = 0; i < jsonArrayVal.size(); i++) {
1407 Object arrayvalue = jsonArrayVal.get(i);
1408 if (arrayvalue instanceof LinkedHashMap<?, ?>) {
1409 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1410 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1411 for (Entry<String, Object> entry : newData.entrySet()) {
1412 data.put(key + "@" + i + "." + entry.getKey(), entry.getValue());
1414 } else if (arrayvalue instanceof ArrayList) {
1415 ArrayList<?> jsonArrayVal1 = (ArrayList<?>) value;
1416 for (int j = 0; j < jsonArrayVal1.size(); j++) {
1417 Object arrayvalue1 = jsonArrayVal1.get(i);
1418 data.put(key + "@" + j, arrayvalue1.toString());
1421 data.put(key + "@" + i, arrayvalue.toString());
1425 data.put(key.toString(), value.toString());
1433 * @param value String
1436 public String getPolicyScope(String value) {
1437 List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1438 if (groupList != null && !groupList.isEmpty()) {
1439 return ((GroupPolicyScopeList) groupList.get(0)).getGroupName();
1445 * Convert the map values and set into JSON body.
1447 * @param attributesMap Map of attributes
1448 * @param attributesRefMap Map of attribute references
1451 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1452 Map<String, String> attribute = new HashMap<>();
1456 for (Entry<String, String> entry : attributesMap.entrySet()) {
1457 key = entry.getKey();
1458 value = entry.getValue();
1459 attribute.put(key, value);
1461 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1462 key = entryRef.getKey();
1463 value = entryRef.getValue();
1464 attribute.put(key, value);
1466 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1467 key = entryList.getKey();
1468 value = entryList.getValue();
1469 attribute.put(key, value);
1471 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()) {
1472 key = arrayList.getKey();
1474 for (Object textList : arrayList.getValue()) {
1476 temp = new StringBuilder();
1477 temp.append("[" + textList);
1479 temp.append("," + textList);
1482 attribute.put(key, temp + "]");
1489 value = {"/ms_dictionary/set_MSModelData"},
1490 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1491 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
1492 throws IOException, FileUploadException {
1493 modelList = new ArrayList<>();
1494 dirDependencyList = new ArrayList<>();
1495 classMap = new LinkedHashMap<>();
1496 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1497 boolean zip = false;
1498 boolean yml = false;
1499 String errorMsg = "";
1500 for (FileItem item : items) {
1501 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
1502 this.newModel = new MicroServiceModels();
1504 File file = new File(item.getName());
1505 OutputStream outputStream = new FileOutputStream(file);
1506 IOUtils.copy(item.getInputStream(), outputStream);
1507 outputStream.close();
1508 this.newFile = file.toString();
1509 this.newModel.setModelName(this.newFile.split("-v")[0]);
1511 if (this.newFile.contains("-v")) {
1512 if (item.getName().endsWith(".zip")) {
1513 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1515 } else if (item.getName().endsWith(".yml")) {
1516 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1519 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1522 } catch (Exception e) {
1523 LOGGER.error("Upload error : ", e);
1524 errorMsg = "Upload error:" + e.getMessage();
1530 if (!errorMsg.isEmpty()) {
1531 response.setCharacterEncoding("UTF-8");
1532 response.setContentType("application / json");
1533 request.setCharacterEncoding("UTF-8");
1535 JSONObject json = new JSONObject();
1536 json.put("errorMsg", errorMsg);
1537 response.getWriter().write(json.toString());
1541 List<File> fileList = new ArrayList<>();
1542 MSModelUtils msModelUtils = new MSModelUtils(commonClassDao);
1543 this.directory = "model";
1545 extractFolder(this.newFile);
1546 fileList = listModelFiles(this.directory);
1548 errorMsg = msModelUtils.parseTosca(this.newFile);
1549 if (errorMsg != null) {
1550 response.setCharacterEncoding("UTF-8");
1551 response.setContentType("application / json");
1552 request.setCharacterEncoding("UTF-8");
1553 JSONObject json = new JSONObject();
1554 json.put("errorMsg", errorMsg);
1555 response.getWriter().write(json.toString());
1560 File file = new File(this.newFile);
1563 String modelType = "";
1566 // Process Main Model file first
1567 classMap = new LinkedHashMap<>();
1568 for (File file : fileList) {
1569 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
1570 retrieveDependency(file.toString());
1574 modelList = createList();
1576 cleanUp(this.newFile);
1580 modelList.add(this.newModel.getModelName());
1581 String className = this.newModel.getModelName();
1582 MSAttributeObject msAttributes = new MSAttributeObject();
1583 msAttributes.setClassName(className);
1585 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
1586 returnAttributeList.put(className, msModelUtils.getAttributeString());
1587 msAttributes.setAttribute(returnAttributeList);
1589 msAttributes.setSubClass(msModelUtils.getRetmap());
1591 msAttributes.setMatchingSet(msModelUtils.getMatchableValues());
1593 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
1595 returnReferenceList.put(className, msModelUtils.getReferenceAttributes());
1596 msAttributes.setRefAttribute(returnReferenceList);
1598 if (msModelUtils.getListConstraints() != "") {
1599 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
1600 String[] listArray = msModelUtils.getListConstraints().split("#");
1601 for (String str : listArray) {
1602 String[] strArr = str.split("=");
1603 if (strArr.length > 1) {
1604 enumList.put(strArr[0], strArr[1]);
1607 msAttributes.setEnumType(enumList);
1610 classMap = new LinkedHashMap<>();
1611 classMap.put(className, msAttributes);
1614 response.setCharacterEncoding("UTF-8");
1615 response.setContentType("application / json");
1616 request.setCharacterEncoding("UTF-8");
1618 ObjectMapper mapper = new ObjectMapper();
1619 JSONObject json = new JSONObject();
1620 json.put("classListDatas", modelList);
1621 json.put("modelDatas", mapper.writeValueAsString(classMap));
1622 json.put("modelType", modelType);
1623 json.put("dataOrderInfo", msModelUtils.getDataOrderInfo());
1624 json.put("ruleFormation", msModelUtils.getJsonRuleFormation());
1626 response.getWriter().write(json.toString());
1630 * Unzip file and store in the model directory for processing
1632 @SuppressWarnings("rawtypes")
1633 private void extractFolder(String zipFile) {
1634 final int buffer = 2048;
1635 File file = new File(zipFile);
1637 try (ZipFile zip = new ZipFile(file)) {
1638 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1639 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1640 checkZipDirectory(this.directory);
1641 new File(newPath).mkdir();
1642 Enumeration zipFileEntries = zip.entries();
1644 // Process each entry
1645 while (zipFileEntries.hasMoreElements()) {
1646 // grab a zip file entry
1647 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1648 String currentEntry = entry.getName();
1649 File destFile = new File("model" + File.separator + currentEntry);
1650 File destinationParent = destFile.getParentFile();
1652 destinationParent.mkdirs();
1654 if (!entry.isDirectory()) {
1655 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1657 byte[] data = new byte[buffer];
1658 try (FileOutputStream fos = new FileOutputStream(destFile);
1659 BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
1660 while ((currentByte = is.read(data, 0, buffer)) != -1) {
1661 dest.write(data, 0, currentByte);
1664 } catch (IOException e) {
1665 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1667 // PLD should I throw e?
1673 if (currentEntry.endsWith(".zip")) {
1674 extractFolder(destFile.getAbsolutePath());
1677 } catch (IOException e) {
1678 LOGGER.error("Failed to unzip model file " + zipFile, e);
1682 private void retrieveDependency(String workingFile) {
1684 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1685 Map<String, MSAttributeObject> tempMap;
1687 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1689 classMap.putAll(tempMap);
1690 LOGGER.info(tempMap);
1693 private List<File> listModelFiles(String directoryName) {
1694 File fileDirectory = new File(directoryName);
1695 List<File> resultList = new ArrayList<>();
1696 for (File file : fileDirectory.listFiles()) {
1697 if (file.isFile()) {
1698 resultList.add(file);
1699 } else if (file.isDirectory()) {
1700 dirDependencyList.add(file.getName());
1701 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1710 * @param path String
1712 public void cleanUp(String path) {
1715 FileUtils.forceDelete(new File(path));
1716 } catch (IOException e) {
1717 LOGGER.error("Failed to delete folder " + path, e);
1723 * checkZipDirectory.
1725 * @param zipDirectory String
1727 public void checkZipDirectory(String zipDirectory) {
1728 Path path = Paths.get(zipDirectory);
1730 if (Files.exists(path)) {
1731 cleanUp(zipDirectory);
1735 private List<String> createList() {
1736 List<String> list = new ArrayList<>();
1737 for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
1738 if (entrySet.getValue().isPolicyTempalate()) {
1739 list.add(entrySet.getKey());
1744 if (list.isEmpty()) {
1745 if (classMap.containsKey(this.newModel.getModelName())) {
1746 list.add(this.newModel.getModelName());
1754 public Map<String, String> getAttributesListRefMap() {
1755 return attributesListRefMap;
1758 public Map<String, LinkedList<String>> getArrayTextList() {
1759 return arrayTextList;
1762 public Map<String, String> getSigRules() {
1766 public void setSigRules(Map<String, String> sigRules) {
1767 this.sigRules = sigRules;
1774 class DCAEMicroServiceObject {
1776 private String service;
1777 private String location;
1778 private String uuid;
1779 private String policyName;
1780 private String description;
1781 private String configName;
1782 private String templateVersion;
1783 private String version;
1784 private String priority;
1785 private String policyScope;
1786 private String riskType;
1787 private String riskLevel;
1788 private String guard = null;
1789 private Object uiContent;
1790 private Object content;