X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=blobdiff_plain;f=POLICY-SDK-APP%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Fcontroller%2FCreateDcaeMicroServiceController.java;h=f0b3313a646ac6cf19067528f964706a47782dc6;hp=67a94474f916f1a2b4497963612ad93159c9693f;hb=1e61676b77dd09659027b8984f050df7e8538526;hpb=26b2f0b9eb6fa60a8e161181768e20fdf3b4c7f7 diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java index 67a94474f..f0b3313a6 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -20,23 +20,23 @@ package org.onap.policy.controller; - import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.io.PrintWriter; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.Path; @@ -53,9 +53,12 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; +import java.util.TreeSet; import java.util.UUID; +import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; @@ -65,13 +68,14 @@ import javax.json.JsonReader; import javax.json.JsonValue; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.Getter; +import lombok.Setter; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -93,6 +97,7 @@ import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.util.MSAttributeObject; import org.onap.policy.rest.util.MSModelUtils; import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.JsonMessage; import org.springframework.beans.factory.annotation.Autowired; @@ -124,7 +129,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private LinkedHashMap classMap = new LinkedHashMap<>(); String referenceAttributes; String attributeString; - Set allManyTrueKeys = new HashSet<>(); + Set allManyTrueKeys = null; + private Map sigRules = null; public static final String DATATYPE = "data_types.policy.data."; public static final String PROPERTIES = ".properties."; @@ -136,7 +142,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { public static final String REQUIRED = ".required"; public static final String MATCHABLE = ".matchable"; public static final String MANYFALSE = ":MANY-false"; - + private static final Pattern PATTERN = Pattern.compile("[A][0-9]"); + private static final String POLICYJSON = "policyJSON"; @Autowired private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) { @@ -153,16 +160,23 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private Map> arrayTextList = new HashMap<>(); private Map jsonStringValues = new HashMap<>(); + /** + * setDataToPolicyRestAdapter. + * + * @param policyData PolicyRestAdapter + * @param root JsonNode + * @return PolicyRestAdapter + */ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { String jsonContent = null; try { - LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString()); + LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString()); - String tempJson = root.get("policyJSON").toString(); - JSONObject policyJSON = new JSONObject(root.get("policyJSON").toString()); - if (policyJSON != null) { - saveOriginalJsonObject(policyJSON, jsonStringValues); + String tempJson = root.get(POLICYJSON).toString(); + JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString()); + if (policyJson != null) { + tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString(); } // ---replace empty value with the value below before calling decodeContent method. String dummyValue = "*empty-value*" + UUID.randomUUID().toString(); @@ -178,9 +192,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } // ----Here is the final step to reset the original value back. - if(policyData.getJsonBody() != null && jsonStringValues.size() > 0){ + if (policyData.getJsonBody() != null && jsonStringValues.size() > 0) { String contentBody = policyData.getJsonBody(); - JSONObject contentJson= new JSONObject(contentBody); + JSONObject contentJson = new JSONObject(contentBody); JSONObject content = contentJson.getJSONObject("content"); content = setOriginalJsonObject(content, jsonStringValues); contentJson.put("content", content); @@ -190,52 +204,52 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return policyData; } - /** - * To save the original JSON string from the root. - * - * @param jsonObj holds the value from the root. - * @param jsonStringValues value get saved. - */ - private void saveOriginalJsonObject(JSONObject jsonObj, Map jsonStringValues) { + private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map jsonStringValues) { for (Object key : jsonObj.keySet()) { String keyStr = (String) key; Object keyvalue = jsonObj.get(keyStr); if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) { jsonStringValues.put(keyStr, keyvalue.toString()); + // --- set default value + jsonObj.put(keyStr, "JSON_STRING"); } // for nested objects iteration if required if (keyvalue instanceof JSONObject) { saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues); + // --- set default value + jsonObj.put(keyStr, "JSON_STRING"); + } + + if (keyvalue instanceof JSONArray) { + for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) { + JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i); + saveOriginalJsonObject(temp, jsonStringValues); + } } } + + return jsonObj; } - /** - * To reset the original JSON string back associated to its key. - * - * @param jsonObj holds the original json. - * @param jsonStringValues value to be reset. - * @return - */ - private JSONObject setOriginalJsonObject(JSONObject jsonObj , Map jsonStringValues) { + private JSONObject setOriginalJsonObject(JSONObject jsonObj, Map jsonStringValues) { for (Object key : jsonObj.keySet()) { - String keyStr = (String)key; + String keyStr = (String) key; Object keyvalue = jsonObj.get(keyStr); String originalValue = getOriginalValue(keyStr); if (originalValue != null) { jsonObj.put(keyStr, originalValue); } - //for nested objects iteration if required + // for nested objects iteration if required if (keyvalue instanceof JSONObject) { - setOriginalJsonObject((JSONObject)keyvalue, jsonStringValues); + setOriginalJsonObject((JSONObject) keyvalue, jsonStringValues); jsonObj.put(keyStr, originalValue); } if (keyvalue instanceof JSONArray) { - for (int i = 0; i < ((JSONArray)keyvalue).length(); i++) { - JSONObject temp = ((JSONArray)keyvalue).getJSONObject(i); + for (int i = 0; i < ((JSONArray) keyvalue).length(); i++) { + JSONObject temp = ((JSONArray) keyvalue).getJSONObject(i); setOriginalJsonObject(temp, jsonStringValues); } } @@ -248,7 +262,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope); } - private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) { + private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) + throws IOException { ObjectWriter om = new ObjectMapper().writer(); String json = ""; DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); @@ -297,7 +312,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { microServiceObject.setGuard(policyAdapter.getGuard()); } microServiceObject.setContent(jsonContent); - + String modelName = policyAdapter.getServiceType(); + String versionName = policyAdapter.getVersion(); + List triggerData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", + modelName + ":" + versionName); + MicroServiceModels model = null; + boolean ruleCheck = false; + if (!triggerData.isEmpty()) { + model = (MicroServiceModels) triggerData.get(0); + if (model.getRuleFormation() != null) { + microServiceObject.setUiContent(jsonContent); + ruleCheck = true; + } + } try { json = om.writeValueAsString(microServiceObject); } catch (JsonProcessingException e) { @@ -305,16 +332,170 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } LOGGER.info("input json: " + json); LOGGER.info("input jsonContent: " + jsonContent); - String cleanJson = cleanUPJson(json); + String cleanJson = cleanUpJson(json); // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes String tempJson = StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""}); LOGGER.info("tempJson: " + tempJson); cleanJson = removeNullAttributes(tempJson); + if (cleanJson.contains("\\")) { + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\"}, new String[] {""}); + } policyAdapter.setJsonBody(cleanJson); + // for Triggers + ObjectMapper mapper = new ObjectMapper(); + JsonNode tempJsonNode = mapper.readTree(cleanJson); + if (! ruleCheck) { + return policyAdapter; + } + ObjectNode finalJson = (ObjectNode) tempJsonNode; + JsonNode object = tempJsonNode.get("content"); + String primaryKey1 = model.getRuleFormation(); + String[] primaryKeyForSignatures = primaryKey1.split("@"); + for (String primaryKeyForSignature : primaryKeyForSignatures) { + String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.')); + JsonNode triggerSig = object.get(primarykeyAlarm); + sigRules = new HashMap<>(); + String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1); + StringBuilder sb = null; + if (triggerSig instanceof ArrayNode) { + for (int i = 0; i < triggerSig.size(); i++) { + sb = new StringBuilder(); + parseData(triggerSig.get(i), parseKey); + sb.append("("); + List keyList = new ArrayList<>(sigRules.keySet()); + for (int j = keyList.size() - 1; j >= 0; j--) { + String key = (String) keyList.get(j); + String jsonNode = sigRules.get(key); + constructRule(sb, jsonNode, sigRules); + } + sb.append(")").toString(); + putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm); + sigRules = new HashMap<>(); + } + } else { + parseData(triggerSig, parseKey); + } + } + policyAdapter.setJsonBody(finalJson.toString()); return policyAdapter; } + private JsonNode putRuletoJson(JsonNode tmpJsonNode, int item, StringBuilder sb, String parseKey, + String primaryKey) { + JsonNode tmp = tmpJsonNode; + ObjectNode objectNode = (ObjectNode) tmp; + JsonNode jsonNode = tmpJsonNode.get("content").get(primaryKey).get(item); + JsonNode tempRuleJsonNode = tmpJsonNode.get("content").get(primaryKey).get(item); + String[] tempSt = parseKey.split("\\."); + for (String value : tempSt) { + if (value.contains("[")) { + if (tempRuleJsonNode instanceof ArrayNode) { + JsonNode tempRuleNode = tempRuleJsonNode.get(item); + ((ArrayNode) tempRuleJsonNode).removeAll(); + ((ArrayNode) tempRuleJsonNode).add(tempRuleNode); + objectNode = (ObjectNode) tempRuleJsonNode.get(item); + } + String key = value.substring(0, value.indexOf('[')); + objectNode.remove(key); + objectNode.put(key, sb.toString()); + return tmp; + } else { + jsonNode = jsonNode.get(value); + if (jsonNode instanceof ArrayNode) { + tempRuleJsonNode = jsonNode; + jsonNode = jsonNode.get(item); + } + } + } + return tmp; + } + + public boolean checkPattern(String patternString) { + return PATTERN.matcher(patternString).find(); + } + + /** + * Construct rule. + * + * @param sb the sb + * @param jsonNode the json node + * @param sigRules2 the sig rules 2 + */ + public void constructRule(StringBuilder sb, String jsonNode, Map sigRules2) { + int count = 0; + String cleanJsonNode = jsonNode.replace("\"\"", " "); + cleanJsonNode = cleanJsonNode.replaceAll("\"", ""); + cleanJsonNode = cleanJsonNode.replaceAll("\\(", ""); + cleanJsonNode = cleanJsonNode.replaceAll("\\)", ""); + boolean flag = false; + if (cleanJsonNode.contains("OR")) { + sb.append("("); + flag = true; + } + for (String rowValue : cleanJsonNode.split(" ")) { + if (checkPattern(rowValue)) { + String value = sigRules2.get(rowValue); + LOGGER.info(" Value is:" + value); + constructRule(sb, value, sigRules2); + } else { + if ((count == 0) && (!("AND").equals(rowValue)) && (!("OR").equals(rowValue))) { + sb.append("("); + } + count++; + LOGGER.info(" " + rowValue + " "); + sb.append(" " + rowValue + " "); + if (count % 3 == 0) { + sb.append(")"); + count = 0; + } + } + } + if (flag) { + sb.append(")"); + } + } + + /** + * Parses the data. + * + * @param jsonNode the json node + * @param string the string + */ + public void parseData(JsonNode jsonNode, String string) { + if (string.contains(".")) { + String firstIndex = string.substring(0, string.indexOf('.')); + JsonNode signtures = jsonNode.get(firstIndex); + String subIndex = string.substring(firstIndex.length() + 1); + if (signtures instanceof ArrayNode) { + for (int i = 0; i < signtures.size(); i++) { + parseData(signtures.get(i), subIndex); + } + } else { + parseData(signtures, subIndex); + } + } else { + if (string.contains("[")) { + String ruleIndex = string.substring(0, string.indexOf('[')); + String[] keys = string.substring(string.indexOf('[') + 1, string.lastIndexOf(']')).split(","); + String key = "A" + Integer.valueOf(sigRules.size() + 1); + JsonNode node = jsonNode.get(ruleIndex); + StringBuilder sb = new StringBuilder("("); + for (int i = 0; i < keys.length; i++) { + sb.append(node.get(keys[i].trim())); + } + sb.append(")"); + sigRules.put(key, sb.toString()); + } + } + } + + /** + * removeNullAttributes. + * + * @param cleanJson String + * @returnString + */ public String removeNullAttributes(String cleanJson) { ObjectMapper mapper = new ObjectMapper(); @@ -358,9 +539,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { if (contentChanged) { // set modified content to cleanJson - JSONObject jObject = new JSONObject(cleanJson); - jObject.put("content", removed.toString()); - cleanJson = cleanUPJson(jObject.toString()); + JSONObject jsonObject = new JSONObject(cleanJson); + jsonObject.put("content", removed.toString()); + cleanJson = cleanUpJson(jsonObject.toString()); } } catch (IOException e) { @@ -397,52 +578,69 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return null; } + /** + * removeNull. + * + * @param array JsonArray + * @return JsonArray + */ public JsonArray removeNull(JsonArray array) { JsonArrayBuilder builder = Json.createArrayBuilder(); - int i = 0; - for (Iterator it = array.iterator(); it.hasNext(); ++i) { + int index = 0; + for (Iterator it = array.iterator(); it.hasNext(); ++index) { JsonValue value = it.next(); switch (value.getValueType()) { case ARRAY: - JsonArray a = removeNull(array.getJsonArray(i)); - if (!a.isEmpty()) - builder.add(a); + JsonArray tempArray = removeNull(array.getJsonArray(index)); + if (!tempArray.isEmpty()) { + builder.add(tempArray); + } break; case OBJECT: - JsonObject object = removeNull(array.getJsonObject(i)); - if (!object.isEmpty()) + JsonObject object = removeNull(array.getJsonObject(index)); + if (!object.isEmpty()) { builder.add(object); + } break; case STRING: - String s = array.getString(i); - if (s != null && !s.isEmpty()) - builder.add(s); + String str = array.getString(index); + if (str != null && !str.isEmpty()) { + builder.add(str); + } break; case NUMBER: - builder.add(array.getJsonNumber(i)); + builder.add(array.getJsonNumber(index)); break; case TRUE: case FALSE: - builder.add(array.getBoolean(i)); + builder.add(array.getBoolean(index)); break; case NULL: + default: break; } } return builder.build(); } + /** + * removeNull. + * + * @param obj JsonObject + * @return JsonObject + */ public JsonObject removeNull(JsonObject obj) { JsonObjectBuilder builder = Json.createObjectBuilder(); for (Iterator> it = obj.entrySet().iterator(); it.hasNext();) { - Entry e = it.next(); - String key = e.getKey(); - JsonValue value = e.getValue(); + Entry entry = it.next(); + String key = entry.getKey(); + JsonValue value = entry.getValue(); switch (value.getValueType()) { case ARRAY: JsonArray array = removeNull(obj.getJsonArray(key)); - if (!array.isEmpty()) + if (!array.isEmpty()) { builder.add(key, array); + } break; case OBJECT: JsonObject object = removeNull(obj.getJsonObject(key)); @@ -458,15 +656,15 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } break; case STRING: - String s = obj.getString(key); - if (s != null && !s.isEmpty()) { + String str = obj.getString(key); + if (str != null && !str.isEmpty()) { if (!jsonStringValues.isEmpty()) { String originalValue = getOriginalValue(key); if (originalValue != null) { - s = getOriginalValue(key); + str = getOriginalValue(key); } } - builder.add(key, s); + builder.add(key, str); } break; case NUMBER: @@ -477,13 +675,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { builder.add(key, obj.getBoolean(key)); break; case NULL: + default: break; } } return builder.build(); } - public String cleanUPJson(String json) { + /** + * cleanUpJson. + * + * @param json String + * @return String + */ + public String cleanUpJson(String json) { String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"}, new String[] {"\\", "\\", "\\"}); cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"}); @@ -504,6 +709,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return cleanJson; } + /** + * decodeContent. + * + * @param jsonNode JsonNode + * @return JsonNode + */ public JSONObject decodeContent(JsonNode jsonNode) { Iterator jsonElements = jsonNode.elements(); Iterator jsonKeys = jsonNode.fieldNames(); @@ -654,10 +865,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return jsonResult; } - @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"}, + @RequestMapping( + value = {"/policyController/getDCAEMSTemplateData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException { + // TreeSet is used to ensure that individual items appear before their containing collection. + allManyTrueKeys = new TreeSet<>(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); @@ -693,7 +907,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { JSONObject json = new JSONObject(returnModel.getSub_attributes()); getAllKeys(json); allkeys = allManyTrueKeys; - allManyTrueKeys = new HashSet<>(); + allManyTrueKeys = new TreeSet<>(); LOGGER.info("allkeys : " + allkeys); } @@ -704,12 +918,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } LOGGER.info("dataOrderInfo : " + dataOrderInfo); - String allManyTrueKeys = ""; + String allMnyTrueKeys = ""; if (allkeys != null) { - allManyTrueKeys = allkeys.toString(); + allMnyTrueKeys = allkeys.toString(); } - String jsonModel = createMicroSeriveJson(returnModel, allkeys); + String jsonModel = createMicroSeriveJson(returnModel); JSONObject jsonObject = new JSONObject(jsonModel); @@ -719,6 +933,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { while (iter.hasNext()) { // Convert to array values for MANY-true keys finalJsonObject = convertToArrayElement(jsonObject, iter.next()); + jsonObject = finalJsonObject; } } @@ -735,6 +950,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { LOGGER.info(s); // convert to array element for MANY-true properties finalJsonObject = convertToArrayElement(jsonObj, s.trim()); + jsonObj = finalJsonObject; } if (finalJsonObject != null) { @@ -743,30 +959,29 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List list = new ArrayList<>(); - PrintWriter out = response.getWriter(); String responseString = mapper.writeValueAsString(returnModel); - JSONObject j = null; + JSONObject json = null; - if ("".equals(allManyTrueKeys)) { - j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + if ("".equals(allMnyTrueKeys)) { + json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}"); } else { - j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " - + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData - + "}"); + json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + + headDefautlsData + "}"); } - list.add(j); - out.write(list.toString()); + list.add(json); + response.getWriter().write(list.toString()); return null; } @SuppressWarnings({"unchecked", "rawtypes"}) - private String createMicroSeriveJson(MicroServiceModels returnModel, Set allkeys) { + private String createMicroSeriveJson(MicroServiceModels returnModel) { Map attributeMap = new HashMap<>(); Map refAttributeMap = new HashMap<>(); String attribute = returnModel.getAttributes(); @@ -800,10 +1015,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class); JSONObject object = new JSONObject(); - JSONArray array = new JSONArray(); for (Entry keySet : attributeMap.entrySet()) { - array = new JSONArray(); + JSONArray array = new JSONArray(); String value = keySet.getValue(); if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) { array.put(value); @@ -814,7 +1028,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } for (Entry keySet : refAttributeMap.entrySet()) { - array = new JSONArray(); + JSONArray array = new JSONArray(); String value = keySet.getValue().split(":")[0]; if (gsonObject.containsKey(value)) { if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) { @@ -867,12 +1081,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return object; } - - public static JSONObject convertToArrayElement(JSONObject json, String keyValue) { + public JSONObject convertToArrayElement(JSONObject json, String keyValue) { return convertToArrayElement(json, new HashSet<>(), keyValue); } - private static JSONObject convertToArrayElement(JSONObject json, Set keys, String keyValue) { + private JSONObject convertToArrayElement(JSONObject json, Set keys, String keyValue) { for (String key : json.keySet()) { Object obj = json.get(key); if (key.equals(keyValue.trim())) { @@ -890,15 +1103,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return json; } - if (obj instanceof JSONObject) + if (obj instanceof JSONObject) { convertToArrayElement(json.getJSONObject(key), keyValue); + } + + if (obj instanceof JSONArray) { + convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue); + } } return json; } - // call this method to get all MANY-true properties - public static Set getManyTrueProperties(String referAttributes) { + /** + * getManyTrueProperties. + * + * @param referAttributes String + * @return a Set of String + */ + public Set getManyTrueProperties(String referAttributes) { LOGGER.info("referAttributes : " + referAttributes); Set manyTrueProperties = new HashSet<>(); @@ -928,10 +1151,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private Set getAllKeys(JSONArray arr, Set keys) { for (int i = 0; i < arr.length(); i++) { Object obj = arr.get(i); - if (obj instanceof JSONObject) + if (obj instanceof JSONObject) { keys.addAll(getAllKeys(arr.getJSONObject(i))); - if (obj instanceof JSONArray) + } + if (obj instanceof JSONArray) { keys.addAll(getAllKeys(arr.getJSONArray(i))); + } } return keys; @@ -946,37 +1171,42 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { LOGGER.info("obj : " + obj); allManyTrueKeys.add(key); } - if (obj instanceof JSONObject) + if (obj instanceof JSONObject) { keys.addAll(getAllKeys(json.getJSONObject(key))); - if (obj instanceof JSONArray) + } + if (obj instanceof JSONArray) { keys.addAll(getAllKeys(json.getJSONArray(key))); + } } return keys; } - - @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"}, + /** + * getModelServiceVersionData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ + @RequestMapping( + value = {"/policyController/getModelServiceVersioneData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + List list = new ArrayList<>(); + String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", ""); String servicename = value.split("-v")[0]; Set returnList = getVersionList(servicename); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - List list = new ArrayList<>(); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(returnList); - JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}"); - list.add(j); - out.write(list.toString()); + list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}")); + response.getWriter().write(list.toString()); return null; } @@ -1021,7 +1251,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { modelName); } - @RequestMapping(value = {"/get_DCAEPriorityValues"}, + @RequestMapping( + value = {"/get_DCAEPriorityValues"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) { @@ -1034,98 +1265,76 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { priorityList.add(String.valueOf(i)); } model.put("priorityDatas", mapper.writeValueAsString(priorityList)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { LOGGER.error(e); } } + /** + * prePopulateDCAEMSPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = - policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (matchList.size() > 1 && iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } - if ("ConfigName".equals(attributeId)) { - policyAdapter.setConfigName(value); - } - if ("uuid".equals(attributeId)) { - policyAdapter.setUuid(value); - } - if ("location".equals(attributeId)) { - policyAdapter.setLocation(value); - } - if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - } - readFile(policyAdapter, entity); - } - } - } - } + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList == null) { + continue; + } + Iterator iterMatch = matchList.iterator(); + // + // Can someone please explain why the matchList MUST have + // more than 1 matches??? + // + while (matchList.size() > 1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + // First match in the target is OnapName, so set that value. + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); } + readFile(policyAdapter, entity); } } } - public static Map convert(String str, String split) { + /** + * Convert. + * + * @param str the str + * @param split the split + * @return the map + */ + public Map convert(String str, String split) { Map map = new HashMap<>(); for (final String entry : str.split(split)) { String[] parts = entry.split("="); @@ -1134,15 +1343,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return map; } - + /** + * Read file. + * + * @param policyAdapter the policy adapter + * @param entity the entity + */ @SuppressWarnings("unchecked") - private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - String policyScopeName = null; - ObjectMapper mapper = new ObjectMapper(); + public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { try { DCAEMicroServiceObject msBody = - mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class); - policyScopeName = getPolicyScope(msBody.getPolicyScope()); + new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), + DCAEMicroServiceObject.class); + String policyScopeName = getPolicyScope(msBody.getPolicyScope()); policyAdapter.setPolicyScope(policyScopeName); policyAdapter.setPriority(msBody.getPriority()); @@ -1153,9 +1366,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } else { policyAdapter.setServiceType(msBody.getService()); } - if (msBody.getContent() != null) { + // + LinkedHashMap content = (LinkedHashMap) msBody.getUiContent(); + if (content == null) { + content = (LinkedHashMap) msBody.getContent(); + } + if (content != null) { LinkedHashMap data = new LinkedHashMap<>(); - LinkedHashMap map = (LinkedHashMap) msBody.getContent(); + LinkedHashMap map = content; readRecursivlyJSONContent(map, data); policyAdapter.setRuleData(data); } @@ -1166,8 +1384,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } + /** + * readRecursivlyJSONContent. + * + * @param map Map of String to something + * @param data Map of String to Object + */ @SuppressWarnings({"rawtypes", "unchecked"}) - public void readRecursivlyJSONContent(LinkedHashMap map, LinkedHashMap data) { + public void readRecursivlyJSONContent(Map map, Map data) { for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { Object key = iterator.next(); Object value = map.get(key); @@ -1203,16 +1427,27 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } + /** + * getPolicyScope. + * + * @param value String + * @return String + */ public String getPolicyScope(String value) { List groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); if (groupList != null && !groupList.isEmpty()) { - GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); - return pScope.getGroupName(); + return ((GroupPolicyScopeList) groupList.get(0)).getGroupName(); } return null; } - // Convert the map values and set into JSON body + /** + * Convert the map values and set into JSON body. + * + * @param attributesMap Map of attributes + * @param attributesRefMap Map of attribute references + * @return Map + */ public Map convertMap(Map attributesMap, Map attributesRefMap) { Map attribute = new HashMap<>(); StringBuilder temp; @@ -1250,7 +1485,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return attribute; } - @RequestMapping(value = {"/ms_dictionary/set_MSModelData"}, + @RequestMapping( + value = {"/ms_dictionary/set_MSModelData"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException { @@ -1292,36 +1528,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } if (!errorMsg.isEmpty()) { - - PrintWriter out = response.getWriter(); - response.setCharacterEncoding("UTF-8"); response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - out.write(j.toString()); + JSONObject json = new JSONObject(); + json.put("errorMsg", errorMsg); + response.getWriter().write(json.toString()); return; } List fileList = new ArrayList<>(); - MSModelUtils msMLUtils = new MSModelUtils(); + MSModelUtils msModelUtils = new MSModelUtils(commonClassDao); this.directory = "model"; if (zip) { extractFolder(this.newFile); fileList = listModelFiles(this.directory); - } else if (yml == true) { - - errorMsg = msMLUtils.parseTosca(this.newFile); + } else if (yml) { + errorMsg = msModelUtils.parseTosca(this.newFile); if (errorMsg != null) { - PrintWriter out = response.getWriter(); response.setCharacterEncoding("UTF-8"); response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - out.write(j.toString()); + JSONObject json = new JSONObject(); + json.put("errorMsg", errorMsg); + response.getWriter().write(json.toString()); return; } @@ -1336,7 +1567,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { classMap = new LinkedHashMap<>(); for (File file : fileList) { if (!file.isDirectory() && file.getName().endsWith(".xmi")) { - retreiveDependency(file.toString(), true); + retrieveDependency(file.toString()); } } @@ -1352,21 +1583,21 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { msAttributes.setClassName(className); LinkedHashMap returnAttributeList = new LinkedHashMap<>(); - returnAttributeList.put(className, msMLUtils.getAttributeString()); + returnAttributeList.put(className, msModelUtils.getAttributeString()); msAttributes.setAttribute(returnAttributeList); - msAttributes.setSubClass(msMLUtils.getRetmap()); + msAttributes.setSubClass(msModelUtils.getRetmap()); - msAttributes.setMatchingSet(msMLUtils.getMatchableValues()); + msAttributes.setMatchingSet(msModelUtils.getMatchableValues()); LinkedHashMap returnReferenceList = new LinkedHashMap<>(); - returnReferenceList.put(className, msMLUtils.getReferenceAttributes()); + returnReferenceList.put(className, msModelUtils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if (msMLUtils.getListConstraints() != "") { + if (msModelUtils.getListConstraints() != "") { LinkedHashMap enumList = new LinkedHashMap<>(); - String[] listArray = msMLUtils.getListConstraints().split("#"); + String[] listArray = msModelUtils.getListConstraints().split("#"); for (String str : listArray) { String[] strArr = str.split("="); if (strArr.length > 1) { @@ -1380,21 +1611,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { classMap.put(className, msAttributes); } - - PrintWriter out = response.getWriter(); - response.setCharacterEncoding("UTF-8"); response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); ObjectMapper mapper = new ObjectMapper(); - JSONObject j = new JSONObject(); - j.put("classListDatas", modelList); - j.put("modelDatas", mapper.writeValueAsString(classMap)); - j.put("modelType", modelType); - j.put("dataOrderInfo", msMLUtils.getDataOrderInfo()); + JSONObject json = new JSONObject(); + json.put("classListDatas", modelList); + json.put("modelDatas", mapper.writeValueAsString(classMap)); + json.put("modelType", modelType); + json.put("dataOrderInfo", msModelUtils.getDataOrderInfo()); + json.put("ruleFormation", msModelUtils.getJsonRuleFormation()); - out.write(j.toString()); + response.getWriter().write(json.toString()); } /* @@ -1402,7 +1631,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { */ @SuppressWarnings("rawtypes") private void extractFolder(String zipFile) { - int BUFFER = 2048; + final int buffer = 2048; File file = new File(zipFile); try (ZipFile zip = new ZipFile(file)) { @@ -1425,10 +1654,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; - byte[] data = new byte[BUFFER]; + byte[] data = new byte[buffer]; try (FileOutputStream fos = new FileOutputStream(destFile); - BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) { - while ((currentByte = is.read(data, 0, BUFFER)) != -1) { + BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { + while ((currentByte = is.read(data, 0, buffer)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); @@ -1450,7 +1679,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } - private void retreiveDependency(String workingFile, Boolean modelClass) { + private void retrieveDependency(String workingFile) { MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); Map tempMap; @@ -1459,16 +1688,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { classMap.putAll(tempMap); LOGGER.info(tempMap); - - return; - } private List listModelFiles(String directoryName) { File fileDirectory = new File(directoryName); List resultList = new ArrayList<>(); - File[] fList = fileDirectory.listFiles(); - for (File file : fList) { + for (File file : fileDirectory.listFiles()) { if (file.isFile()) { resultList.add(file); } else if (file.isDirectory()) { @@ -1479,6 +1704,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return resultList; } + /** + * cleanUp. + * + * @param path String + */ public void cleanUp(String path) { if (path != null) { try { @@ -1489,6 +1719,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } + /** + * checkZipDirectory. + * + * @param zipDirectory String + */ public void checkZipDirectory(String zipDirectory) { Path path = Paths.get(zipDirectory); @@ -1499,9 +1734,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private List createList() { List list = new ArrayList<>(); - for (Entry cMap : classMap.entrySet()) { - if (cMap.getValue().isPolicyTempalate()) { - list.add(cMap.getKey()); + for (Entry entrySet : classMap.entrySet()) { + if (entrySet.getValue().isPolicyTempalate()) { + list.add(entrySet.getKey()); } } @@ -1524,9 +1759,18 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return arrayTextList; } -} + public Map getSigRules() { + return sigRules; + } + + public void setSigRules(Map sigRules) { + this.sigRules = sigRules; + } +} +@Getter +@Setter class DCAEMicroServiceObject { private String service; @@ -1542,120 +1786,6 @@ class DCAEMicroServiceObject { private String riskType; private String riskLevel; private String guard = null; - - public String getGuard() { - return guard; - } - - public void setGuard(String guard) { - this.guard = guard; - } - - public String getRiskType() { - return riskType; - } - - public void setRiskType(String riskType) { - this.riskType = riskType; - } - - public String getRiskLevel() { - return riskLevel; - } - - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - - public String getPolicyScope() { - return policyScope; - } - - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - - public String getPriority() { - return priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - + private Object uiContent; private Object content; - - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName) { - this.configName = configName; - } - - public Object getContent() { - return content; - } - - public void setContent(Object content) { - this.content = content; - } - - public String getService() { - return service; - } - - public void setService(String service) { - this.service = service; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - }