e74cc335926966464c1c7a9f841a2be3a814635f
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / CreateClosedLoopPerformanceMetrics.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
23
24 import java.io.File;
25 import java.io.PrintWriter;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.HashMap;
31 import java.util.Map;
32
33 import org.apache.commons.io.FilenameUtils;
34 import org.onap.policy.common.logging.eelf.MessageCodes;
35 import org.onap.policy.common.logging.eelf.PolicyLogger;
36 import org.onap.policy.common.logging.flexlogger.FlexLogger;
37 import org.onap.policy.common.logging.flexlogger.Logger;
38 import org.onap.policy.rest.adapter.PolicyRestAdapter;
39
40 import com.att.research.xacml.api.pap.PAPException;
41 import com.att.research.xacml.std.IdentifierImpl;
42
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
56
57 public class CreateClosedLoopPerformanceMetrics extends Policy {
58
59     private static final Logger LOGGER  = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class);
60
61     public CreateClosedLoopPerformanceMetrics() {
62         super();
63     }
64
65     public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){
66         this.policyAdapter = policyAdapter;
67     }
68
69     //save configuration of the policy based on the policyname
70     private void saveConfigurations(String policyName, final String jsonBody) {
71
72             if(policyName.endsWith(".xml")){
73                 policyName   = policyName.substring(0, policyName.lastIndexOf(".xml"));
74             }
75         try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json")){
76             out.println(jsonBody);
77             policyAdapter.setJsonBody(jsonBody);
78             policyAdapter.setConfigBodyData(jsonBody);
79         } catch (Exception e) {
80             LOGGER.error("Exception Occured"+e);
81         }
82     }
83
84     //getting the policy name and setting to configuration on adding .json
85     private String getConfigFile(String filename) {
86         filename = FilenameUtils.removeExtension(filename);
87         if (filename.endsWith(".xml")) {
88             filename = filename.substring(0, filename.length() - 4);
89         }
90         filename = filename +".json";
91         return filename;
92     }
93
94     @Override
95     public Map<String, String> savePolicies() throws PAPException {
96
97         Map<String, String> successMap = new HashMap<>();
98         if(isPolicyExists()){
99             successMap.put("EXISTS", "This Policy already exist on the PAP");
100             return successMap;
101         }
102
103         if(!isPreparedToSave()){
104             //Prep and configure the policy for saving
105             prepareToSave();
106         }
107
108         // Until here we prepared the data and here calling the method to create xml.
109         Path newPolicyPath = null;
110         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
111
112         successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
113
114         return successMap;
115     }
116
117     //This is the method for preparing the policy for saving.  We have broken it out
118     //separately because the fully configured policy is used for multiple things
119     @Override
120     public boolean prepareToSave() throws PAPException{
121
122         if(isPreparedToSave()){
123             //we have already done this
124             return true;
125         }
126
127         int version = 0;
128         String policyID = policyAdapter.getPolicyID();
129         version = policyAdapter.getHighestVersion();
130
131         // Create the Instance for pojo, PolicyType object is used in marshalling.
132         if (policyAdapter.getPolicyType().equals("Config")) {
133             PolicyType policyConfig = new PolicyType();
134
135             policyConfig.setVersion(Integer.toString(version));
136             policyConfig.setPolicyId(policyID);
137             policyConfig.setTarget(new TargetType());
138             policyAdapter.setData(policyConfig);
139         }
140         policyName = policyAdapter.getNewFileName();
141         if (policyAdapter.getData() != null) {
142             // Save the Configurations file with the policy name with extention based on selection.
143             String jsonBody = policyAdapter.getJsonBody();
144             saveConfigurations(policyName, jsonBody);
145
146             // Make sure the filename ends with an extension
147             if (policyName.endsWith(".xml") == false) {
148                 policyName = policyName + ".xml";
149             }
150
151
152             PolicyType configPolicy = (PolicyType) policyAdapter.getData();
153
154             configPolicy.setDescription(policyAdapter.getPolicyDescription());
155
156             configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
157
158             AllOfType allOfOne = new AllOfType();
159             String fileName = policyAdapter.getNewFileName();
160             String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
161             if ((name == null) || (name.equals(""))) {
162                 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
163             }
164             allOfOne.getMatch().add(createMatch("PolicyName", name));
165             AllOfType allOf = new AllOfType();
166
167             // Adding the matches to AllOfType element Match for Onap
168             allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
169             // Match for riskType
170             allOf.getMatch().add(
171                     createDynamicMatch("RiskType", policyAdapter.getRiskType()));
172             // Match for riskLevel
173             allOf.getMatch().add(
174                     createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
175             // Match for riskguard
176             allOf.getMatch().add(
177                     createDynamicMatch("guard", policyAdapter.getGuard()));
178             // Match for ttlDate
179             allOf.getMatch().add(
180                     createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
181             // Match for ServiceType
182             allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType()));
183
184             AnyOfType anyOf = new AnyOfType();
185             anyOf.getAllOf().add(allOfOne);
186             anyOf.getAllOf().add(allOf);
187
188             TargetType target = new TargetType();
189             ((TargetType) target).getAnyOf().add(anyOf);
190
191             // Adding the target to the policy element
192             configPolicy.setTarget((TargetType) target);
193
194             RuleType rule = new RuleType();
195             rule.setRuleId(policyAdapter.getRuleID());
196
197             rule.setEffect(EffectType.PERMIT);
198
199             // Create Target in Rule
200             AllOfType allOfInRule = new AllOfType();
201
202             // Creating match for ACCESS in rule target
203             MatchType accessMatch = new MatchType();
204             AttributeValueType accessAttributeValue = new AttributeValueType();
205             accessAttributeValue.setDataType(STRING_DATATYPE);
206             accessAttributeValue.getContent().add("ACCESS");
207             accessMatch.setAttributeValue(accessAttributeValue);
208             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
209             URI accessURI = null;
210             try {
211                 accessURI = new URI(ACTION_ID);
212             } catch (URISyntaxException e) {
213                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI");
214             }
215             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
216             accessAttributeDesignator.setDataType(STRING_DATATYPE);
217             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
218             accessMatch.setAttributeDesignator(accessAttributeDesignator);
219             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
220
221             // Creating Config Match in rule Target
222             MatchType configMatch = new MatchType();
223             AttributeValueType configAttributeValue = new AttributeValueType();
224             configAttributeValue.setDataType(STRING_DATATYPE);
225             configAttributeValue.getContent().add("Config");
226             configMatch.setAttributeValue(configAttributeValue);
227             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
228             URI configURI = null;
229             try {
230                 configURI = new URI(RESOURCE_ID);
231             } catch (URISyntaxException e) {
232                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI");
233             }
234             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
235             configAttributeDesignator.setDataType(STRING_DATATYPE);
236             configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
237             configMatch.setAttributeDesignator(configAttributeDesignator);
238             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
239
240             allOfInRule.getMatch().add(accessMatch);
241             allOfInRule.getMatch().add(configMatch);
242
243             AnyOfType anyOfInRule = new AnyOfType();
244             anyOfInRule.getAllOf().add(allOfInRule);
245
246             TargetType targetInRule = new TargetType();
247             targetInRule.getAnyOf().add(anyOfInRule);
248
249             rule.setTarget(targetInRule);
250             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
251
252             configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
253             policyAdapter.setPolicyData(configPolicy);
254
255         } else {
256             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
257         }
258         setPreparedToSave(true);
259         return true;
260     }
261
262     // Data required for Advice part is setting here.
263     @SuppressWarnings("static-access")
264     private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
265         AdviceExpressionsType advices = new AdviceExpressionsType();
266         AdviceExpressionType advice = new AdviceExpressionType();
267         advice.setAdviceId("PMID");
268         advice.setAppliesTo(EffectType.PERMIT);
269         // For Configuration
270         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
271         assignment1.setAttributeId("type");
272         assignment1.setCategory(CATEGORY_RESOURCE);
273         assignment1.setIssuer("");
274
275         AttributeValueType configNameAttributeValue = new AttributeValueType();
276         configNameAttributeValue.setDataType(STRING_DATATYPE);
277         configNameAttributeValue.getContent().add("Configuration");
278         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
279
280         advice.getAttributeAssignmentExpression().add(assignment1);
281         // For Config file Url if configurations are provided.
282         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
283         assignment2.setAttributeId("URLID");
284         assignment2.setCategory(CATEGORY_RESOURCE);
285         assignment2.setIssuer("");
286
287         AttributeValueType AttributeValue = new AttributeValueType();
288         AttributeValue.setDataType(URI_DATATYPE);
289         String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName);
290         AttributeValue.getContent().add(content);
291         assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
292
293         advice.getAttributeAssignmentExpression().add(assignment2);
294         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
295         assignment3.setAttributeId("PolicyName");
296         assignment3.setCategory(CATEGORY_RESOURCE);
297         assignment3.setIssuer("");
298
299         AttributeValueType attributeValue3 = new AttributeValueType();
300         attributeValue3.setDataType(STRING_DATATYPE);
301         fileName = FilenameUtils.removeExtension(fileName);
302         fileName = fileName + ".xml";
303         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
304         if ((name == null) || (name.equals(""))) {
305             name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
306         }
307         attributeValue3.getContent().add(name);
308         assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
309         advice.getAttributeAssignmentExpression().add(assignment3);
310
311         AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
312         assignment4.setAttributeId("VersionNumber");
313         assignment4.setCategory(CATEGORY_RESOURCE);
314         assignment4.setIssuer("");
315
316         AttributeValueType configNameAttributeValue4 = new AttributeValueType();
317         configNameAttributeValue4.setDataType(STRING_DATATYPE);
318         configNameAttributeValue4.getContent().add(Integer.toString(version));
319         assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
320
321         advice.getAttributeAssignmentExpression().add(assignment4);
322
323         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
324         assignment5.setAttributeId("matching:" + this.ONAPID);
325         assignment5.setCategory(CATEGORY_RESOURCE);
326         assignment5.setIssuer("");
327
328         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
329         configNameAttributeValue5.setDataType(STRING_DATATYPE);
330         configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
331         assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
332
333         advice.getAttributeAssignmentExpression().add(assignment5);
334
335         AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
336         assignment6.setAttributeId("matching:" + this.CLOSEDLOOPID);
337         assignment6.setCategory(CATEGORY_RESOURCE);
338         assignment6.setIssuer("");
339
340         AttributeValueType configNameAttributeValue6 = new AttributeValueType();
341         configNameAttributeValue6.setDataType(STRING_DATATYPE);
342         configNameAttributeValue6.getContent().add(policyAdapter.getServiceType());
343         assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
344
345         advice.getAttributeAssignmentExpression().add(assignment6);
346
347         //Risk Attributes
348         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
349         assignment7.setAttributeId("RiskType");
350         assignment7.setCategory(CATEGORY_RESOURCE);
351         assignment7.setIssuer("");
352
353         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
354         configNameAttributeValue7.setDataType(STRING_DATATYPE);
355         configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
356         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
357
358         advice.getAttributeAssignmentExpression().add(assignment7);
359
360         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
361         assignment8.setAttributeId("RiskLevel");
362         assignment8.setCategory(CATEGORY_RESOURCE);
363         assignment8.setIssuer("");
364
365         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
366         configNameAttributeValue8.setDataType(STRING_DATATYPE);
367         configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
368         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
369
370         advice.getAttributeAssignmentExpression().add(assignment8);
371
372         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
373         assignment9.setAttributeId("guard");
374         assignment9.setCategory(CATEGORY_RESOURCE);
375         assignment9.setIssuer("");
376
377         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
378         configNameAttributeValue9.setDataType(STRING_DATATYPE);
379         configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
380         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
381
382         advice.getAttributeAssignmentExpression().add(assignment9);
383
384         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
385         assignment10.setAttributeId("TTLDate");
386         assignment10.setCategory(CATEGORY_RESOURCE);
387         assignment10.setIssuer("");
388
389         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
390         configNameAttributeValue10.setDataType(STRING_DATATYPE);
391         configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
392         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
393
394         advice.getAttributeAssignmentExpression().add(assignment10);
395
396         advices.getAdviceExpression().add(advice);
397         return advices;
398     }
399
400     @Override
401     public Object getCorrectPolicyDataObject() {
402         return policyAdapter.getPolicyData();
403     }
404
405 }