Add dynamic port
[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, null);
126         push(DictionaryType.Decision.toString(), prop, null);
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, null);
157         String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
158         push(policyType, prop, null);
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, null);
187         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
188         push(policyType, prop, null);
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             null);
223         push(PolicyConfigType.Base.toString(), prop, null);
224         return rtnMsg;
225     }
226
227     /**
228      * Perform send of Microservice policy in OTHER type.
229      *
230      * @param configBody
231      *        The config policy string body
232      * @param prop
233      *        The ModelProperties
234      * @return The answer from policy call
235      */
236     public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
237         PolicyParameters policyParameters = new PolicyParameters();
238         // Set Policy Type
239         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
240         policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
241         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
242         policyParameters.setConfigBody(configBody);
243         String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
244         // Adding this line to clear the policy id from policy name while
245         // pushing to policy engine
246         prop.setPolicyUniqueId("");
247         String rtnMsg = send(policyParameters, prop, policyNamePrefix, null);
248         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
249         push(policyType, prop, null);
250         return rtnMsg;
251     }
252
253     /**
254      * Perform send of Configuration or Decision policies.
255      *
256      * @param policyParameters
257      *        The PolicyParameters
258      * @param prop
259      *        The ModelProperties
260      * @return The response message of Policy
261      */
262     protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyPrefix,
263         String policyNameWithPrefix) {
264         // Verify whether it is triggered by Validation Test button from UI
265         if (prop.isTestOnly()) {
266             return "send not executed for test action";
267         }
268         // API method to create or update Policy.
269         PolicyChangeResponse response = null;
270         String responseMessage = "";
271         Date startTime = new Date();
272         try {
273             if ((PolicyClass.Decision.equals(policyParameters.getPolicyClass()) && !checkDecisionPolicyExists(prop))
274                 || (PolicyClass.Config.equals(policyParameters.getPolicyClass())
275                     && !checkPolicyExists(prop, policyPrefix, policyNameWithPrefix))) {
276                 LoggingUtils.setTargetContext("Policy", "createPolicy");
277                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
278                 response = getPolicyEngine().createPolicy(policyParameters);
279                 responseMessage = response.getResponseMessage();
280             } else {
281                 LoggingUtils.setTargetContext("Policy", "updatePolicy");
282                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
283                 response = getPolicyEngine().updatePolicy(policyParameters);
284                 responseMessage = response.getResponseMessage();
285             }
286         } catch (Exception e) {
287             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
288             LoggingUtils.setErrorContext("900", "Policy send error");
289             logger.error("Exception occurred during policy communication", e);
290             throw new PolicyClientException("Exception while communicating with Policy", e);
291         }
292         logger.info(LOG_POLICY_PREFIX + responseMessage);
293         LoggingUtils.setTimeContext(startTime, new Date());
294         if (response.getResponseCode() == 200) {
295             LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
296             logger.info("Policy send successful");
297             metricsLogger.info("Policy send success");
298         } else {
299             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
300             logger.warn("Policy send failed: " + responseMessage);
301             metricsLogger.info("Policy send failure");
302             throw new BadRequestException("Policy send failed: " + responseMessage);
303         }
304         return responseMessage;
305     }
306
307     /**
308      * Format and send push of policy.
309      *
310      * @param policyType
311      *        The policy Type
312      * @param prop
313      *        The ModelProperties
314      * @return The response message of policy
315      */
316     protected String push(String policyType, ModelProperties prop, String policyName) {
317         // Verify whether it is triggered by Validation Test button from UI
318         if (prop.isTestOnly()) {
319             return "push not executed for test action";
320         }
321         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
322         pushPolicyParameters.setPolicyName(selectRightPolicyName(prop, policyType, policyName));
323         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
324         pushPolicyParameters.setPolicyType(policyType);
325         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
326         pushPolicyParameters.setRequestID(null);
327         // API method to create or update Policy.
328         PolicyChangeResponse response;
329         String responseMessage = "";
330         try {
331             LoggingUtils.setTargetContext("Policy", "pushPolicy");
332             logger.info("Attempting to push policy...");
333             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
334             if (response != null) {
335                 responseMessage = response.getResponseMessage();
336             }
337         } catch (Exception e) {
338             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
339             LoggingUtils.setErrorContext("900", "Policy push error");
340             logger.error("Exception occurred during policy communication", e);
341             throw new PolicyClientException("Exception while communicating with Policy", e);
342         }
343         logger.info(LOG_POLICY_PREFIX + responseMessage);
344         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
345             LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
346             logger.info("Policy push successful");
347             metricsLogger.info("Policy push success");
348         } else {
349             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
350             logger.warn("Policy push failed: " + responseMessage);
351             metricsLogger.info("Policy push failure");
352             throw new BadRequestException("Policy push failed: " + responseMessage);
353         }
354         return responseMessage;
355     }
356
357     /**
358      * Use list Decision policy to know if the decision policy exists.
359      *
360      * @param prop
361      *        The model properties
362      * @return true if it exists, false otherwise
363      */
364     protected boolean checkDecisionPolicyExists(ModelProperties prop) {
365         boolean policyexists = false;
366
367         logger.info("Search in Policy Engine for DecisionpolicyName=" + prop.getPolicyScopeAndNameWithUniqueGuardId());
368         try {
369             // No other choice than pushing to see if it exists or not
370             String response = push(DictionaryType.Decision.toString(), prop, null);
371             if (response != null) {
372                 policyexists = true;
373             }
374         } catch (BadRequestException e) {
375             // just print warning - if no policy version found
376             logger.warn("Policy not found...policy name - " + prop.getPolicyScopeAndNameWithUniqueGuardId(), e);
377         }
378         return policyexists;
379     }
380
381     /**
382      * Use list Policy API to retrieve the policy. Return true if policy exists
383      * otherwise return false.
384      *
385      * @param policyNamePrefix
386      *        The Policy Name Prefix
387      * @param prop
388      *        The ModelProperties
389      * @return The response message from policy
390      * @throws PolicyConfigException
391      *         In case of issues with policy engine
392      */
393     protected boolean checkPolicyExists(ModelProperties prop, String policyPrefix, String policyNameWithPrefix) {
394         boolean policyexists = false;
395         String policyName = "";
396         try {
397             policyName = selectRightPolicyNameWithPrefix(prop, policyPrefix, policyNameWithPrefix);
398             logger.info("Search in Policy Engine for policyName=" + policyName);
399
400             ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
401             configRequestParameters.setPolicyName(policyName);
402             Collection<String> response = getPolicyEngine().listConfig(configRequestParameters);
403             if (response != null && !response.isEmpty() && !response.contains("Policy Name: null")) {
404                 policyexists = true;
405             }
406         } catch (PolicyConfigException e1) {
407             // just print warning - if no policy version found
408             logger.warn("Policy not found...policy name - " + policyName, e1);
409         }
410         return policyexists;
411     }
412
413     /**
414      * This method create a new policy engine.
415      *
416      * @return A new policy engine
417      */
418     private synchronized PolicyEngine getPolicyEngine() {
419         try {
420             if (policyEngine == null) {
421                 policyEngine = new PolicyEngine(policyConfiguration.getProperties());
422             }
423         } catch (PolicyEngineException e) {
424             throw new PolicyClientException("Exception when creating a new policy engine", e);
425         }
426         return policyEngine;
427     }
428
429     /**
430      * Format and send delete Micro Service requests to Policy.
431      *
432      * @param prop
433      *        The ModelProperties
434      * @return The response message from Policy
435      */
436     public String deleteMicrosService(ModelProperties prop) {
437         String deletePolicyResponse = "";
438         try {
439             String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
440             if (checkPolicyExists(prop, policyNamePrefix, null)) {
441                 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
442                 deletePolicyResponse = deletePolicy(prop, policyType, null);
443             }
444         } catch (Exception e) {
445             logger.error("Exception occurred during policy communication", e);
446             throw new PolicyClientException("Exception while communicating with Policy", e);
447         }
448         return deletePolicyResponse;
449     }
450
451     /**
452      * This method delete the Base policy.
453      *
454      * @param prop
455      *        The model Properties
456      * @return A string with the answer from policy
457      */
458     public String deleteBasePolicy(ModelProperties prop) {
459         return deletePolicy(prop, PolicyConfigType.Base.toString(), null);
460     }
461
462     /**
463      * Format and send delete Guard requests to Policy.
464      *
465      * @param prop
466      *        The ModelProperties
467      * @return The response message from policy
468      */
469     public String deleteGuard(ModelProperties prop) {
470         String deletePolicyResponse = "";
471         try {
472
473             if (checkDecisionPolicyExists(prop)) {
474                 deletePolicyResponse = deletePolicy(prop, DictionaryType.Decision.toString(), null);
475             }
476         } catch (Exception e) {
477             logger.error("Exception occurred during policy communication", e);
478             throw new PolicyClientException("Exception while communicating with Policy", e);
479         }
480         return deletePolicyResponse;
481     }
482
483     /**
484      * Format and send delete BRMS requests to Policy.
485      *
486      * @param prop
487      *        The ModelProperties
488      * @return The response message from policy
489      */
490     public String deleteBrms(ModelProperties prop) {
491         String deletePolicyResponse = "";
492         try {
493             String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
494             if (checkPolicyExists(prop, policyNamePrefix, null)) {
495                 String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
496                 deletePolicyResponse = deletePolicy(prop, policyType, null);
497             }
498         } catch (Exception e) {
499             logger.error("Exception occurred during policy communication", e);
500             throw new PolicyClientException("Exception while communicating with Policy", e);
501         }
502         return deletePolicyResponse;
503     }
504
505     protected String selectRightPolicyName(ModelProperties prop, String policyType, String policyName) {
506         if (policyName == null) {
507             if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
508                 if (DictionaryType.Decision.toString().equals(policyType)) {
509                     return prop.getPolicyScopeAndNameWithUniqueGuardId();
510                 } else {
511                     return prop.getPolicyScopeAndNameWithUniqueId();
512                 }
513             } else {
514                 return prop.getCurrentPolicyScopeAndPolicyName();
515             }
516         } else {
517             return policyName;
518         }
519     }
520
521     /**
522      * Method to return correct policy name with prefix
523      * 
524      * @param prop
525      *        The ModelProperties
526      * @param policyPrefix
527      *        Policy Prefix
528      * @param policyNameWithPrefix
529      *        Policy Name With Prefix
530      * @return
531      */
532     protected String selectRightPolicyNameWithPrefix(ModelProperties prop, String policyPrefix,
533         String policyNameWithPrefix) {
534         if (policyNameWithPrefix == null) {
535             if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
536                 return prop.getCurrentPolicyScopeAndFullPolicyName(policyPrefix) + "_" + prop.getPolicyUniqueId();
537             } else {
538                 return prop.getCurrentPolicyScopeAndFullPolicyName(policyPrefix);
539             }
540         } else {
541             return policyNameWithPrefix;
542         }
543     }
544
545     /**
546      * Format and send delete PAP and PDP requests to Policy.
547      *
548      * @param prop
549      *        The ModelProperties
550      * @param policyType
551      *        The policyType "Decision" or
552      * @return The response message from policy
553      */
554     protected String deletePolicy(ModelProperties prop, String policyType, String policyName) {
555         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
556         deletePolicyParameters.setPolicyName(selectRightPolicyName(prop, policyType, policyName));
557         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
558         logger.info("Deleting policy from PDP...");
559         deletePolicyParameters.setPolicyComponent("PDP");
560         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
561         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
562         deletePolicyParameters.setPolicyType(policyType);
563         // send delete request
564         StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
565         logger.info("Deleting policy from PAP...");
566         deletePolicyParameters.setPolicyComponent("PAP");
567         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
568         // send delete request
569         responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
570         return responseMessage.toString();
571     }
572
573     /**
574      * Send delete request to Policy.
575      *
576      * @param deletePolicyParameters
577      *        The DeletePolicyParameters
578      * @param prop
579      *        The ModelProperties
580      * @return The response message from policy
581      */
582     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
583         // Verify whether it is triggered by Validation Test button from UI
584         if (prop.isTestOnly()) {
585             return "delete not executed for test action";
586         }
587         // API method to create or update Policy.
588         PolicyChangeResponse response = null;
589         String responseMessage = "";
590         try {
591             logger.info("Attempting to delete policy...");
592             response = getPolicyEngine().deletePolicy(deletePolicyParameters);
593             responseMessage = response.getResponseMessage();
594         } catch (Exception e) {
595             logger.error("Exception occurred during policy communnication", e);
596         }
597         logger.info(LOG_POLICY_PREFIX + responseMessage);
598         if (response != null && response.getResponseCode() == 200) {
599             logger.info("Policy delete successful");
600         } else {
601             logger.warn("Policy delete failed: " + responseMessage);
602             throw new BadRequestException("Policy delete failed: " + responseMessage);
603         }
604         return responseMessage;
605     }
606
607     /**
608      * Create a temp Tosca model file and perform import model to Policy Engine
609      *
610      * @param cldsToscaModel
611      *        Policy model details
612      * @return The response message from policy
613      */
614     public String importToscaModel(CldsToscaModel cldsToscaModel) {
615         String filePath = "";
616         try {
617             String clampToscaPath = refProp.getStringValue(TOSCA_FILE_TEMP_PATH);
618             filePath = buildFilePathForToscaFile(clampToscaPath, cldsToscaModel.getToscaModelName());
619             logger.info("Writing Tosca model : " + filePath);
620             Path path = Paths.get(filePath);
621             Files.createDirectories(path.getParent());
622             // Create or Ovewrite an existing the file
623             try (OutputStream out = Files.newOutputStream(path)) {
624                 out.write(cldsToscaModel.getToscaModelYaml().getBytes(), 0,
625                     cldsToscaModel.getToscaModelYaml().getBytes().length);
626             }
627         } catch (IOException e) {
628                         logger.error("Exception caught when attempting to write Tosca files to disk", e);
629             throw new PolicyClientException("Exception caught when attempting to write Tosca files to disk", e);
630         }
631
632         ImportParameters importParameters = new ImportParameters();
633         importParameters.setImportParameters(cldsToscaModel.getToscaModelName(), cldsToscaModel.getToscaModelName(),
634             null, filePath, IMPORT_TYPE.MICROSERVICE, String.valueOf(cldsToscaModel.getVersion()));
635         return importModel(importParameters);
636     }
637
638     /**
639      * @param importParameters
640      *        The ImportParameters
641      * @return The response message from policy
642      */
643     protected String importModel(ImportParameters importParameters) {
644         PolicyChangeResponse response = null;
645         String responseMessage = "";
646
647         try {
648             logger.info("Attempting to import tosca policy model for action=" + importParameters.getFilePath());
649             response = getPolicyEngine().policyEngineImport(importParameters);
650             if (response != null) {
651                 responseMessage = response.getResponseMessage();
652             }
653         } catch (Exception e) {
654             LoggingUtils.setResponseContext("900", "Policy Model import failed", this.getClass().getName());
655             LoggingUtils.setErrorContext("900", "Policy Model import error");
656             logger.error("Exception occurred during policy communication", e);
657             throw new PolicyClientException("Exception while communicating with Policy", e);
658         }
659         logger.info(LOG_POLICY_PREFIX + responseMessage);
660         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
661             LoggingUtils.setResponseContext("0", "Policy Model import success", this.getClass().getName());
662             logger.info("Policy import model successful");
663             metricsLogger.info("Policy import model success");
664         } else {
665             LoggingUtils.setResponseContext("900", "Policy import model failed", this.getClass().getName());
666             logger.warn("Policy import model failed: " + responseMessage);
667             metricsLogger.info("Policy import model failure");
668             throw new BadRequestException("Policy import model failed: " + responseMessage);
669         }
670         return responseMessage;
671     }
672
673     /**
674      * @param clampToscaPath
675      *        Temp directory path for writing tosca files
676      * @param toscaModelName
677      *        Tosca Model Name
678      * @return File Path on the system
679      */
680     private String buildFilePathForToscaFile(String clampToscaPath, String toscaModelName) {
681         return clampToscaPath + "/" + toscaModelName + ".yml";
682     }
683 }