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