Fixed various sonar identified code smells
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / policy / PolicyClient.java
index 58366d9..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
@@ -26,6 +28,11 @@ package org.onap.clamp.clds.client.req.policy;
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
 
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.Collection;
 import java.util.Date;
 import java.util.Map;
@@ -36,12 +43,17 @@ import javax.ws.rs.BadRequestException;
 import org.onap.clamp.clds.config.ClampProperties;
 import org.onap.clamp.clds.config.PolicyConfiguration;
 import org.onap.clamp.clds.exception.policy.PolicyClientException;
+import org.onap.clamp.clds.model.CldsToscaModel;
 import org.onap.clamp.clds.model.properties.ModelProperties;
+import org.onap.clamp.clds.model.properties.PolicyItem;
 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.DictionaryType;
+import org.onap.policy.api.ImportParameters;
+import org.onap.policy.api.ImportParameters.IMPORT_TYPE;
 import org.onap.policy.api.PolicyChangeResponse;
 import org.onap.policy.api.PolicyClass;
 import org.onap.policy.api.PolicyConfigException;
@@ -53,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;
 
@@ -64,20 +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";
-    @Autowired
-    protected ApplicationContext appContext;
+    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 ClampProperties refProp;
+    private ClampProperties refProp;
     @Autowired
     private PolicyConfiguration policyConfiguration;
 
@@ -85,33 +99,32 @@ public class PolicyClient {
      * Perform Guard policy type.
      *
      * @param attributes
-     *            A map of attributes
+     *        A map of attributes
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @param policyRequestUuid
-     *            PolicyRequest UUID
+     *        PolicyRequest UUID
      * @return The response message of policy
      */
     public String sendGuardPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
-        String policyRequestUuid) {
+        String policyRequestUuid, PolicyItem policyItem) {
         PolicyParameters policyParameters = new PolicyParameters();
         // Set Policy Type(Mandatory)
         policyParameters.setPolicyClass(PolicyClass.Decision);
         // Set Policy Name(Mandatory)
-        policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId()+"Guard");
+        policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId());
         // 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.setOnapName("PDPD");
-        policyParameters.setRuleProvider(RuleProvider.GUARD_YAML);
+        policyParameters.setRuleProvider(RuleProvider.valueOf(policyItem.getGuardPolicyType()));
         policyParameters.setAttributes(attributes);
         // 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 policyType = "Decision";
-        push(policyType, prop);
+
+        String rtnMsg = send(policyParameters, prop, null, null);
+        push(DictionaryType.Decision.toString(), prop, null);
         return rtnMsg;
     }
 
@@ -119,11 +132,11 @@ public class PolicyClient {
      * Perform BRMS policy type.
      *
      * @param attributes
-     *            A map of attributes
+     *        A map of attributes
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @param policyRequestUuid
-     *            PolicyRequest UUID
+     *        PolicyRequest UUID
      * @return The response message of policy
      */
     public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
@@ -141,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;
     }
 
@@ -151,11 +164,11 @@ public class PolicyClient {
      * Perform send of microservice policy in JSON.
      *
      * @param policyJson
-     *            The policy JSON
+     *        The policy JSON
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @param policyRequestUuid
-     *            The policy Request UUID
+     *        The policy Request UUID
      * @return The response message of policy
      */
     public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
@@ -171,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;
     }
 
@@ -181,14 +194,14 @@ public class PolicyClient {
      * Perform send of base policy in OTHER type.
      *
      * @param configBody
-     *            The config policy string body
+     *        The config policy string body
      * @param configPolicyName
-     *            The config policy name of the component that has been
-     *            pre-deployed in DCAE
+     *        The config policy name of the component that has been pre-deployed in
+     *        DCAE
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @param policyRequestUuid
-     *            The policy request UUID
+     *        The policy request UUID
      * @return The answer from policy call
      */
     public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
@@ -206,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;
     }
 
@@ -215,9 +229,9 @@ public class PolicyClient {
      * Perform send of Microservice policy in OTHER type.
      *
      * @param configBody
-     *            The config policy string body
+     *        The config policy string body
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @return The answer from policy call
      */
     public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
@@ -231,22 +245,23 @@ 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;
     }
 
     /**
-     * Perform send of policy.
+     * Perform send of Configuration or Decision policies.
      *
      * @param policyParameters
-     *            The PolicyParameters
+     *        The PolicyParameters
      * @param prop
-     *            The ModelProperties
+     *        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";
@@ -256,13 +271,15 @@ public class PolicyClient {
         String responseMessage = "";
         Date startTime = new Date();
         try {
-            if (!checkPolicyExists(policyNamePrefix, prop)) {
-                LoggingUtils.setTargetContext("Policy", "createPolicy");
+            if ((PolicyClass.Decision.equals(policyParameters.getPolicyClass()) && !checkDecisionPolicyExists(prop))
+                || (PolicyClass.Config.equals(policyParameters.getPolicyClass())
+                    && !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();
@@ -270,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());
@@ -292,23 +309,18 @@ public class PolicyClient {
      * Format and send push of policy.
      *
      * @param policyType
-     *            The policy Type
+     *        The policy Type
      * @param prop
-     *            The ModelProperties
+     *        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()) {
-            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"));
@@ -317,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) {
@@ -326,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)) {
@@ -343,37 +355,60 @@ public class PolicyClient {
         return responseMessage;
     }
 
+    /**
+     * Use list Decision policy to know if the decision policy exists.
+     *
+     * @param prop
+     *        The model properties
+     * @return true if it exists, false otherwise
+     */
+    protected boolean checkDecisionPolicyExists(ModelProperties prop) {
+        boolean policyexists = false;
+
+        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, null);
+            if (response != null) {
+                policyexists = true;
+            }
+        } catch (BadRequestException e) {
+            // just print warning - if no policy version found
+            logger.warn("Policy not found...policy name - " + prop.getPolicyScopeAndNameWithUniqueGuardId(), e);
+        }
+        return policyexists;
+    }
+
     /**
      * 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
+     *        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
+     *         In case of issues with policy engine
      */
-    protected boolean checkPolicyExists(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
+    protected boolean checkPolicyExists(ModelProperties prop, String policyPrefix, String policyNameWithPrefix) {
         boolean policyexists = false;
-        ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
         String policyName = "";
-        if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
-            policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
-        } else {
-            policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
-        }
-        logger.info("Search in Policy Engine for policyName=" + policyName);
-        configRequestParameters.setPolicyName(policyName);
         try {
+            policyName = selectRightPolicyNameWithPrefix(prop, policyPrefix, policyNameWithPrefix);
+            logger.info("Search in Policy Engine for policyName=" + policyName);
+
+            ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
+            configRequestParameters.setPolicyName(policyName);
             Collection<String> response = getPolicyEngine().listConfig(configRequestParameters);
             if (response != null && !response.isEmpty() && !response.contains("Policy Name: null")) {
                 policyexists = true;
             }
-        } catch (PolicyConfigException e) {
+        } catch (PolicyConfigException e1) {
             // just print warning - if no policy version found
-            logger.warn("policy not found...policy name - " + policyName, e);
+            logger.warn("Policy not found...policy name - " + policyName, e1);
         }
         return policyexists;
     }
@@ -398,52 +433,41 @@ public class PolicyClient {
      * Format and send delete Micro Service requests to Policy.
      *
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @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);
     }
 
     /**
      * This method delete the Base policy.
      *
      * @param prop
-     *            The model Properties
+     *        The model Properties
      * @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);
     }
 
     /**
      * Format and send delete Guard requests to Policy.
      *
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @return The response message from policy
      */
     public String deleteGuard(ModelProperties prop) {
         String deletePolicyResponse = "";
         try {
-            String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
-            if (checkPolicyExists(policyNamePrefix, prop)) {
-                deletePolicyResponse = deletePolicy(prop, "Decision");
+
+            if (checkDecisionPolicyExists(prop)) {
+                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;
     }
@@ -452,46 +476,89 @@ public class PolicyClient {
      * Format and send delete BRMS requests to Policy.
      *
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @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;
+        }
+    }
+
+    /**
+     * Method to return correct policy name with prefix.
+     *
+     * @param prop
+     *        The ModelProperties
+     * @param policyPrefix
+     *        Policy Prefix
+     * @param policyNameWithPrefix
+     *        Policy Name With Prefix
+     * @return The policy name with the prefix
+     */
+    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 {
+                return prop.getCurrentPolicyScopeAndFullPolicyName(policyPrefix);
+            }
+        } else {
+            return policyNameWithPrefix;
+        }
+    }
+
     /**
      * Format and send delete PAP and PDP requests to Policy.
      *
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
+     * @param policyType
+     *        The policyType "Decision" or
      * @return The response message from policy
      */
-    protected String deletePolicy(ModelProperties prop, String policyType) {
+    protected String deletePolicy(ModelProperties prop, String policyType, String policyName) {
         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
-        if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
-            deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
-        } else {
-            deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
-        }
+        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");
         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
         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
@@ -503,9 +570,9 @@ public class PolicyClient {
      * Send delete request to Policy.
      *
      * @param deletePolicyParameters
-     *            The DeletePolicyParameters
+     *        The DeletePolicyParameters
      * @param prop
-     *            The ModelProperties
+     *        The ModelProperties
      * @return The response message from policy
      */
     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
@@ -532,4 +599,83 @@ public class PolicyClient {
         }
         return responseMessage;
     }
+
+    /**
+     * Create a temp Tosca model file and perform import model to Policy Engine.
+     *
+     * @param cldsToscaModel
+     *        Policy model details
+     * @return The response message from policy
+     */
+    public String importToscaModel(CldsToscaModel cldsToscaModel) {
+        String filePath = "";
+        try {
+            String clampToscaPath = refProp.getStringValue(TOSCA_FILE_TEMP_PATH);
+            filePath = buildFilePathForToscaFile(clampToscaPath, cldsToscaModel.getToscaModelName());
+            logger.info("Writing Tosca model : " + filePath);
+            Path path = Paths.get(filePath);
+            Files.createDirectories(path.getParent());
+            // Create or Ovewrite an existing the file
+            try (OutputStream out = Files.newOutputStream(path)) {
+                out.write(cldsToscaModel.getToscaModelYaml().getBytes(), 0,
+                    cldsToscaModel.getToscaModelYaml().getBytes().length);
+            }
+        } catch (IOException e) {
+            logger.error("Exception caught when attempting to write Tosca files to disk", e);
+            throw new PolicyClientException("Exception caught when attempting to write Tosca files to disk", e);
+        }
+
+        ImportParameters importParameters = new ImportParameters();
+        importParameters.setImportParameters(cldsToscaModel.getToscaModelName(), cldsToscaModel.getToscaModelName(),
+            null, filePath, IMPORT_TYPE.MICROSERVICE, String.valueOf(cldsToscaModel.getVersion()));
+        return importModel(importParameters);
+    }
+
+    /**
+     * Import the model.
+     * @param importParameters
+     *        The ImportParameters
+     * @return The response message from policy
+     */
+    private String importModel(ImportParameters importParameters) {
+        PolicyChangeResponse response = null;
+        String responseMessage = "";
+
+        try {
+            logger.info("Attempting to import tosca policy model for action=" + importParameters.getFilePath());
+            response = getPolicyEngine().policyEngineImport(importParameters);
+            if (response != null) {
+                responseMessage = response.getResponseMessage();
+            }
+        } catch (Exception e) {
+            LoggingUtils.setResponseContext("900", "Policy Model import failed", this.getClass().getName());
+            LoggingUtils.setErrorContext("900", "Policy Model import error");
+            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)) {
+            LoggingUtils.setResponseContext("0", "Policy Model import success", this.getClass().getName());
+            logger.info("Policy import model successful");
+            metricsLogger.info("Policy import model success");
+        } else {
+            LoggingUtils.setResponseContext("900", "Policy import model failed", this.getClass().getName());
+            logger.warn("Policy import model failed: " + responseMessage);
+            metricsLogger.info("Policy import model failure");
+            throw new BadRequestException("Policy import model failed: " + responseMessage);
+        }
+        return responseMessage;
+    }
+
+    /**
+     * Build file path for tosca file.
+     * @param clampToscaPath
+     *        Temp directory path for writing tosca files
+     * @param toscaModelName
+     *        Tosca Model Name
+     * @return File Path on the system
+     */
+    private String buildFilePathForToscaFile(String clampToscaPath, String toscaModelName) {
+        return clampToscaPath + "/" + toscaModelName + ".yml";
+    }
 }
\ No newline at end of file