Unit/SONAR/Checkstyle in ONAP-REST
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / CreateDcaeMicroServiceController.java
index c5e29e4..5dee2e6 100644 (file)
@@ -37,7 +37,6 @@ 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;
@@ -73,8 +72,6 @@ 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;
@@ -90,16 +87,17 @@ import org.json.JSONArray;
 import org.json.JSONObject;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
 import org.onap.policy.rest.adapter.PolicyRestAdapter;
 import org.onap.policy.rest.dao.CommonClassDao;
 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
 import org.onap.policy.rest.jpa.MicroServiceModels;
 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
 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.rest.util.MsAttributeObject;
+import org.onap.policy.rest.util.MsModelUtils;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
+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;
@@ -128,7 +126,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
     private String directory;
     private List<String> modelList = new ArrayList<>();
     private List<String> dirDependencyList = new ArrayList<>();
-    private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
+    private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>();
     String referenceAttributes;
     String attributeString;
     Set<String> allManyTrueKeys = null;
@@ -270,7 +268,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         String json = "";
         DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
         MicroServiceModels returnModel = new MicroServiceModels();
-        microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
+        microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_MS));
         if (policyAdapter.getServiceType() != null) {
             microServiceObject.setService(policyAdapter.getServiceType());
             microServiceObject.setVersion(policyAdapter.getVersion());
@@ -347,39 +345,39 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         // for Triggers
         ObjectMapper mapper = new ObjectMapper();
         JsonNode tempJsonNode = mapper.readTree(cleanJson);
-        if (ruleCheck) {
-            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 {
+        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, parseKey);
+                    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());
         }
+        policyAdapter.setJsonBody(finalJson.toString());
         return policyAdapter;
     }
 
@@ -905,8 +903,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
         // Get all keys with "MANY-true" defined in their value from subAttribute
         Set<String> allkeys = null;
-        if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
-            JSONObject json = new JSONObject(returnModel.getSub_attributes());
+        if (returnModel.getSubAttributes() != null && !returnModel.getSubAttributes().isEmpty()) {
+            JSONObject json = new JSONObject(returnModel.getSubAttributes());
             getAllKeys(json);
             allkeys = allManyTrueKeys;
             allManyTrueKeys = new TreeSet<>();
@@ -925,7 +923,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             allMnyTrueKeys = allkeys.toString();
         }
 
-        String jsonModel = createMicroSeriveJson(returnModel, allkeys);
+        String jsonModel = createMicroSeriveJson(returnModel);
 
         JSONObject jsonObject = new JSONObject(jsonModel);
 
@@ -944,8 +942,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             jsonModel = finalJsonObject.toString();
         }
 
-        // get all properties with "MANY-true" defined in Ref_attributes
-        Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
+        // get all properties with "MANY-true" defined in RefAttributes
+        Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRefAttributes());
         if (manyTrueProperties != null) {
             JSONObject jsonObj = new JSONObject(jsonModel);
             for (String s : manyTrueProperties) {
@@ -961,9 +959,9 @@ 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<Object> list = new ArrayList<>();
         String responseString = mapper.writeValueAsString(returnModel);
 
@@ -983,14 +981,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
     }
 
     @SuppressWarnings({"unchecked", "rawtypes"})
-    private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
+    private String createMicroSeriveJson(MicroServiceModels returnModel) {
         Map<String, String> attributeMap = new HashMap<>();
         Map<String, String> refAttributeMap = new HashMap<>();
         String attribute = returnModel.getAttributes();
         if (attribute != null) {
             attribute = attribute.trim();
         }
-        String refAttribute = returnModel.getRef_attributes();
+        String refAttribute = returnModel.getRefAttributes();
         if (refAttribute != null) {
             refAttribute = refAttribute.trim();
         }
@@ -1007,7 +1005,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
         Gson gson = new Gson();
 
-        String subAttributes = returnModel.getSub_attributes();
+        String subAttributes = returnModel.getSubAttributes();
         if (subAttributes != null) {
             subAttributes = subAttributes.trim();
         } else {
@@ -1184,6 +1182,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         return keys;
     }
 
+    /**
+     * 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})
@@ -1192,9 +1198,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         ObjectMapper mapper = new ObjectMapper();
         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
-        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<Object> list = new ArrayList<>();
         String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", "");
         String servicename = value.split("-v")[0];
@@ -1294,65 +1300,27 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
         if (target == null) {
             return;
         }
-        // Under target we have AnyOFType
-        List<AnyOfType> anyOfList = target.getAnyOf();
-        if (anyOfList == null) {
-            return;
-        }
-        Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
-        while (iterAnyOf.hasNext()) {
-            AnyOfType anyOf = iterAnyOf.next();
-            // Under AnyOFType we have AllOFType
-            List<AllOfType> allOfList = anyOf.getAllOf();
-            if (allOfList == null) {
-                continue;
-            }
-            Iterator<AllOfType> iterAllOf = allOfList.iterator();
-            while (iterAllOf.hasNext()) {
-                AllOfType allOf = iterAllOf.next();
+        for (AnyOfType anyOf : target.getAnyOf()) {
+            for (AllOfType allOf : anyOf.getAllOf()) {
                 // Under AllOFType we have Match
                 List<MatchType> matchList = allOf.getMatch();
                 if (matchList == null) {
                     continue;
                 }
                 Iterator<MatchType> 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.
                     //
-                    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);
-                    }
+                    policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+                            (String) match.getAttributeValue().getContent().get(0));
                 }
                 readFile(policyAdapter, entity);
             }
@@ -1416,6 +1384,12 @@ 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(Map<String, ?> map, Map<String, Object> data) {
         for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
@@ -1558,14 +1532,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             response.setContentType("application / json");
             request.setCharacterEncoding("UTF-8");
 
-            JSONObject j = new JSONObject();
-            j.put("errorMsg", errorMsg);
-            response.getWriter().write(j.toString());
+            JSONObject json = new JSONObject();
+            json.put("errorMsg", errorMsg);
+            response.getWriter().write(json.toString());
             return;
         }
 
         List<File> fileList = new ArrayList<>();
-        MSModelUtils msModelUtils = new MSModelUtils(commonClassDao);
+        MsModelUtils msModelUtils = new MsModelUtils(commonClassDao);
         this.directory = "model";
         if (zip) {
             extractFolder(this.newFile);
@@ -1593,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());
                 }
             }
 
@@ -1605,7 +1579,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
             modelType = "yml";
             modelList.add(this.newModel.getModelName());
             String className = this.newModel.getModelName();
-            MSAttributeObject msAttributes = new MSAttributeObject();
+            MsAttributeObject msAttributes = new MsAttributeObject();
             msAttributes.setClassName(className);
 
             LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
@@ -1657,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)) {
@@ -1705,18 +1679,15 @@ 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<String, MSAttributeObject> tempMap;
+        MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
+        Map<String, MsAttributeObject> tempMap;
 
-        tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+        tempMap = utils.processEpackage(workingFile, ModelType.XMI);
 
         classMap.putAll(tempMap);
         LOGGER.info(tempMap);
-
-        return;
-
     }
 
     private List<File> listModelFiles(String directoryName) {
@@ -1763,7 +1734,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
     private List<String> createList() {
         List<String> list = new ArrayList<>();
-        for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
+        for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) {
             if (entrySet.getValue().isPolicyTempalate()) {
                 list.add(entrySet.getKey());
             }
@@ -1798,7 +1769,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
 
 }
 
-
 @Getter
 @Setter
 class DCAEMicroServiceObject {