CHeckstyle and JUnit for base package in ONAP-REST
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / CreateOptimizationController.java
index 05fddb5..0e42c78 100644 (file)
@@ -20,7 +20,6 @@
 
 package org.onap.policy.controller;
 
-
 import com.att.research.xacml.util.XACMLProperties;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -28,13 +27,13 @@ import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.ObjectWriter;
 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.util.ArrayList;
 import java.util.Enumeration;
 import java.util.HashMap;
@@ -49,15 +48,17 @@ import java.util.Set;
 import java.util.UUID;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
+
 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;
@@ -68,7 +69,7 @@ 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.MicroserviceHeaderdeFaults;
@@ -77,6 +78,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.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
@@ -87,6 +89,9 @@ import org.springframework.web.servlet.ModelAndView;
 @RequestMapping("/")
 public class CreateOptimizationController extends RestrictedBaseController {
     private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
+
+    private static final int BUFFER = 2048;
+
     private static CommonClassDao commonClassDao;
 
     public static CommonClassDao getCommonClassDao() {
@@ -115,10 +120,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
     public static final String MANYFALSE = ":MANY-false";
     public static final String MODEL = "model";
     public static final String MANY = "MANY-";
-    public static final String UTF8 = "UTF-8";
     public static final String MODELNAME = "modelName";
-    public static final String APPLICATIONJSON = "application / json";
-
 
     @Autowired
     private CreateOptimizationController(CommonClassDao commonClassDao) {
@@ -138,6 +140,13 @@ public class CreateOptimizationController extends RestrictedBaseController {
     private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
     CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
 
+    /**
+     * setDataToPolicyRestAdapter.
+     *
+     * @param policyData PolicyRestAdapter
+     * @param root JsonNode
+     * @return PolicyRestAdapter
+     */
     public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
         String jsonContent = null;
         try {
@@ -175,7 +184,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
         }
         LOGGER.info("input json: " + json);
         LOGGER.info("input jsonContent: " + jsonContent);
-        String cleanJson = msController.cleanUPJson(json);
+        String cleanJson = msController.cleanUpJson(json);
 
         // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
         String tempJson =
@@ -186,7 +195,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
         return policyAdapter;
     }
 
-    @RequestMapping(value = {"/policyController/getOptimizationTemplateData.htm"},
+    /**
+     * getOptimizationTemplateData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     * @throws IOException IOException
+     */
+    @RequestMapping(
+            value = {"/policyController/getOptimizationTemplateData.htm"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
     public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response)
             throws IOException {
@@ -196,10 +214,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
         JsonNode root = mapper.readTree(request.getReader());
 
         String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
-        String servicename = value.toString().split("-v")[0];
+        String servicename = value.split("-v")[0];
         String version = null;
-        if (value.toString().contains("-v")) {
-            version = value.toString().split("-v")[1];
+        if (value.contains("-v")) {
+            version = value.split("-v")[1];
         }
 
         OptimizationModels returnModel = getAttributeObject(servicename, version);
@@ -226,8 +244,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
         // Get all keys with "MANY-true" defined in their value from subAttribute
         Set<String> allkeys = null;
         if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
-            JSONObject json = new JSONObject(returnModel.getSubattributes());
-            getAllKeys(json);
+            getAllKeys(new JSONObject(returnModel.getSubattributes()));
             allkeys = allManyTrueKeys;
             allManyTrueKeys = new HashSet<>();
             LOGGER.info("allkeys : " + allkeys);
@@ -276,23 +293,22 @@ public class CreateOptimizationController extends RestrictedBaseController {
             jsonModel = finalJsonObject.toString();
         }
 
-        response.setCharacterEncoding(UTF8);
-        response.setContentType(APPLICATIONJSON);
-        request.setCharacterEncoding(UTF8);
+        response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+        response.setContentType(PolicyUtils.APPLICATION_JSON);
+        request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
         List<Object> list = new ArrayList<>();
-        PrintWriter out = response.getWriter();
         String responseString = mapper.writeValueAsString(returnModel);
-        JSONObject j = null;
+        JSONObject json = null;
         if ("".equals(nameOfTrueKeys)) {
-            j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+            json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
                     + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
         } else {
-            j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+            json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
                     + ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
                     + headDefautlsData + "}");
         }
-        list.add(j);
-        out.write(list.toString());
+        list.add(json);
+        response.getWriter().write(list.toString());
         return null;
     }
 
@@ -415,10 +431,12 @@ public class CreateOptimizationController extends RestrictedBaseController {
     private Set<String> getAllKeys(JSONArray arr, Set<String> 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;
@@ -433,16 +451,27 @@ public class CreateOptimizationController 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/getModelServiceVersionData.htm"},
+    /**
+     * getModelServiceVersionData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @return ModelAndView
+     * @throws IOException IOException
+     */
+    @RequestMapping(
+            value = {"/policyController/getModelServiceVersionData.htm"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
     public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
             throws IOException {
@@ -450,19 +479,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         JsonNode root = mapper.readTree(request.getReader());
 
-        String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
-        String servicename = value.split("-v")[0];
-        Set<String> returnList = getVersionList(servicename);
+        final String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+        final String servicename = value.split("-v")[0];
 
-        response.setCharacterEncoding(UTF8);
-        response.setContentType(APPLICATIONJSON);
-        request.setCharacterEncoding(UTF8);
+        response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+        response.setContentType(PolicyUtils.APPLICATION_JSON);
+        request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
         List<Object> list = new ArrayList<>();
-        PrintWriter out = response.getWriter();
-        String responseString = mapper.writeValueAsString(returnList);
-        JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString + "}");
-        list.add(j);
-        out.write(list.toString());
+        list.add(new JSONObject("{optimizationModelVersionData: "
+                + mapper.writeValueAsString(getVersionList(servicename)) + "}"));
+        response.getWriter().write(list.toString());
         return null;
     }
 
@@ -507,76 +533,46 @@ public class CreateOptimizationController extends RestrictedBaseController {
                 modelName);
     }
 
+    /**
+     * prePopulatePolicyData.
+     *
+     * @param policyAdapter PolicyRestAdapter
+     * @param entity PolicyEntity
+     */
     public void prePopulatePolicyData(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("OOF_") + 4);
-            policyAdapter.setPolicyName(policyNameValue);
-            String description = "";
-            try {
-                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
-            } catch (Exception e) {
-                LOGGER.error("Error while collecting the description tag in " + 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<AnyOfType> anyOfList = target.getAnyOf();
-                if (anyOfList != null) {
-                    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) {
-                            Iterator<AllOfType> iterAllOf = allOfList.iterator();
-                            while (iterAllOf.hasNext()) {
-                                AllOfType allOf = iterAllOf.next();
-                                // Under AllOFType we have Match
-                                List<MatchType> matchList = allOf.getMatch();
-                                if (matchList != null) {
-                                    Iterator<MatchType> 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 ("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("OOF_") + 4);
+        policyAdapter.setPolicyName(policyNameValue);
+        String description = "";
+        try {
+            description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+        } catch (Exception e) {
+            LOGGER.error("Error while collecting the description tag in " + 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()) {
+                for (MatchType match : allOf.getMatch()) {
+                    //
+                    // Under the match we have attribute value and
+                    // attributeDesignator. So,finally down to the actual attribute.
+                    //
+                    policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+                            (String) match.getAttributeValue().getContent().get(0));
                 }
+                readFile(policyAdapter, entity);
             }
         }
     }
@@ -612,7 +608,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
     }
 
-    @RequestMapping(value = {"/oof_dictionary/set_ModelData"},
+    /**
+     * setModelData.
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @throws IOException IOException
+     * @throws FileUploadException FileUploadException
+     */
+    @RequestMapping(
+            value = {"/oof_dictionary/set_ModelData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
     public void setModelData(HttpServletRequest request, HttpServletResponse response)
             throws IOException, FileUploadException {
@@ -655,16 +660,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
         }
 
         if (!errorMsg.isEmpty()) {
-
-            PrintWriter out = response.getWriter();
-
-            response.setCharacterEncoding(UTF8);
-            response.setContentType(APPLICATIONJSON);
-            request.setCharacterEncoding(UTF8);
-
-            JSONObject j = new JSONObject();
-            j.put("errorMsg", errorMsg);
-            out.write(j.toString());
+            response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+            response.setContentType(PolicyUtils.APPLICATION_JSON);
+            request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+            response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString());
             return;
         }
 
@@ -731,20 +730,18 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
         }
 
-        PrintWriter out = response.getWriter();
-
-        response.setCharacterEncoding(UTF8);
-        response.setContentType(APPLICATIONJSON);
-        request.setCharacterEncoding(UTF8);
+        response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+        response.setContentType(PolicyUtils.APPLICATION_JSON);
+        request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
 
         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", modelUtil.getDataOrderInfo());
+        JSONObject json = new JSONObject();
+        json.put("classListDatas", modelList);
+        json.put("modelDatas", mapper.writeValueAsString(classMap));
+        json.put("modelType", modelType);
+        json.put("dataOrderInfo", modelUtil.getDataOrderInfo());
 
-        out.write(j.toString());
+        response.getWriter().write(json.toString());
     }
 
     /*
@@ -752,7 +749,6 @@ public class CreateOptimizationController extends RestrictedBaseController {
      */
     @SuppressWarnings("rawtypes")
     private void extractFolder(String zipFile) {
-        int BUFFER = 2048;
         File file = new File(zipFile);
 
         try (ZipFile zip = new ZipFile(file)) {
@@ -809,16 +805,12 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
         classMap.putAll(tempMap);
         LOGGER.info(tempMap);
-
-        return;
-
     }
 
     private List<File> listModelFiles(String directoryName) {
         File fileDirectory = new File(directoryName);
         List<File> 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()) {
@@ -831,9 +823,9 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
     private List<String> createList() {
         List<String> list = new ArrayList<>();
-        for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
-            if (cMap.getValue().isPolicyTempalate()) {
-                list.add(cMap.getKey());
+        for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
+            if (entrySet.getValue().isPolicyTempalate()) {
+                list.add(entrySet.getKey());
             }
 
         }
@@ -858,7 +850,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
 
     private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) {
         OptimizationObject optimizationObject = new OptimizationObject();
-        optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_OOF));
+        optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_OOF));
 
         if (policyAdapter.getServiceType() != null) {
             optimizationObject.setService(policyAdapter.getServiceType());
@@ -888,7 +880,8 @@ public class CreateOptimizationController extends RestrictedBaseController {
     }
 }
 
-
+@Getter
+@Setter
 class OptimizationObject {
 
     private String service;
@@ -901,95 +894,5 @@ class OptimizationObject {
     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 getPriority() {
-        return priority;
-    }
-
-    public void setPriority(String priority) {
-        this.priority = priority;
-    }
-
-    public String getPolicyScope() {
-        return policyScope;
-    }
-
-    public void setPolicyScope(String policyScope) {
-        this.policyScope = policyScope;
-    }
-
-    public String getVersion() {
-        return version;
-    }
-
-    public void setVersion(String version) {
-        this.version = version;
-    }
-
     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 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 getTemplateVersion() {
-        return templateVersion;
-    }
-
-    public void setTemplateVersion(String templateVersion) {
-        this.templateVersion = templateVersion;
-    }
-
 }