More sonar cleanup and line consolidation
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyController.java
index 69444c4..40f6be8 100644 (file)
@@ -4,6 +4,7 @@
  * ================================================================================
  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -23,11 +24,13 @@ 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;
 import java.io.IOException;
 import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -35,12 +38,15 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Properties;
 import java.util.Set;
-import java.nio.charset.StandardCharsets;
+
 import javax.annotation.PostConstruct;
-import javax.mail.MessagingException;
 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;
@@ -57,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;
@@ -71,8 +78,6 @@ import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.servlet.ModelAndView;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 
 @Controller
 @RequestMapping("/")
@@ -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
@@ -208,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"));
@@ -260,7 +265,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Get FunctionData Type from DB.
-     * 
+     *
      * @return list of FunctionData.
      */
     public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
@@ -274,7 +279,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Get Function ID.
-     * 
+     *
      * @return Function ID.
      */
     public static Map<String, FunctionDefinition> getFunctionIdMap() {
@@ -302,21 +307,21 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Get Functional Definition data.
-     * 
-     * @param request  HttpServletRequest.
+     *
+     * @param request HttpServletRequest.
      * @param response HttpServletResponse.
      */
-    @RequestMapping(value = { "/get_FunctionDefinitionDataByName" }, method = {
-            org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
+    @RequestMapping(
+            value = {"/get_FunctionDefinitionDataByName"},
+            method = {org.springframework.web.bind.annotation.RequestMethod.GET},
+            produces = MediaType.APPLICATION_JSON_VALUE)
     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());
+            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);
@@ -325,8 +330,8 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Get PolicyEntity Data from db.
-     * 
-     * @param scope      scopeName.
+     *
+     * @param scope scopeName.
      * @param policyName policyName.
      * @return policyEntity data.
      */
@@ -338,7 +343,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Get Policy User Roles from db.
-     * 
+     *
      * @param userId LoginID.
      * @return list of Roles.
      */
@@ -357,21 +362,21 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Get List of User Roles.
-     * 
-     * @param request  HttpServletRequest.
+     *
+     * @param request HttpServletRequest.
      * @param response HttpServletResponse.
      */
-    @RequestMapping(value = { "/get_UserRolesData" }, method = {
-            org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
+    @RequestMapping(
+            value = {"/get_UserRolesData"},
+            method = {org.springframework.web.bind.annotation.RequestMethod.GET},
+            produces = MediaType.APPLICATION_JSON_VALUE)
     public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
         try {
             String userId = UserUtils.getUserSession(request).getOrgUserId();
             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);
         }
@@ -379,11 +384,11 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Policy tabs Model and View.
-     * 
+     *
      * @param request Request input.
      * @return view model.
      */
-    @RequestMapping(value = { "/policy", "/policy/Editor" }, method = RequestMethod.GET)
+    @RequestMapping(value = {"/policy", "/policy/Editor"}, method = RequestMethod.GET)
     public ModelAndView view(HttpServletRequest request) {
         getUserRoleFromSession(request);
         String myRequestUrl = request.getRequestURL().toString();
@@ -402,7 +407,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Read the role from session for inserting into the database.
-     * 
+     *
      * @param request Request input for Role.
      */
     public void getUserRoleFromSession(HttpServletRequest request) {
@@ -440,9 +445,9 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Build a delete query for cleaning up roles and execute it.
-     * 
+     *
      * @param filteredRoles Filtered roles list.
-     * @param userId        UserID.
+     * @param userId UserID.
      */
     private void cleanUpRoles(List<String> filteredRoles, String userId) {
         StringBuilder query = new StringBuilder();
@@ -460,10 +465,10 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Save the Role to DB.
-     * 
-     * @param name         User Name.
+     *
+     * @param name User Name.
      * @param filteredRole Role Name.
-     * @param userId       User LoginID.
+     * @param userId User LoginID.
      */
     private void savePolicyRoles(String name, String filteredRole, String userId) {
         UserInfo userInfo = new UserInfo();
@@ -479,7 +484,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Filter the list of roles hierarchy wise.
-     * 
+     *
      * @param newRoles list of roles from request.
      * @return
      */
@@ -524,7 +529,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Get UserName based on LoginID.
-     * 
+     *
      * @param createdBy loginID.
      * @return name.
      */
@@ -536,7 +541,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Check if the Policy is Active or not.
-     * 
+     *
      * @param query sql query.
      * @return boolean.
      */
@@ -579,29 +584,24 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Watch Policy Function.
-     * 
-     * @param entity     PolicyVersion entity.
+     *
+     * @param entity PolicyVersion entity.
      * @param policyName updated policy name.
-     * @param mode       type of action rename/delete/import.
+     * @param mode type of action rename/delete/import.
      */
     public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) {
         PolicyNotificationMail email = new PolicyNotificationMail();
-        try {
-            email.sendMail(entity, policyName, mode, commonClassDao);
-        } catch (MessagingException e) {
-            policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
-                    + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
-        }
+        email.sendMail(entity, policyName, mode, commonClassDao);
     }
 
     /**
      * 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_");
@@ -617,20 +617,19 @@ public class PolicyController extends RestrictedBaseController {
         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);
@@ -638,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) {
@@ -653,6 +659,12 @@ 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));
         Object policy = XACMLPolicyScanner.readPolicy(stream);
@@ -660,24 +672,34 @@ public class PolicyController extends RestrictedBaseController {
             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 pVersion = 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());
+        }
 
-        UserInfo userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getCreatedBy());
-        UserInfo userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getModifiedBy());
-        result[0] = userCreate != null ? userCreate.getUserName() : "super-admin";
-        result[1] = userModify != null ? userModify.getUserName() : "super-admin";
+        result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN;
+        result[1] = userModify != null ? userModify.getUserName() : SUPERADMIN;
 
         return result;
     }
@@ -936,7 +958,7 @@ public class PolicyController extends RestrictedBaseController {
 
     /**
      * Set File Size limit.
-     * 
+     *
      * @param uploadSize value.
      */
     public static void setFileSizeLimit(String uploadSize) {
@@ -954,14 +976,14 @@ 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;
     }