Fixed various sonar identified code smells
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / policy / PolicyClient.java
index 9f25ba9..68d8529 100644 (file)
@@ -5,6 +5,8 @@
  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
  *                             reserved.
  * ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -63,7 +65,6 @@ import org.onap.policy.api.PolicyType;
 import org.onap.policy.api.PushPolicyParameters;
 import org.onap.policy.api.RuleProvider;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
 import org.springframework.context.annotation.Primary;
 import org.springframework.stereotype.Component;
 
@@ -74,23 +75,23 @@ import org.springframework.stereotype.Component;
 @Primary
 public class PolicyClient {
 
-    protected PolicyEngine policyEngine;
-    protected static final String LOG_POLICY_PREFIX = "Response is ";
-    protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
-    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
-    public static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
-    public static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
-    public static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix";
-    public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix";
+    private PolicyEngine policyEngine;
+    private static final String LOG_POLICY_PREFIX = "Response is ";
+    private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
+    private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+    private static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
+    private static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
+    private static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix";
+    private static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix";
     public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix";
-    public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type";
-    public static final String POLICY_GUARD_SUFFIX = "_Guard";
-    public static final String TOSCA_FILE_TEMP_PATH = "tosca.filePath";
+    private static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type";
+    private static final String TOSCA_FILE_TEMP_PATH = "tosca.filePath";
+    private static final String POLICY_COMMUNICATION_LOG_MESSAGE = "Exception occurred during policy communication";
+    private static final String POLICY_COMMUNICATION_EXC_MESSAGE = "Exception while communicating with Policy";
+    private static final String POLICY = "Policy";
 
     @Autowired
-    protected ApplicationContext appContext;
-    @Autowired
-    protected ClampProperties refProp;
+    private ClampProperties refProp;
     @Autowired
     private PolicyConfiguration policyConfiguration;
 
@@ -122,8 +123,8 @@ public class PolicyClient {
         // Set a random UUID(Mandatory)
         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
 
-        String rtnMsg = send(policyParameters, prop, null);
-        push(DictionaryType.Decision.toString(), prop);
+        String rtnMsg = send(policyParameters, prop, null, null);
+        push(DictionaryType.Decision.toString(), prop, null);
         return rtnMsg;
     }
 
@@ -153,9 +154,9 @@ public class PolicyClient {
         // Set a random UUID(Mandatory)
         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
         String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
-        String rtnMsg = send(policyParameters, prop, policyNamePrefix);
+        String rtnMsg = send(policyParameters, prop, policyNamePrefix, null);
         String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
-        push(policyType, prop);
+        push(policyType, prop, null);
         return rtnMsg;
     }
 
@@ -183,9 +184,9 @@ public class PolicyClient {
         // Adding this line to clear the policy id from policy name while
         // pushing to policy engine
         prop.setPolicyUniqueId("");
-        String rtnMsg = send(policyParameters, prop, policyNamePrefix);
+        String rtnMsg = send(policyParameters, prop, policyNamePrefix, null);
         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
-        push(policyType, prop);
+        push(policyType, prop, null);
         return rtnMsg;
     }
 
@@ -218,8 +219,9 @@ public class PolicyClient {
         // Adding this line to clear the policy id from policy name while
         // pushing to policy engine
         prop.setPolicyUniqueId("");
-        String rtnMsg = send(policyParameters, prop, refProp.getStringValue(POLICY_BASENAME_PREFIX_PROPERTY_NAME));
-        push(PolicyConfigType.Base.toString(), prop);
+        String rtnMsg = send(policyParameters, prop, refProp.getStringValue(POLICY_BASENAME_PREFIX_PROPERTY_NAME),
+            null);
+        push(PolicyConfigType.Base.toString(), prop, null);
         return rtnMsg;
     }
 
@@ -243,9 +245,9 @@ public class PolicyClient {
         // Adding this line to clear the policy id from policy name while
         // pushing to policy engine
         prop.setPolicyUniqueId("");
-        String rtnMsg = send(policyParameters, prop, policyNamePrefix);
+        String rtnMsg = send(policyParameters, prop, policyNamePrefix, null);
         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
-        push(policyType, prop);
+        push(policyType, prop, null);
         return rtnMsg;
     }
 
@@ -258,7 +260,8 @@ public class PolicyClient {
      *        The ModelProperties
      * @return The response message of Policy
      */
-    protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
+    protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyPrefix,
+        String policyNameWithPrefix) {
         // Verify whether it is triggered by Validation Test button from UI
         if (prop.isTestOnly()) {
             return "send not executed for test action";
@@ -270,13 +273,13 @@ public class PolicyClient {
         try {
             if ((PolicyClass.Decision.equals(policyParameters.getPolicyClass()) && !checkDecisionPolicyExists(prop))
                 || (PolicyClass.Config.equals(policyParameters.getPolicyClass())
-                    && !checkPolicyExists(policyNamePrefix, prop))) {
-                LoggingUtils.setTargetContext("Policy", "createPolicy");
+                    && !checkPolicyExists(prop, policyPrefix, policyNameWithPrefix))) {
+                LoggingUtils.setTargetContext(POLICY, "createPolicy");
                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
                 response = getPolicyEngine().createPolicy(policyParameters);
                 responseMessage = response.getResponseMessage();
             } else {
-                LoggingUtils.setTargetContext("Policy", "updatePolicy");
+                LoggingUtils.setTargetContext(POLICY, "updatePolicy");
                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
                 response = getPolicyEngine().updatePolicy(policyParameters);
                 responseMessage = response.getResponseMessage();
@@ -284,8 +287,8 @@ public class PolicyClient {
         } catch (Exception e) {
             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
             LoggingUtils.setErrorContext("900", "Policy send error");
-            logger.error("Exception occurred during policy communication", e);
-            throw new PolicyClientException("Exception while communicating with Policy", e);
+            logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e);
+            throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e);
         }
         logger.info(LOG_POLICY_PREFIX + responseMessage);
         LoggingUtils.setTimeContext(startTime, new Date());
@@ -311,22 +314,13 @@ public class PolicyClient {
      *        The ModelProperties
      * @return The response message of policy
      */
-    protected String push(String policyType, ModelProperties prop) {
+    protected String push(String policyType, ModelProperties prop, String policyName) {
         // Verify whether it is triggered by Validation Test button from UI
         if (prop.isTestOnly()) {
             return "push not executed for test action";
         }
         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
-        // Parameter arguments
-        if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
-            if (DictionaryType.Decision.toString().equals(policyType)) {
-                pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId());
-            } else {
-                pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
-            }
-        } else {
-            pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
-        }
+        pushPolicyParameters.setPolicyName(selectRightPolicyName(prop, policyType, policyName));
         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
         pushPolicyParameters.setPolicyType(policyType);
         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
@@ -335,7 +329,7 @@ public class PolicyClient {
         PolicyChangeResponse response;
         String responseMessage = "";
         try {
-            LoggingUtils.setTargetContext("Policy", "pushPolicy");
+            LoggingUtils.setTargetContext(POLICY, "pushPolicy");
             logger.info("Attempting to push policy...");
             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
             if (response != null) {
@@ -344,8 +338,8 @@ public class PolicyClient {
         } catch (Exception e) {
             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
             LoggingUtils.setErrorContext("900", "Policy push error");
-            logger.error("Exception occurred during policy communication", e);
-            throw new PolicyClientException("Exception while communicating with Policy", e);
+            logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e);
+            throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e);
         }
         logger.info(LOG_POLICY_PREFIX + responseMessage);
         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
@@ -374,7 +368,7 @@ public class PolicyClient {
         logger.info("Search in Policy Engine for DecisionpolicyName=" + prop.getPolicyScopeAndNameWithUniqueGuardId());
         try {
             // No other choice than pushing to see if it exists or not
-            String response = push(DictionaryType.Decision.toString(), prop);
+            String response = push(DictionaryType.Decision.toString(), prop, null);
             if (response != null) {
                 policyexists = true;
             }
@@ -389,25 +383,21 @@ public class PolicyClient {
      * Use list Policy API to retrieve the policy. Return true if policy exists
      * otherwise return false.
      *
-     * @param policyNamePrefix
-     *        The Policy Name Prefix
      * @param prop
      *        The ModelProperties
+     * @param policyPrefix
+     *        The Policy Name Prefix
+     * @param policyNameWithPrefix
+     *        The Policy Full Name
      * @return The response message from policy
      * @throws PolicyConfigException
      *         In case of issues with policy engine
      */
-    protected boolean checkPolicyExists(String policyNamePrefix, ModelProperties prop) {
+    protected boolean checkPolicyExists(ModelProperties prop, String policyPrefix, String policyNameWithPrefix) {
         boolean policyexists = false;
         String policyName = "";
         try {
-
-            if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
-                policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_"
-                    + prop.getPolicyUniqueId();
-            } else {
-                policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
-            }
+            policyName = selectRightPolicyNameWithPrefix(prop, policyPrefix, policyNameWithPrefix);
             logger.info("Search in Policy Engine for policyName=" + policyName);
 
             ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
@@ -447,18 +437,7 @@ public class PolicyClient {
      * @return The response message from Policy
      */
     public String deleteMicrosService(ModelProperties prop) {
-        String deletePolicyResponse = "";
-        try {
-            String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
-            if (checkPolicyExists(policyNamePrefix, prop)) {
-                String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
-                deletePolicyResponse = deletePolicy(prop, policyType);
-            }
-        } catch (Exception e) {
-            logger.error("Exception occurred during policy communication", e);
-            throw new PolicyClientException("Exception while communicating with Policy", e);
-        }
-        return deletePolicyResponse;
+        return findAndDelete(prop, POLICY_MS_NAME_PREFIX_PROPERTY_NAME, POLICY_MSTYPE_PROPERTY_NAME);
     }
 
     /**
@@ -469,7 +448,7 @@ public class PolicyClient {
      * @return A string with the answer from policy
      */
     public String deleteBasePolicy(ModelProperties prop) {
-        return deletePolicy(prop, PolicyConfigType.Base.toString());
+        return deletePolicy(prop, PolicyConfigType.Base.toString(), null);
     }
 
     /**
@@ -484,11 +463,11 @@ public class PolicyClient {
         try {
 
             if (checkDecisionPolicyExists(prop)) {
-                deletePolicyResponse = deletePolicy(prop, DictionaryType.Decision.toString());
+                deletePolicyResponse = deletePolicy(prop, DictionaryType.Decision.toString(), null);
             }
         } catch (Exception e) {
-            logger.error("Exception occurred during policy communication", e);
-            throw new PolicyClientException("Exception while communicating with Policy", e);
+            logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e);
+            throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e);
         }
         return deletePolicyResponse;
     }
@@ -501,38 +480,76 @@ public class PolicyClient {
      * @return The response message from policy
      */
     public String deleteBrms(ModelProperties prop) {
+        return findAndDelete(prop, POLICY_OP_NAME_PREFIX_PROPERTY_NAME, POLICY_OP_TYPE_PROPERTY_NAME);
+    }
+
+    private String findAndDelete(ModelProperties prop, String policyPrefixProperty, String policyTypeProperty) {
         String deletePolicyResponse = "";
         try {
-            String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
-            if (checkPolicyExists(policyNamePrefix, prop)) {
-                String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
-                deletePolicyResponse = deletePolicy(prop, policyType);
+            String policyNamePrefix = refProp.getStringValue(policyPrefixProperty);
+            if (checkPolicyExists(prop, policyNamePrefix, null)) {
+                String policyType = refProp.getStringValue(policyTypeProperty);
+                deletePolicyResponse = deletePolicy(prop, policyType, null);
             }
         } catch (Exception e) {
-            logger.error("Exception occurred during policy communication", e);
-            throw new PolicyClientException("Exception while communicating with Policy", e);
+            logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e);
+            throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e);
         }
         return deletePolicyResponse;
     }
 
+    protected String selectRightPolicyName(ModelProperties prop, String policyType, String policyName) {
+        if (policyName == null) {
+            if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
+                if (DictionaryType.Decision.toString().equals(policyType)) {
+                    return prop.getPolicyScopeAndNameWithUniqueGuardId();
+                } else {
+                    return prop.getPolicyScopeAndNameWithUniqueId();
+                }
+            } else {
+                return prop.getCurrentPolicyScopeAndPolicyName();
+            }
+        } else {
+            return policyName;
+        }
+    }
+
     /**
-     * Format and send delete PAP and PDP requests to Policy.
+     * Method to return correct policy name with prefix.
      *
      * @param prop
      *        The ModelProperties
-     * @return The response message from policy
+     * @param policyPrefix
+     *        Policy Prefix
+     * @param policyNameWithPrefix
+     *        Policy Name With Prefix
+     * @return The policy name with the prefix
      */
-    protected String deletePolicy(ModelProperties prop, String policyType) {
-        DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
-        if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
-            if (DictionaryType.Decision.toString().equals(policyType)) {
-                deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId());
+    protected String selectRightPolicyNameWithPrefix(ModelProperties prop, String policyPrefix,
+        String policyNameWithPrefix) {
+        if (policyNameWithPrefix == null) {
+            if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
+                return prop.getCurrentPolicyScopeAndFullPolicyName(policyPrefix) + "_" + prop.getPolicyUniqueId();
             } else {
-                deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
+                return prop.getCurrentPolicyScopeAndFullPolicyName(policyPrefix);
             }
         } else {
-            deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
+            return policyNameWithPrefix;
         }
+    }
+
+    /**
+     * Format and send delete PAP and PDP requests to Policy.
+     *
+     * @param prop
+     *        The ModelProperties
+     * @param policyType
+     *        The policyType "Decision" or
+     * @return The response message from policy
+     */
+    protected String deletePolicy(ModelProperties prop, String policyType, String policyName) {
+        DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
+        deletePolicyParameters.setPolicyName(selectRightPolicyName(prop, policyType, policyName));
         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
         logger.info("Deleting policy from PDP...");
         deletePolicyParameters.setPolicyComponent("PDP");
@@ -540,8 +557,8 @@ public class PolicyClient {
         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
         deletePolicyParameters.setPolicyType(policyType);
         // send delete request
-        StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
         logger.info("Deleting policy from PAP...");
+        StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
         deletePolicyParameters.setPolicyComponent("PAP");
         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
         // send delete request
@@ -584,7 +601,7 @@ public class PolicyClient {
     }
 
     /**
-     * Create a temp Tosca model file and perform import model to Policy Engine
+     * Create a temp Tosca model file and perform import model to Policy Engine.
      *
      * @param cldsToscaModel
      *        Policy model details
@@ -615,11 +632,12 @@ public class PolicyClient {
     }
 
     /**
+     * Import the model.
      * @param importParameters
      *        The ImportParameters
      * @return The response message from policy
      */
-    protected String importModel(ImportParameters importParameters) {
+    private String importModel(ImportParameters importParameters) {
         PolicyChangeResponse response = null;
         String responseMessage = "";
 
@@ -632,8 +650,8 @@ public class PolicyClient {
         } catch (Exception e) {
             LoggingUtils.setResponseContext("900", "Policy Model import failed", this.getClass().getName());
             LoggingUtils.setErrorContext("900", "Policy Model import error");
-            logger.error("Exception occurred during policy communication", e);
-            throw new PolicyClientException("Exception while communicating with Policy", e);
+            logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e);
+            throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e);
         }
         logger.info(LOG_POLICY_PREFIX + responseMessage);
         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
@@ -650,6 +668,7 @@ public class PolicyClient {
     }
 
     /**
+     * Build file path for tosca file.
      * @param clampToscaPath
      *        Temp directory path for writing tosca files
      * @param toscaModelName