9f25ba9fd063cfa26c8bf877c30bd27cb187b07f
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / policy / PolicyClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  *
22  */
23
24 package org.onap.clamp.clds.client.req.policy;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.io.IOException;
30 import java.io.OutputStream;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.util.Collection;
35 import java.util.Date;
36 import java.util.Map;
37 import java.util.UUID;
38
39 import javax.ws.rs.BadRequestException;
40
41 import org.onap.clamp.clds.config.ClampProperties;
42 import org.onap.clamp.clds.config.PolicyConfiguration;
43 import org.onap.clamp.clds.exception.policy.PolicyClientException;
44 import org.onap.clamp.clds.model.CldsToscaModel;
45 import org.onap.clamp.clds.model.properties.ModelProperties;
46 import org.onap.clamp.clds.model.properties.PolicyItem;
47 import org.onap.clamp.clds.util.LoggingUtils;
48 import org.onap.policy.api.AttributeType;
49 import org.onap.policy.api.ConfigRequestParameters;
50 import org.onap.policy.api.DeletePolicyCondition;
51 import org.onap.policy.api.DeletePolicyParameters;
52 import org.onap.policy.api.DictionaryType;
53 import org.onap.policy.api.ImportParameters;
54 import org.onap.policy.api.ImportParameters.IMPORT_TYPE;
55 import org.onap.policy.api.PolicyChangeResponse;
56 import org.onap.policy.api.PolicyClass;
57 import org.onap.policy.api.PolicyConfigException;
58 import org.onap.policy.api.PolicyConfigType;
59 import org.onap.policy.api.PolicyEngine;
60 import org.onap.policy.api.PolicyEngineException;
61 import org.onap.policy.api.PolicyParameters;
62 import org.onap.policy.api.PolicyType;
63 import org.onap.policy.api.PushPolicyParameters;
64 import org.onap.policy.api.RuleProvider;
65 import org.springframework.beans.factory.annotation.Autowired;
66 import org.springframework.context.ApplicationContext;
67 import org.springframework.context.annotation.Primary;
68 import org.springframework.stereotype.Component;
69
70 /**
71  * Policy utility methods - specifically, send the policy.
72  */
73 @Component
74 @Primary
75 public class PolicyClient {
76
77     protected PolicyEngine policyEngine;
78     protected static final String LOG_POLICY_PREFIX = "Response is ";
79     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
80     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
81     public static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
82     public static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
83     public static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix";
84     public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix";
85     public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix";
86     public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type";
87     public static final String POLICY_GUARD_SUFFIX = "_Guard";
88     public static final String TOSCA_FILE_TEMP_PATH = "tosca.filePath";
89
90     @Autowired
91     protected ApplicationContext appContext;
92     @Autowired
93     protected ClampProperties refProp;
94     @Autowired
95     private PolicyConfiguration policyConfiguration;
96
97     /**
98      * Perform Guard policy type.
99      *
100      * @param attributes
101      *        A map of attributes
102      * @param prop
103      *        The ModelProperties
104      * @param policyRequestUuid
105      *        PolicyRequest UUID
106      * @return The response message of policy
107      */
108     public String sendGuardPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
109         String policyRequestUuid, PolicyItem policyItem) {
110         PolicyParameters policyParameters = new PolicyParameters();
111         // Set Policy Type(Mandatory)
112         policyParameters.setPolicyClass(PolicyClass.Decision);
113         // Set Policy Name(Mandatory)
114         policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId());
115         // documentation says this is options, but when tested, got the
116         // following failure: java.lang.Exception: Policy send failed: PE300 -
117         // Data Issue: No policyDescription given.
118         policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
119         policyParameters.setOnapName("PDPD");
120         policyParameters.setRuleProvider(RuleProvider.valueOf(policyItem.getGuardPolicyType()));
121         policyParameters.setAttributes(attributes);
122         // Set a random UUID(Mandatory)
123         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
124
125         String rtnMsg = send(policyParameters, prop, null);
126         push(DictionaryType.Decision.toString(), prop);
127         return rtnMsg;
128     }
129
130     /**
131      * Perform BRMS policy type.
132      *
133      * @param attributes
134      *        A map of attributes
135      * @param prop
136      *        The ModelProperties
137      * @param policyRequestUuid
138      *        PolicyRequest UUID
139      * @return The response message of policy
140      */
141     public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
142         String policyRequestUuid) {
143         PolicyParameters policyParameters = new PolicyParameters();
144         // Set Policy Type(Mandatory)
145         policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
146         // Set Policy Name(Mandatory)
147         policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
148         // documentation says this is options, but when tested, got the
149         // following failure: java.lang.Exception: Policy send failed: PE300 -
150         // Data Issue: No policyDescription given.
151         policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
152         policyParameters.setAttributes(attributes);
153         // Set a random UUID(Mandatory)
154         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
155         String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
156         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
157         String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
158         push(policyType, prop);
159         return rtnMsg;
160     }
161
162     /**
163      * Perform send of microservice policy in JSON.
164      *
165      * @param policyJson
166      *        The policy JSON
167      * @param prop
168      *        The ModelProperties
169      * @param policyRequestUuid
170      *        The policy Request UUID
171      * @return The response message of policy
172      */
173     public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
174         PolicyParameters policyParameters = new PolicyParameters();
175         // Set Policy Type
176         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
177         policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
178         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
179         policyParameters.setConfigBody(policyJson);
180         policyParameters.setConfigBodyType(PolicyType.JSON);
181         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
182         String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
183         // Adding this line to clear the policy id from policy name while
184         // pushing to policy engine
185         prop.setPolicyUniqueId("");
186         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
187         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
188         push(policyType, prop);
189         return rtnMsg;
190     }
191
192     /**
193      * Perform send of base policy in OTHER type.
194      *
195      * @param configBody
196      *        The config policy string body
197      * @param configPolicyName
198      *        The config policy name of the component that has been pre-deployed in
199      *        DCAE
200      * @param prop
201      *        The ModelProperties
202      * @param policyRequestUuid
203      *        The policy request UUID
204      * @return The answer from policy call
205      */
206     public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
207         String policyRequestUuid) {
208         PolicyParameters policyParameters = new PolicyParameters();
209         // Set Policy Type
210         policyParameters.setPolicyConfigType(PolicyConfigType.Base);
211         policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
212         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
213         policyParameters.setConfigBody(configBody);
214         policyParameters.setConfigBodyType(PolicyType.OTHER);
215         policyParameters.setConfigName("HolmesPolicy");
216         policyParameters.setPolicyName(configPolicyName);
217         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
218         // Adding this line to clear the policy id from policy name while
219         // pushing to policy engine
220         prop.setPolicyUniqueId("");
221         String rtnMsg = send(policyParameters, prop, refProp.getStringValue(POLICY_BASENAME_PREFIX_PROPERTY_NAME));
222         push(PolicyConfigType.Base.toString(), prop);
223         return rtnMsg;
224     }
225
226     /**
227      * Perform send of Microservice policy in OTHER type.
228      *
229      * @param configBody
230      *        The config policy string body
231      * @param prop
232      *        The ModelProperties
233      * @return The answer from policy call
234      */
235     public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
236         PolicyParameters policyParameters = new PolicyParameters();
237         // Set Policy Type
238         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
239         policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
240         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
241         policyParameters.setConfigBody(configBody);
242         String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
243         // Adding this line to clear the policy id from policy name while
244         // pushing to policy engine
245         prop.setPolicyUniqueId("");
246         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
247         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
248         push(policyType, prop);
249         return rtnMsg;
250     }
251
252     /**
253      * Perform send of Configuration or Decision policies.
254      *
255      * @param policyParameters
256      *        The PolicyParameters
257      * @param prop
258      *        The ModelProperties
259      * @return The response message of Policy
260      */
261     protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
262         // Verify whether it is triggered by Validation Test button from UI
263         if (prop.isTestOnly()) {
264             return "send not executed for test action";
265         }
266         // API method to create or update Policy.
267         PolicyChangeResponse response = null;
268         String responseMessage = "";
269         Date startTime = new Date();
270         try {
271             if ((PolicyClass.Decision.equals(policyParameters.getPolicyClass()) && !checkDecisionPolicyExists(prop))
272                 || (PolicyClass.Config.equals(policyParameters.getPolicyClass())
273                     && !checkPolicyExists(policyNamePrefix, prop))) {
274                 LoggingUtils.setTargetContext("Policy", "createPolicy");
275                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
276                 response = getPolicyEngine().createPolicy(policyParameters);
277                 responseMessage = response.getResponseMessage();
278             } else {
279                 LoggingUtils.setTargetContext("Policy", "updatePolicy");
280                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
281                 response = getPolicyEngine().updatePolicy(policyParameters);
282                 responseMessage = response.getResponseMessage();
283             }
284         } catch (Exception e) {
285             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
286             LoggingUtils.setErrorContext("900", "Policy send error");
287             logger.error("Exception occurred during policy communication", e);
288             throw new PolicyClientException("Exception while communicating with Policy", e);
289         }
290         logger.info(LOG_POLICY_PREFIX + responseMessage);
291         LoggingUtils.setTimeContext(startTime, new Date());
292         if (response.getResponseCode() == 200) {
293             LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
294             logger.info("Policy send successful");
295             metricsLogger.info("Policy send success");
296         } else {
297             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
298             logger.warn("Policy send failed: " + responseMessage);
299             metricsLogger.info("Policy send failure");
300             throw new BadRequestException("Policy send failed: " + responseMessage);
301         }
302         return responseMessage;
303     }
304
305     /**
306      * Format and send push of policy.
307      *
308      * @param policyType
309      *        The policy Type
310      * @param prop
311      *        The ModelProperties
312      * @return The response message of policy
313      */
314     protected String push(String policyType, ModelProperties prop) {
315         // Verify whether it is triggered by Validation Test button from UI
316         if (prop.isTestOnly()) {
317             return "push not executed for test action";
318         }
319         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
320         // Parameter arguments
321         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
322             if (DictionaryType.Decision.toString().equals(policyType)) {
323                 pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId());
324             } else {
325                 pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
326             }
327         } else {
328             pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
329         }
330         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
331         pushPolicyParameters.setPolicyType(policyType);
332         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
333         pushPolicyParameters.setRequestID(null);
334         // API method to create or update Policy.
335         PolicyChangeResponse response;
336         String responseMessage = "";
337         try {
338             LoggingUtils.setTargetContext("Policy", "pushPolicy");
339             logger.info("Attempting to push policy...");
340             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
341             if (response != null) {
342                 responseMessage = response.getResponseMessage();
343             }
344         } catch (Exception e) {
345             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
346             LoggingUtils.setErrorContext("900", "Policy push error");
347             logger.error("Exception occurred during policy communication", e);
348             throw new PolicyClientException("Exception while communicating with Policy", e);
349         }
350         logger.info(LOG_POLICY_PREFIX + responseMessage);
351         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
352             LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
353             logger.info("Policy push successful");
354             metricsLogger.info("Policy push success");
355         } else {
356             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
357             logger.warn("Policy push failed: " + responseMessage);
358             metricsLogger.info("Policy push failure");
359             throw new BadRequestException("Policy push failed: " + responseMessage);
360         }
361         return responseMessage;
362     }
363
364     /**
365      * Use list Decision policy to know if the decision policy exists.
366      *
367      * @param prop
368      *        The model properties
369      * @return true if it exists, false otherwise
370      */
371     protected boolean checkDecisionPolicyExists(ModelProperties prop) {
372         boolean policyexists = false;
373
374         logger.info("Search in Policy Engine for DecisionpolicyName=" + prop.getPolicyScopeAndNameWithUniqueGuardId());
375         try {
376             // No other choice than pushing to see if it exists or not
377             String response = push(DictionaryType.Decision.toString(), prop);
378             if (response != null) {
379                 policyexists = true;
380             }
381         } catch (BadRequestException e) {
382             // just print warning - if no policy version found
383             logger.warn("Policy not found...policy name - " + prop.getPolicyScopeAndNameWithUniqueGuardId(), e);
384         }
385         return policyexists;
386     }
387
388     /**
389      * Use list Policy API to retrieve the policy. Return true if policy exists
390      * otherwise return false.
391      *
392      * @param policyNamePrefix
393      *        The Policy Name Prefix
394      * @param prop
395      *        The ModelProperties
396      * @return The response message from policy
397      * @throws PolicyConfigException
398      *         In case of issues with policy engine
399      */
400     protected boolean checkPolicyExists(String policyNamePrefix, ModelProperties prop) {
401         boolean policyexists = false;
402         String policyName = "";
403         try {
404
405             if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
406                 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_"
407                     + prop.getPolicyUniqueId();
408             } else {
409                 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
410             }
411             logger.info("Search in Policy Engine for policyName=" + policyName);
412
413             ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
414             configRequestParameters.setPolicyName(policyName);
415             Collection<String> response = getPolicyEngine().listConfig(configRequestParameters);
416             if (response != null && !response.isEmpty() && !response.contains("Policy Name: null")) {
417                 policyexists = true;
418             }
419         } catch (PolicyConfigException e1) {
420             // just print warning - if no policy version found
421             logger.warn("Policy not found...policy name - " + policyName, e1);
422         }
423         return policyexists;
424     }
425
426     /**
427      * This method create a new policy engine.
428      *
429      * @return A new policy engine
430      */
431     private synchronized PolicyEngine getPolicyEngine() {
432         try {
433             if (policyEngine == null) {
434                 policyEngine = new PolicyEngine(policyConfiguration.getProperties());
435             }
436         } catch (PolicyEngineException e) {
437             throw new PolicyClientException("Exception when creating a new policy engine", e);
438         }
439         return policyEngine;
440     }
441
442     /**
443      * Format and send delete Micro Service requests to Policy.
444      *
445      * @param prop
446      *        The ModelProperties
447      * @return The response message from Policy
448      */
449     public String deleteMicrosService(ModelProperties prop) {
450         String deletePolicyResponse = "";
451         try {
452             String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
453             if (checkPolicyExists(policyNamePrefix, prop)) {
454                 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
455                 deletePolicyResponse = deletePolicy(prop, policyType);
456             }
457         } catch (Exception e) {
458             logger.error("Exception occurred during policy communication", e);
459             throw new PolicyClientException("Exception while communicating with Policy", e);
460         }
461         return deletePolicyResponse;
462     }
463
464     /**
465      * This method delete the Base policy.
466      *
467      * @param prop
468      *        The model Properties
469      * @return A string with the answer from policy
470      */
471     public String deleteBasePolicy(ModelProperties prop) {
472         return deletePolicy(prop, PolicyConfigType.Base.toString());
473     }
474
475     /**
476      * Format and send delete Guard requests to Policy.
477      *
478      * @param prop
479      *        The ModelProperties
480      * @return The response message from policy
481      */
482     public String deleteGuard(ModelProperties prop) {
483         String deletePolicyResponse = "";
484         try {
485
486             if (checkDecisionPolicyExists(prop)) {
487                 deletePolicyResponse = deletePolicy(prop, DictionaryType.Decision.toString());
488             }
489         } catch (Exception e) {
490             logger.error("Exception occurred during policy communication", e);
491             throw new PolicyClientException("Exception while communicating with Policy", e);
492         }
493         return deletePolicyResponse;
494     }
495
496     /**
497      * Format and send delete BRMS requests to Policy.
498      *
499      * @param prop
500      *        The ModelProperties
501      * @return The response message from policy
502      */
503     public String deleteBrms(ModelProperties prop) {
504         String deletePolicyResponse = "";
505         try {
506             String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
507             if (checkPolicyExists(policyNamePrefix, prop)) {
508                 String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
509                 deletePolicyResponse = deletePolicy(prop, policyType);
510             }
511         } catch (Exception e) {
512             logger.error("Exception occurred during policy communication", e);
513             throw new PolicyClientException("Exception while communicating with Policy", e);
514         }
515         return deletePolicyResponse;
516     }
517
518     /**
519      * Format and send delete PAP and PDP requests to Policy.
520      *
521      * @param prop
522      *        The ModelProperties
523      * @return The response message from policy
524      */
525     protected String deletePolicy(ModelProperties prop, String policyType) {
526         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
527         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
528             if (DictionaryType.Decision.toString().equals(policyType)) {
529                 deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId());
530             } else {
531                 deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
532             }
533         } else {
534             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
535         }
536         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
537         logger.info("Deleting policy from PDP...");
538         deletePolicyParameters.setPolicyComponent("PDP");
539         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
540         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
541         deletePolicyParameters.setPolicyType(policyType);
542         // send delete request
543         StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
544         logger.info("Deleting policy from PAP...");
545         deletePolicyParameters.setPolicyComponent("PAP");
546         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
547         // send delete request
548         responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
549         return responseMessage.toString();
550     }
551
552     /**
553      * Send delete request to Policy.
554      *
555      * @param deletePolicyParameters
556      *        The DeletePolicyParameters
557      * @param prop
558      *        The ModelProperties
559      * @return The response message from policy
560      */
561     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
562         // Verify whether it is triggered by Validation Test button from UI
563         if (prop.isTestOnly()) {
564             return "delete not executed for test action";
565         }
566         // API method to create or update Policy.
567         PolicyChangeResponse response = null;
568         String responseMessage = "";
569         try {
570             logger.info("Attempting to delete policy...");
571             response = getPolicyEngine().deletePolicy(deletePolicyParameters);
572             responseMessage = response.getResponseMessage();
573         } catch (Exception e) {
574             logger.error("Exception occurred during policy communnication", e);
575         }
576         logger.info(LOG_POLICY_PREFIX + responseMessage);
577         if (response != null && response.getResponseCode() == 200) {
578             logger.info("Policy delete successful");
579         } else {
580             logger.warn("Policy delete failed: " + responseMessage);
581             throw new BadRequestException("Policy delete failed: " + responseMessage);
582         }
583         return responseMessage;
584     }
585
586     /**
587      * Create a temp Tosca model file and perform import model to Policy Engine
588      *
589      * @param cldsToscaModel
590      *        Policy model details
591      * @return The response message from policy
592      */
593     public String importToscaModel(CldsToscaModel cldsToscaModel) {
594         String filePath = "";
595         try {
596             String clampToscaPath = refProp.getStringValue(TOSCA_FILE_TEMP_PATH);
597             filePath = buildFilePathForToscaFile(clampToscaPath, cldsToscaModel.getToscaModelName());
598             logger.info("Writing Tosca model : " + filePath);
599             Path path = Paths.get(filePath);
600             Files.createDirectories(path.getParent());
601             // Create or Ovewrite an existing the file
602             try (OutputStream out = Files.newOutputStream(path)) {
603                 out.write(cldsToscaModel.getToscaModelYaml().getBytes(), 0,
604                     cldsToscaModel.getToscaModelYaml().getBytes().length);
605             }
606         } catch (IOException e) {
607             logger.error("Exception caught when attempting to write Tosca files to disk", e);
608             throw new PolicyClientException("Exception caught when attempting to write Tosca files to disk", e);
609         }
610
611         ImportParameters importParameters = new ImportParameters();
612         importParameters.setImportParameters(cldsToscaModel.getToscaModelName(), cldsToscaModel.getToscaModelName(),
613             null, filePath, IMPORT_TYPE.MICROSERVICE, String.valueOf(cldsToscaModel.getVersion()));
614         return importModel(importParameters);
615     }
616
617     /**
618      * @param importParameters
619      *        The ImportParameters
620      * @return The response message from policy
621      */
622     protected String importModel(ImportParameters importParameters) {
623         PolicyChangeResponse response = null;
624         String responseMessage = "";
625
626         try {
627             logger.info("Attempting to import tosca policy model for action=" + importParameters.getFilePath());
628             response = getPolicyEngine().policyEngineImport(importParameters);
629             if (response != null) {
630                 responseMessage = response.getResponseMessage();
631             }
632         } catch (Exception e) {
633             LoggingUtils.setResponseContext("900", "Policy Model import failed", this.getClass().getName());
634             LoggingUtils.setErrorContext("900", "Policy Model import error");
635             logger.error("Exception occurred during policy communication", e);
636             throw new PolicyClientException("Exception while communicating with Policy", e);
637         }
638         logger.info(LOG_POLICY_PREFIX + responseMessage);
639         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
640             LoggingUtils.setResponseContext("0", "Policy Model import success", this.getClass().getName());
641             logger.info("Policy import model successful");
642             metricsLogger.info("Policy import model success");
643         } else {
644             LoggingUtils.setResponseContext("900", "Policy import model failed", this.getClass().getName());
645             logger.warn("Policy import model failed: " + responseMessage);
646             metricsLogger.info("Policy import model failure");
647             throw new BadRequestException("Policy import model failed: " + responseMessage);
648         }
649         return responseMessage;
650     }
651
652     /**
653      * @param clampToscaPath
654      *        Temp directory path for writing tosca files
655      * @param toscaModelName
656      *        Tosca Model Name
657      * @return File Path on the system
658      */
659     private String buildFilePathForToscaFile(String clampToscaPath, String toscaModelName) {
660         return clampToscaPath + "/" + toscaModelName + ".yml";
661     }
662 }