More sonar cleanup and line consolidation
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyController.java
index 3485163..40f6be8 100644 (file)
@@ -24,6 +24,7 @@ package org.onap.policy.controller;
 
 import com.att.research.xacml.util.XACMLProperties;
 import com.fasterxml.jackson.databind.ObjectMapper;
+
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileInputStream;
@@ -37,12 +38,15 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Properties;
 import java.util.Set;
+
 import javax.annotation.PostConstruct;
 import javax.script.SimpleBindings;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
 import org.json.JSONObject;
 import org.onap.policy.admin.PolicyNotificationMail;
 import org.onap.policy.admin.RESTfulPAPEngine;
@@ -59,6 +63,7 @@ import org.onap.policy.rest.jpa.FunctionDefinition;
 import org.onap.policy.rest.jpa.PolicyEntity;
 import org.onap.policy.rest.jpa.PolicyVersion;
 import org.onap.policy.rest.jpa.UserInfo;
+import org.onap.policy.utils.PeCryptoUtils;
 import org.onap.policy.utils.UserUtils.Pair;
 import org.onap.policy.xacml.api.XACMLErrorConstants;
 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
@@ -159,8 +164,8 @@ public class PolicyController extends RestrictedBaseController {
         return jUnit;
     }
 
-    public static void setjUnit(boolean jUnit) {
-        PolicyController.jUnit = jUnit;
+    public static void setjUnit(boolean isJunit) {
+        PolicyController.jUnit = isJunit;
     }
 
     @Autowired
@@ -182,9 +187,8 @@ public class PolicyController extends RestrictedBaseController {
         try {
             String fileName;
             if (jUnit) {
-                fileName = new File(".").getCanonicalPath() + File.separator + "src"
-                        + File.separator + "test" + File.separator + "resources" + File.separator
-                        + "JSONConfig.json";
+                fileName = new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test"
+                        + File.separator + "resources" + File.separator + "JSONConfig.json";
             } else {
                 fileName = "xacml.admin.properties";
             }
@@ -209,12 +213,12 @@ public class PolicyController extends RestrictedBaseController {
             setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
             setLogdbUrl(prop.getProperty("xacml.log.db.url"));
             setLogdbUserName(prop.getProperty("xacml.log.db.user"));
-            setLogdbPassword(prop.getProperty("xacml.log.db.password"));
+            setLogdbPassword(PeCryptoUtils.decrypt(prop.getProperty("xacml.log.db.password")));
             setLogdbDialect(prop.getProperty("onap.dialect"));
             // Xacml Database Properties
             setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
             setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
-            setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
+            setXacmldbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password")));
             // AutoPuh
             setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
             setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
@@ -235,19 +239,17 @@ public class PolicyController extends RestrictedBaseController {
             // Get the Property Values for Dashboard tab Limit
             try {
                 setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
-                setSystemAlertTableLimit(
-                        prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
+                setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
             } catch (Exception e) {
-                policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
-                        + "Dashboard tab Property fields are missing" + e);
+                policyLogger
+                        .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Dashboard tab Property fields are missing" + e);
                 setLogTableLimit("5000");
                 setSystemAlertTableLimit("2000");
             }
             System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
         } catch (IOException ex) {
             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
-                    + "Exception Occured while reading the Smtp properties from xacml.admin.properties file"
-                    + ex);
+                    + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + ex);
         }
 
         // Initialize the FunctionDefinition table at Server Start up
@@ -297,8 +299,7 @@ public class PolicyController extends RestrictedBaseController {
             FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
             mapID2Function.put(value.getXacmlid(), value);
             if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
-                mapDatatype2Function.put(value.getDatatypeBean(),
-                        new ArrayList<FunctionDefinition>());
+                mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
             }
             mapDatatype2Function.get(value.getDatatypeBean()).add(value);
         }
@@ -310,22 +311,20 @@ public class PolicyController extends RestrictedBaseController {
      * @param request HttpServletRequest.
      * @param response HttpServletResponse.
      */
-    @RequestMapping(value = {"/get_FunctionDefinitionDataByName"},
+    @RequestMapping(
+            value = {"/get_FunctionDefinitionDataByName"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
             produces = MediaType.APPLICATION_JSON_VALUE)
-    public void getFunctionDefinitionData(HttpServletRequest request,
-            HttpServletResponse response) {
+    public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) {
         try {
             Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
-            model.put("functionDefinitionDatas", mapper.writeValueAsString(
-                    commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
-            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-            JSONObject j = new JSONObject(msg);
-            response.getWriter().write(j.toString());
+            model.put("functionDefinitionDatas",
+                    mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
+            response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
         } catch (Exception e) {
-            policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
-                    + "Error while retriving the Function Definition data" + e);
+            policyLogger.error(
+                    XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e);
         }
     }
 
@@ -367,7 +366,8 @@ public class PolicyController extends RestrictedBaseController {
      * @param request HttpServletRequest.
      * @param response HttpServletResponse.
      */
-    @RequestMapping(value = {"/get_UserRolesData"},
+    @RequestMapping(
+            value = {"/get_UserRolesData"},
             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
             produces = MediaType.APPLICATION_JSON_VALUE)
     public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
@@ -376,9 +376,7 @@ public class PolicyController extends RestrictedBaseController {
             Map<String, Object> model = new HashMap<>();
             ObjectMapper mapper = new ObjectMapper();
             model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
-            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) {
             policyLogger.error("Exception Occured" + e);
         }
@@ -401,8 +399,7 @@ public class PolicyController extends RestrictedBaseController {
             setPapEngine(new RESTfulPAPEngine(myRequestUrl));
             new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl));
         } catch (Exception e) {
-            policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
-                    + "Exception Occured while loading PAP" + e);
+            policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e);
         }
         Map<String, Object> model = new HashMap<>();
         return new ModelAndView("policy_Editor", "model", model);
@@ -437,8 +434,7 @@ public class PolicyController extends RestrictedBaseController {
                 savePolicyRoles(name, filteredRole, userId);
             } else {
                 userRoles = getRoles(userId);
-                Pair<Set<String>, List<String>> pair =
-                        org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+                Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
                 roles = pair.u;
                 if (!roles.contains(filteredRole)) {
                     savePolicyRoles(name, filteredRole, userId);
@@ -510,8 +506,7 @@ public class PolicyController extends RestrictedBaseController {
                 roles.clear();
                 roles.add(SUPERADMIN);
             }
-            if (!roles.contains(SUPERADMIN)
-                    || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
+            if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
                 if ("Policy Admin".equalsIgnoreCase(role.trim())) {
                     roles.add("admin");
                 } else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
@@ -575,8 +570,7 @@ public class PolicyController extends RestrictedBaseController {
     }
 
     public PolicyVersion getPolicyEntityFromPolicyVersion(String query) {
-        return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName",
-                query);
+        return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
     }
 
     public List<Object> getDataByQuery(String query, SimpleBindings params) {
@@ -603,11 +597,11 @@ public class PolicyController extends RestrictedBaseController {
     /**
      * Switch Version Policy Content.
      *
-     * @param pName which is used to find associated versions.
+     * @param thePolicyName which is used to find associated versions.
      * @return list of available versions based on policy name.
      */
-    public JSONObject switchVersionPolicyContent(String pName) {
-        String policyName = pName;
+    public JSONObject switchVersionPolicyContent(String thePolicyName) {
+        String policyName = thePolicyName;
         String dbCheckName = policyName.replace("/", ".");
         if (dbCheckName.contains("Config_")) {
             dbCheckName = dbCheckName.replace(".Config_", ":Config_");
@@ -619,25 +613,23 @@ public class PolicyController extends RestrictedBaseController {
             dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
         }
         String[] splitDbCheckName = dbCheckName.split(":");
-        String query =
-                "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
+        String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
         SimpleBindings params = new SimpleBindings();
         params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
         params.put("splitDBCheckName0", splitDbCheckName[0]);
-        List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
         List<String> av = new ArrayList<>();
-        for (Object entity : policyEntity) {
-            PolicyEntity pEntity = (PolicyEntity) entity;
-            String removeExtension = pEntity.getPolicyName().replace(".xml", "");
+        for (Object entity : commonClassDao.getDataByQuery(query, params)) {
+            PolicyEntity policyEntity = (PolicyEntity) entity;
+            String removeExtension = policyEntity.getPolicyName().replace(".xml", "");
             String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
-            String userName = getUserId(pEntity, "@ModifiedBy:");
-            av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
+            String userName = getUserId(policyEntity, "@ModifiedBy:");
+            av.add(version + " | " + policyEntity.getModifiedDate() + " | " + userName);
         }
         if (policyName.contains("/")) {
             policyName = policyName.replace("/", File.separator);
         }
-        PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class,
-                "policyName", policyName);
+        PolicyVersion entity =
+                (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
         JSONObject el = new JSONObject();
         el.put("activeVersion", entity.getActiveVersion());
         el.put("availableVersions", av);
@@ -645,13 +637,20 @@ public class PolicyController extends RestrictedBaseController {
         return el;
     }
 
+    /**
+     * getUserId.
+     *
+     * @param data PolicyEntity
+     * @param value String
+     * @return String
+     */
     public String getUserId(PolicyEntity data, String value) {
         String userId = "";
-        String uValue = value;
+        String userValue = value; // Why?
         String description = getDescription(data);
-        if (description.contains(uValue)) {
-            userId = description.substring(description.indexOf(uValue) + uValue.length(),
-                    description.lastIndexOf(uValue));
+        if (description.contains(userValue)) {
+            userId = description.substring(description.indexOf(userValue) + userValue.length(),
+                    description.lastIndexOf(userValue));
         }
         UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
         if (userInfo == null) {
@@ -660,35 +659,43 @@ public class PolicyController extends RestrictedBaseController {
         return userInfo.getUserName();
     }
 
+    /**
+     * getDescription.
+     *
+     * @param data PolicyEntity
+     * @return String
+     */
     public String getDescription(PolicyEntity data) {
-        InputStream stream =
-                new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
+        InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
         Object policy = XACMLPolicyScanner.readPolicy(stream);
         if (policy instanceof PolicySetType) {
             return ((PolicySetType) policy).getDescription();
         } else if (policy instanceof PolicyType) {
             return ((PolicyType) policy).getDescription();
-        } else {
-            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE
-                    + "Expecting a PolicySet/Policy/Rule object. Got: "
-                    + policy.getClass().getCanonicalName());
-            return null;
         }
+        PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
+                + policy.getClass().getCanonicalName());
+        return null;
     }
 
+    /**
+     * getUserInfo.
+     *
+     * @param data PolicyEntity
+     * @param activePolicies list of active policies
+     * @return array of String
+     */
     public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
         String policyName = data.getScope().replace(".", File.separator) + File.separator
                 + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
-        PolicyVersion polVersion = activePolicies.stream()
-                .filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null);
+        PolicyVersion polVersion =
+                activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null);
         String[] result = new String[2];
         UserInfo userCreate = null;
         UserInfo userModify = null;
         if (polVersion != null) {
-            userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
-                    polVersion.getCreatedBy());
-            userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
-                    polVersion.getModifiedBy());
+            userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getCreatedBy());
+            userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getModifiedBy());
         }
 
         result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN;
@@ -725,8 +732,7 @@ public class PolicyController extends RestrictedBaseController {
         return mapDatatype2Function;
     }
 
-    public static void setMapDatatype2Function(
-            Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
+    public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
         PolicyController.mapDatatype2Function = mapDatatype2Function;
     }
 
@@ -971,13 +977,13 @@ public class PolicyController extends RestrictedBaseController {
     /**
      * Function to convert date.
      *
-     * @param dateTTL input date value.
+     * @param dateTimeToLive input date value.
      * @return
      */
-    public String convertDate(String dateTTL) {
+    public String convertDate(String dateTimeToLive) {
         String formateDate = null;
-        if (dateTTL.contains("-")) {
-            formateDate = dateTTL.replace("-", "/");
+        if (dateTimeToLive.contains("-")) {
+            formateDate = dateTimeToLive.replace("-", "/");
         }
         return formateDate;
     }