[CLAMP-1] Initial ONAP CLAMP seed code commit
[clamp.git] / src / main / java / org / onap / clamp / clds / client / PolicyClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.client;
25
26 import org.onap.clamp.clds.model.prop.ModelProperties;
27 import org.onap.clamp.clds.model.refprop.RefProp;
28 import org.openecomp.policy.api.*;
29 import org.springframework.beans.factory.annotation.Autowired;
30 import org.springframework.beans.factory.annotation.Value;
31 import org.springframework.context.ApplicationContext;
32
33 import java.util.*;
34 import java.util.logging.Logger;
35
36
37 /**
38  * Policy utility methods - specifically, send the policy.
39  */
40 public class PolicyClient {
41     // currently uses the java.util.logging.Logger like the Camunda engine
42     private static final Logger logger = Logger.getLogger(PolicyClient.class.getName());
43
44     @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:etc/clds/clds-policy-config.properties'}")
45     private String cldsPolicyConfigFile;
46
47     @Autowired
48     private ApplicationContext appContext;
49     
50     @Autowired
51     private RefProp refProp;
52     
53     public PolicyClient() {
54         
55     }
56
57     /**
58      * Perform send of microservice policy
59      *
60      * @param attributes
61      * @param prop
62      * @param policyRequestUUID
63      * @return
64      * @throws Exception
65      */
66     public String sendBrms(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop, String policyRequestUUID) throws Exception {
67
68         PolicyParameters policyParameters = new PolicyParameters();
69
70         // Set Policy Type(Mandatory)
71         policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
72
73         // Set Policy Name(Mandatory)
74         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
75         //Set Scope folder where the policy needs to be created(Mandatory)
76         //policyParameters.setPolicyScope(policyScope);
77
78         // documentation says this is options, but when tested, got the following failure: java.lang.Exception: Policy send failed: PE300 - Data Issue: No policyDescription given.
79         policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
80
81         policyParameters.setAttributes(attributes);
82
83         //Set a random UUID(Mandatory)
84         policyParameters.setRequestID(UUID.fromString(policyRequestUUID));
85
86         String rtnMsg = send(policyParameters, prop);
87
88         String policyType = refProp.getStringValue("policy.op.type");
89         push(policyType, prop);
90
91         return rtnMsg;
92     }
93
94     /**
95      * Perform send of microservice policy
96      *
97      * @param policyJson
98      * @param prop
99      * @param policyRequestUUID
100      * @return
101      * @throws Exception
102      */
103     public String sendMicroService(String policyJson, ModelProperties prop, String policyRequestUUID) throws Exception {
104
105         PolicyParameters policyParameters = new PolicyParameters();
106
107         // Set Policy Type
108         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
109         policyParameters.setEcompName(refProp.getStringValue("policy.ecomp.name"));
110         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
111
112         policyParameters.setConfigBody(policyJson);
113         policyParameters.setConfigBodyType(PolicyType.JSON);
114
115         policyParameters.setRequestID(UUID.fromString(policyRequestUUID));
116
117         String rtnMsg = send(policyParameters, prop);
118
119         String policyType = refProp.getStringValue("policy.ms.type");
120         push(policyType, prop);
121
122         return rtnMsg;
123     }
124
125     /**
126      * Perform send of policy.
127      *
128      * @param policyParameters
129      * @param prop
130      * @return
131      * @throws Exception
132      */
133     private String send(PolicyParameters policyParameters, ModelProperties prop) throws Exception {
134         PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
135
136         // API method to create or update Policy.
137         PolicyChangeResponse response = null;
138         String responseMessage;
139         try {
140             if (prop.isCreateRequest()) {
141                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
142                 response = policyEngine.createPolicy(policyParameters);
143                 responseMessage = response.getResponseMessage();
144             } else {
145                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
146                 response = policyEngine.updatePolicy(policyParameters);
147                 responseMessage = response.getResponseMessage();
148             }
149         } catch (Exception e) {
150             responseMessage = e.toString();
151         }
152         logger.info("response is " + responseMessage);
153
154         if (response != null && response.getResponseCode() == 200) {
155             logger.info("Policy send successful");
156         } else {
157             logger.warning("Policy send failed: " + responseMessage);
158             throw new Exception("Policy send failed: " + responseMessage);
159         }
160
161         return responseMessage;
162     }
163
164     /**
165      * Format and send push of policy.
166      *
167      * @param policyType
168      * @param prop
169      * @return
170      * @throws Exception
171      */
172     private String push(String policyType, ModelProperties prop) throws Exception {
173         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
174
175         //Parameter arguments
176         pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
177         pushPolicyParameters.setPolicyType(policyType);
178         //pushPolicyParameters.setPolicyScope(policyScope);
179         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
180         pushPolicyParameters.setRequestID(null);
181
182         PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
183
184         // API method to create or update Policy.
185         PolicyChangeResponse response = null;
186         String responseMessage;
187         try {
188             logger.info("Attempting to push policy...");
189             response = policyEngine.pushPolicy(pushPolicyParameters);
190             responseMessage = response.getResponseMessage();
191         } catch (Exception e) {
192             responseMessage = e.toString();
193         }
194         logger.info("response is " + responseMessage);
195
196         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
197             logger.info("Policy push successful");
198         } else {
199             logger.warning("Policy push failed: " + responseMessage);
200             throw new Exception("Policy push failed: " + responseMessage);
201         }
202
203         return responseMessage;
204     }
205
206     /**
207      * Use Get Config Policy API to retrieve the versions for a policy.
208      * Return versions in sorted order.
209      * Return empty list if none found.
210      *
211      * @param policyNamePrefix
212      * @param prop
213      * @return
214      * @throws Exception
215      */
216     private List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws Exception {
217
218         ArrayList<Integer> versions = new ArrayList<>();
219         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
220         String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
221         logger.info("policyName=" + policyName);
222         configRequestParameters.setPolicyName(policyName);
223
224         PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
225
226         Collection<PolicyConfig> response = policyEngine.getConfig(configRequestParameters);
227
228         Iterator<PolicyConfig> itrResp = response.iterator();
229
230         while (itrResp.hasNext()) {
231             PolicyConfig policyConfig = itrResp.next();
232             try {
233                 Integer version = new Integer(policyConfig.getPolicyVersion());
234                 versions.add(version);
235             } catch (Exception e) {
236                 // just print warning - if n;o policies, version may be null
237                 logger.warning("warning: failed to parse policyConfig.getPolicyVersion()=" + policyConfig.getPolicyVersion());
238             }
239         }
240         Collections.sort(versions);
241         logger.info("versions.size()=" + versions.size());
242
243         return versions;
244     }
245
246     /**
247      * Format and send delete Micro Service requests to Policy
248      *
249      * @param prop
250      * @return
251      * @throws Exception
252      */
253     public String deleteMicrosService(ModelProperties prop) throws Exception {
254         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
255         return deletePolicy(policyNamePrefix, prop);
256     }
257
258     /**
259      * Format and send delete BRMS requests to Policy
260      *
261      * @param prop
262      * @return
263      * @throws Exception
264      */
265     public String deleteBrms(ModelProperties prop) throws Exception {
266         String policyNamePrefix = refProp.getStringValue("policy.op.policyNamePrefix");
267         return deletePolicy(policyNamePrefix, prop);
268     }
269
270     /**
271      * Format and send delete PAP and PDP requests to Policy
272      *
273      * @param policyNamePrefix
274      * @param prop
275      * @return
276      * @throws Exception
277      */
278     private String deletePolicy(String policyNamePrefix, ModelProperties prop) throws Exception {
279         String responseMessage = null;
280
281         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
282
283         List<Integer> versions = getVersions(policyNamePrefix, prop);
284         if (versions.size() > 0) {
285             int maxVersion = Collections.max(versions);
286
287             // format delete all PAP request
288             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndFullPolicyNameWithVersion(policyNamePrefix, maxVersion));
289             deletePolicyParameters.setPolicyComponent("PAP");
290             deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
291             String policyType = refProp.getStringValue("policy.ms.type");
292             deletePolicyParameters.setPolicyType(policyType);
293
294             //send delete request
295             responseMessage = sendDeletePolicy(deletePolicyParameters, prop);
296         }
297
298         for (Integer version : versions) {
299             // format delete all PDP request
300             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndFullPolicyNameWithVersion(policyNamePrefix, version));
301             deletePolicyParameters.setPolicyComponent("PDP");
302             deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
303             //send delete request
304             responseMessage = responseMessage + "; " + sendDeletePolicy(deletePolicyParameters, prop);
305         }
306
307         return responseMessage;
308     }
309
310     /**
311      * Send delete request to Policy
312      *
313      * @param deletePolicyParameters
314      * @param prop
315      * @return
316      * @throws Exception
317      */
318     private String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) throws Exception {
319         PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
320
321         // API method to create or update Policy.
322         PolicyChangeResponse response = null;
323         String responseMessage;
324         try {
325             logger.info("Attempting to delete policy...");
326             response = policyEngine.deletePolicy(deletePolicyParameters);
327             responseMessage = response.getResponseMessage();
328         } catch (Exception e) {
329             responseMessage = e.toString();
330         }
331         logger.info("response is " + responseMessage);
332
333         if (response != null && response.getResponseCode() == 200) {
334             logger.info("Policy delete successful");
335         } else {
336             logger.warning("Policy delete failed: " + responseMessage);
337             throw new Exception("Policy delete failed: " + responseMessage);
338         }
339
340         return responseMessage;
341     }
342 }