Merge "Remove Variable in POM"
[clamp.git] / src / main / java / org / onap / clamp / clds / client / PolicyClient.java
index d19c216..22f215c 100644 (file)
@@ -5,16 +5,16 @@
  * Copyright (C) 2017 AT&T Intellectual Property. All rights
  *                             reserved.
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License"); 
- * you may not use this file except in compliance with the License. 
+ * 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
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software 
- * distributed under the License is distributed on an "AS IS" BASIS, 
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
- * See the License for the specific language governing permissions and 
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
  * limitations under the License.
  * ============LICENSE_END============================================
  * ===================================================================
 
 package org.onap.clamp.clds.client;
 
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.ws.rs.BadRequestException;
+
 import org.onap.clamp.clds.model.prop.ModelProperties;
 import org.onap.clamp.clds.model.refprop.RefProp;
-import org.onap.policy.api.*;
+import org.onap.clamp.clds.util.LoggingUtils;
+import org.onap.policy.api.AttributeType;
+import org.onap.policy.api.ConfigRequestParameters;
+import org.onap.policy.api.DeletePolicyCondition;
+import org.onap.policy.api.DeletePolicyParameters;
+import org.onap.policy.api.PolicyChangeResponse;
+import org.onap.policy.api.PolicyConfig;
+import org.onap.policy.api.PolicyConfigType;
+import org.onap.policy.api.PolicyEngine;
+import org.onap.policy.api.PolicyEngineException;
+import org.onap.policy.api.PolicyParameters;
+import org.onap.policy.api.PolicyType;
+import org.onap.policy.api.PushPolicyParameters;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.ApplicationContext;
 
-import java.util.*;
-import java.util.logging.Logger;
-
-
 /**
  * Policy utility methods - specifically, send the policy.
  */
 public class PolicyClient {
-    // currently uses the java.util.logging.Logger like the Camunda engine
-    private static final Logger logger = Logger.getLogger(PolicyClient.class.getName());
 
-    @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:etc/clds/clds-policy-config.properties'}")
-    private String cldsPolicyConfigFile;
+    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();
+
+    @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}")
+    protected String                  cldsPolicyConfigFile;
 
     @Autowired
-    private ApplicationContext appContext;
-    
+    protected ApplicationContext      appContext;
+
     @Autowired
-    private RefProp refProp;
-    
-    public PolicyClient() {
-        
-    }
+    protected RefProp                 refProp;
 
     /**
-     * Perform send of microservice policy
+     * Perform send of microservice policy.
      *
      * @param attributes
+     *            A map of attributes
      * @param prop
-     * @param policyRequestUUID
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @param policyRequestUuid
+     *            PolicyRequest UUID
+     * @return The response message of policy
+     * @throws IOException
+     *             In case of issues with the Stream
+     * @throws PolicyEngineException
+     *             In case of issues with the PolicyEngine class
+     * 
      */
-    public String sendBrms(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop, String policyRequestUUID) throws Exception {
+    public String sendBrms(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
+            String policyRequestUuid) throws PolicyEngineException, IOException {
 
         PolicyParameters policyParameters = new PolicyParameters();
 
@@ -71,19 +101,19 @@ public class PolicyClient {
         policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
 
         // Set Policy Name(Mandatory)
-        policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
-        //Set Scope folder where the policy needs to be created(Mandatory)
-        //policyParameters.setPolicyScope(policyScope);
+        policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
 
-        // documentation says this is options, but when tested, got the following failure: java.lang.Exception: Policy send failed: PE300 - Data Issue: No policyDescription given.
+        // documentation says this is options, but when tested, got the
+        // following failure: java.lang.Exception: Policy send failed: PE300 -
+        // Data Issue: No policyDescription given.
         policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
 
         policyParameters.setAttributes(attributes);
 
-        //Set a random UUID(Mandatory)
-        policyParameters.setRequestID(UUID.fromString(policyRequestUUID));
-
-        String rtnMsg = send(policyParameters, prop);
+        // Set a random UUID(Mandatory)
+        policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
+        String policyNamePrefix = refProp.getStringValue("policy.op.policyNamePrefix");
+        String rtnMsg = send(policyParameters, prop, policyNamePrefix);
 
         String policyType = refProp.getStringValue("policy.op.type");
         push(policyType, prop);
@@ -92,30 +122,41 @@ public class PolicyClient {
     }
 
     /**
-     * Perform send of microservice policy
+     * Perform send of microservice policy.
      *
      * @param policyJson
+     *            The policy JSON
      * @param prop
-     * @param policyRequestUUID
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @param policyRequestUuid
+     *            The policy Request UUID
+     * @return The response message of policy
+     * @throws PolicyEngineException
+     *             In case of issues with the policy engine class creation
+     * @throws IOException
+     *             In case of issue with the Stream
      */
-    public String sendMicroService(String policyJson, ModelProperties prop, String policyRequestUUID) throws Exception {
+    public String sendMicroService(String policyJson, ModelProperties prop, String policyRequestUuid)
+            throws IOException, PolicyEngineException {
 
         PolicyParameters policyParameters = new PolicyParameters();
 
         // Set Policy Type
         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
-        policyParameters.setOnapName(refProp.getStringValue("policy.onap.name"));
+        policyParameters.setEcompName(refProp.getStringValue("policy.ecomp.name"));
         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
 
         policyParameters.setConfigBody(policyJson);
         policyParameters.setConfigBodyType(PolicyType.JSON);
 
-        policyParameters.setRequestID(UUID.fromString(policyRequestUUID));
+        policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
+        String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
 
-        String rtnMsg = send(policyParameters, prop);
+        // 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 policyType = refProp.getStringValue("policy.ms.type");
         push(policyType, prop);
 
@@ -126,36 +167,56 @@ public class PolicyClient {
      * Perform send of policy.
      *
      * @param policyParameters
+     *            The PolicyParameters
      * @param prop
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @return THe response message of Policy
+     * @throws IOException
+     *             In case of issues with the Stream
+     * @throws PolicyEngineException
+     *             In case of issue when creating PolicyEngine class
      */
-    private String send(PolicyParameters policyParameters, ModelProperties prop) throws Exception {
-        PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+    protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix)
+            throws IOException, PolicyEngineException {
+        // Verify whether it is triggered by Validation Test button from UI
+        if (prop.isTest()) {
+            return "send not executed for test action";
+        }
+
+        PolicyEngine policyEngine = new PolicyEngine(
+                appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
 
         // API method to create or update Policy.
         PolicyChangeResponse response = null;
-        String responseMessage;
+        String responseMessage = "";
+        Date startTime = new Date();
         try {
-            if (prop.isCreateRequest()) {
+            List<Integer> versions = getVersions(policyNamePrefix, prop);
+            if (versions.isEmpty()) {
+                LoggingUtils.setTargetContext("Policy", "createPolicy");
                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
                 response = policyEngine.createPolicy(policyParameters);
                 responseMessage = response.getResponseMessage();
             } else {
+                LoggingUtils.setTargetContext("Policy", "updatePolicy");
                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
                 response = policyEngine.updatePolicy(policyParameters);
                 responseMessage = response.getResponseMessage();
             }
         } catch (Exception e) {
-            responseMessage = e.toString();
+            logger.error("Exception occurred during policy communnication", e);
         }
-        logger.info("response is " + responseMessage);
+        logger.info(LOG_POLICY_PREFIX + responseMessage);
+
+        LoggingUtils.setTimeContext(startTime, new Date());
 
         if (response != null && response.getResponseCode() == 200) {
             logger.info("Policy send successful");
+            metricsLogger.info("Policy send success");
         } else {
-            logger.warning("Policy send failed: " + responseMessage);
-            throw new Exception("Policy send failed: " + responseMessage);
+            logger.warn("Policy send failed: " + responseMessage);
+            metricsLogger.info("Policy send failure");
+            throw new BadRequestException("Policy send failed: " + responseMessage);
         }
 
         return responseMessage;
@@ -165,178 +226,233 @@ public class PolicyClient {
      * Format and send push of policy.
      *
      * @param policyType
+     *            The policy Type
      * @param prop
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @return The response message of policy
+     * @throws IOException
+     *             In case of issues with the stream
+     * @throws PolicyEngineException
+     *             In case of issues with the PolicyEngine creation
      */
-    private String push(String policyType, ModelProperties prop) throws Exception {
+    protected String push(String policyType, ModelProperties prop) throws PolicyEngineException, IOException {
+        // Verify whether it is triggered by Validation Test button from UI
+        if (prop.isTest()) {
+            return "push not executed for test action";
+        }
+
         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
 
-        //Parameter arguments
-        pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
+        // Parameter arguments
+        if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
+            pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
+        } else {
+            pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
+        }
+        logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
+
         pushPolicyParameters.setPolicyType(policyType);
-        //pushPolicyParameters.setPolicyScope(policyScope);
         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
         pushPolicyParameters.setRequestID(null);
 
-        PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+        PolicyEngine policyEngine = new PolicyEngine(
+                appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
 
         // API method to create or update Policy.
         PolicyChangeResponse response = null;
-        String responseMessage;
+        String responseMessage = "";
         try {
             logger.info("Attempting to push policy...");
             response = policyEngine.pushPolicy(pushPolicyParameters);
             responseMessage = response.getResponseMessage();
         } catch (Exception e) {
-            responseMessage = e.toString();
+            logger.error("Exception occurred during policy communnication", e);
         }
-        logger.info("response is " + responseMessage);
+        logger.info(LOG_POLICY_PREFIX + responseMessage);
 
         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
             logger.info("Policy push successful");
         } else {
-            logger.warning("Policy push failed: " + responseMessage);
-            throw new Exception("Policy push failed: " + responseMessage);
+            logger.warn("Policy push failed: " + responseMessage);
+            throw new BadRequestException("Policy push failed: " + responseMessage);
         }
 
         return responseMessage;
     }
 
     /**
-     * Use Get Config Policy API to retrieve the versions for a policy.
-     * Return versions in sorted order.
-     * Return empty list if none found.
+     * Use Get Config Policy API to retrieve the versions for a policy. Return
+     * versions in sorted order. Return empty list if none found.
      *
      * @param policyNamePrefix
+     *            The Policy Name Prefix
      * @param prop
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @return The response message from policy
+     * @throws IOException
+     *             In case of issues with the stream
+     * @throws PolicyEngineException
+     *             In case of issues with the PolicyEngine creation
      */
-    private List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws Exception {
+    protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop)
+            throws PolicyEngineException, IOException {
 
         ArrayList<Integer> versions = new ArrayList<>();
         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
-        String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
-        logger.info("policyName=" + policyName);
-        configRequestParameters.setPolicyName(policyName);
+        String policyName = "";
 
-        PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+        if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
+            policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
+        } else {
+            policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
+        }
 
-        Collection<PolicyConfig> response = policyEngine.getConfig(configRequestParameters);
+        logger.info("policyName=" + policyName);
+        configRequestParameters.setPolicyName(policyName);
 
-        Iterator<PolicyConfig> itrResp = response.iterator();
+        PolicyEngine policyEngine = new PolicyEngine(
+                appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
 
-        while (itrResp.hasNext()) {
-            PolicyConfig policyConfig = itrResp.next();
-            try {
-                Integer version = new Integer(policyConfig.getPolicyVersion());
-                versions.add(version);
-            } catch (Exception e) {
-                // just print warning - if n;o policies, version may be null
-                logger.warning("warning: failed to parse policyConfig.getPolicyVersion()=" + policyConfig.getPolicyVersion());
+        try {
+            Collection<PolicyConfig> response = policyEngine.getConfig(configRequestParameters);
+            Iterator<PolicyConfig> itrResp = response.iterator();
+
+            while (itrResp.hasNext()) {
+                PolicyConfig policyConfig = itrResp.next();
+                try {
+                    Integer version = new Integer(policyConfig.getPolicyVersion());
+                    versions.add(version);
+                } catch (Exception e) {
+                    // just print warning - if n;o policies, version may be null
+                    logger.warn("Failed to parse due to an exception policyConfig.getPolicyVersion()="
+                            + policyConfig.getPolicyVersion(), e);
+                }
             }
+            Collections.sort(versions);
+            logger.info("Policy versions.size()=" + versions.size());
+        } catch (Exception e) {
+            // just print warning - if no policy version found
+            logger.warn("warning: policy not found...policy name - " + policyName, e);
         }
-        Collections.sort(versions);
-        logger.info("versions.size()=" + versions.size());
 
         return versions;
     }
 
     /**
-     * Format and send delete Micro Service requests to Policy
+     * Format and send delete Micro Service requests to Policy.
      *
      * @param prop
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @return The response message from Policy
+     * @throws IOException
+     *             In case of issues with the stream
+     * @throws PolicyEngineException
+     *             In case of issues with the PolicyEngine creation
      */
-    public String deleteMicrosService(ModelProperties prop) throws Exception {
+    public String deleteMicrosService(ModelProperties prop) throws PolicyEngineException, IOException {
         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
-        return deletePolicy(policyNamePrefix, prop);
+        String policyType = refProp.getStringValue("policy.ms.type");
+        return deletePolicy(policyNamePrefix, prop, policyType);
     }
 
     /**
-     * Format and send delete BRMS requests to Policy
+     * Format and send delete BRMS requests to Policy.
      *
      * @param prop
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @return The response message from policy
+     * @throws IOException
+     *             In case of issues with the stream
+     * @throws PolicyEngineException
+     *             In case of issues with the PolicyEngine creation
      */
-    public String deleteBrms(ModelProperties prop) throws Exception {
+    public String deleteBrms(ModelProperties prop) throws PolicyEngineException, IOException {
         String policyNamePrefix = refProp.getStringValue("policy.op.policyNamePrefix");
-        return deletePolicy(policyNamePrefix, prop);
+        String policyType = refProp.getStringValue("policy.op.type");
+        return deletePolicy(policyNamePrefix, prop, policyType);
     }
 
     /**
-     * Format and send delete PAP and PDP requests to Policy
+     * Format and send delete PAP and PDP requests to Policy.
      *
      * @param policyNamePrefix
+     *            The String policyNamePrefix
      * @param prop
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @return The response message from policy
+     * @throws IOException
+     *             in case of issues with the Stream
+     * @throws PolicyEngineException
+     *             In case of issues with the PolicyEngine class creation
      */
-    private String deletePolicy(String policyNamePrefix, ModelProperties prop) throws Exception {
-        String responseMessage = null;
-
+    protected String deletePolicy(String policyNamePrefix, ModelProperties prop, String policyType)
+            throws PolicyEngineException, IOException {
         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
 
-        List<Integer> versions = getVersions(policyNamePrefix, prop);
-        if (versions.size() > 0) {
-            int maxVersion = Collections.max(versions);
-
-            // format delete all PAP request
-            deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndFullPolicyNameWithVersion(policyNamePrefix, maxVersion));
-            deletePolicyParameters.setPolicyComponent("PAP");
-            deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
-            String policyType = refProp.getStringValue("policy.ms.type");
-            deletePolicyParameters.setPolicyType(policyType);
-
-            //send delete request
-            responseMessage = sendDeletePolicy(deletePolicyParameters, prop);
+        if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
+            deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
+        } else {
+            deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
         }
+        logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
+        deletePolicyParameters.setPolicyComponent("PDP");
+        deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
+        deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
+        deletePolicyParameters.setPolicyType(policyType);
+        // send delete request
+        String responseMessage = sendDeletePolicy(deletePolicyParameters, prop);
 
-        for (Integer version : versions) {
-            // format delete all PDP request
-            deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndFullPolicyNameWithVersion(policyNamePrefix, version));
-            deletePolicyParameters.setPolicyComponent("PDP");
-            deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
-            //send delete request
-            responseMessage = responseMessage + "; " + sendDeletePolicy(deletePolicyParameters, prop);
-        }
+        logger.info("Deleting policy from PAP...");
+        deletePolicyParameters.setPolicyComponent("PAP");
+        deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
+
+        // send delete request
+        responseMessage = sendDeletePolicy(deletePolicyParameters, prop);
 
         return responseMessage;
     }
 
     /**
-     * Send delete request to Policy
+     * Send delete request to Policy.
      *
      * @param deletePolicyParameters
+     *            The DeletePolicyParameters
      * @param prop
-     * @return
-     * @throws Exception
+     *            The ModelProperties
+     * @return The response message from policy
+     * @throws IOException
+     *             In case of issues with the stream
+     * @throws PolicyEngineException
+     *             In case of issues with PolicyEngine class creation
      */
-    private String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) throws Exception {
-        PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+    protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop)
+            throws PolicyEngineException, IOException {
+        // Verify whether it is triggered by Validation Test button from UI
+        if (prop.isTest()) {
+            return "delete not executed for test action";
+        }
+        PolicyEngine policyEngine = new PolicyEngine(
+                appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
 
         // API method to create or update Policy.
         PolicyChangeResponse response = null;
-        String responseMessage;
+        String responseMessage = "";
         try {
             logger.info("Attempting to delete policy...");
             response = policyEngine.deletePolicy(deletePolicyParameters);
             responseMessage = response.getResponseMessage();
         } catch (Exception e) {
-            responseMessage = e.toString();
+            logger.error("Exception occurred during policy communnication", e);
         }
-        logger.info("response is " + responseMessage);
+        logger.info(LOG_POLICY_PREFIX + responseMessage);
 
         if (response != null && response.getResponseCode() == 200) {
             logger.info("Policy delete successful");
         } else {
-            logger.warning("Policy delete failed: " + responseMessage);
-            throw new Exception("Policy delete failed: " + responseMessage);
+            logger.warn("Policy delete failed: " + responseMessage);
+            throw new BadRequestException("Policy delete failed: " + responseMessage);
         }
 
         return responseMessage;
     }
-}
+}
\ No newline at end of file