Clean configPolicy
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / ConfigPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * Modified Copyright (C) 2019 Bell Canada.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.xacml.rest.components;
24
25 import java.io.BufferedWriter;
26 import java.io.File;
27 import java.io.FileWriter;
28 import java.io.IOException;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.HashMap;
34 import java.util.Map;
35
36 import org.apache.commons.io.FilenameUtils;
37 import org.onap.policy.common.logging.eelf.MessageCodes;
38 import org.onap.policy.common.logging.eelf.PolicyLogger;
39 import org.onap.policy.common.logging.flexlogger.FlexLogger;
40 import org.onap.policy.common.logging.flexlogger.Logger;
41 import org.onap.policy.rest.adapter.PolicyRestAdapter;
42 import org.onap.policy.utils.PolicyUtils;
43
44 import com.att.research.xacml.api.pap.PAPException;
45 import com.att.research.xacml.std.IdentifierImpl;
46
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
60
61 public class ConfigPolicy extends Policy {
62
63     /**
64      * Config Fields
65      */
66     private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class);
67
68     public static final String JSON_CONFIG = "JSON";
69     public static final String XML_CONFIG = "XML";
70     public static final String PROPERTIES_CONFIG = "PROPERTIES";
71     public static final String OTHER_CONFIG = "OTHER";
72
73     private String configBodyData;
74
75     public ConfigPolicy() {
76         super();
77     }
78
79     public ConfigPolicy(PolicyRestAdapter policyAdapter) {
80         this.policyAdapter = policyAdapter;
81     }
82
83     // Saving the Configurations file at server location for config policy.
84     protected void saveConfigurations(String policyName) {
85         String fileName = getConfigFile(policyName);
86         try (BufferedWriter bw = new BufferedWriter(new FileWriter(CONFIG_HOME + File.separator + fileName))) {
87             bw.write(configBodyData);
88             if (LOGGER.isDebugEnabled()) {
89                 LOGGER.debug("Configuration is succesfully saved");
90             }
91         } catch (IOException e) {
92             LOGGER.error("Exception Occured while writing Configuration Data" + e);
93         }
94     }
95
96
97     // Here we are adding the extension for the configurations file based on the
98     // config type selection for saving.
99     private String getConfigFile(String filename) {
100         filename = removeExtentsion(filename);
101         String id = policyAdapter.getConfigType();
102
103         if (id == null) {
104             return filename;
105         }
106         switch (id.toUpperCase())
107         {
108             case JSON_CONFIG:
109                 return filename + ".json";
110             case XML_CONFIG:
111                 return filename + ".xml";
112             case PROPERTIES_CONFIG:
113                 return filename + ".properties";
114             case OTHER_CONFIG:
115                 return filename + ".txt";
116             default:
117                 return filename;
118
119         }
120     }
121
122     private String removeExtentsion(String filename) {
123         filename = FilenameUtils.removeExtension(filename);
124         if (filename.endsWith(".xml")) {
125             filename = filename.substring(0, filename.length() - 4);
126         }
127         return filename;
128     }
129
130
131     // Validations for Config form
132     /*
133      * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
134      * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
135      */
136     public boolean validateConfigForm() {
137
138         isValidForm = true;
139
140         /*
141          * Validate Text Area Body
142          */
143         configBodyData = policyAdapter.getConfigBodyData();
144         String id = policyAdapter.getConfigType();
145         if (id == null) {
146             return isValidForm;
147         }
148         switch (id) {
149             case JSON_CONFIG:
150                 if (!PolicyUtils.isJSONValid(configBodyData)) {
151                     isValidForm = false;
152                 }
153                 break;
154             case XML_CONFIG:
155                 if (!PolicyUtils.isXMLValid(configBodyData)) {
156                     isValidForm = false;
157                 }
158                 break;
159             case PROPERTIES_CONFIG:
160                 if (!PolicyUtils.isPropValid(configBodyData) || configBodyData.equals("")) {
161                     isValidForm = false;
162                 }
163                 break;
164             case OTHER_CONFIG:
165                 if (configBodyData.equals("")) {
166                     isValidForm = false;
167                 }
168                 break;
169         }
170         return isValidForm;
171
172     }
173
174     @Override
175     public Map<String, String> savePolicies() throws PAPException {
176
177         Map<String, String> successMap = new HashMap<>();
178         if (isPolicyExists()) {
179             successMap.put("EXISTS", "This Policy already exist on the PAP");
180             return successMap;
181         }
182
183         if (!isPreparedToSave()) {
184             //Prep and configure the policy for saving
185             prepareToSave();
186         }
187
188         // Until here we prepared the data and here calling the method to create xml.
189         Path newPolicyPath = null;
190         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
191         successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
192         return successMap;
193     }
194
195     //This is the method for preparing the policy for saving.  We have broken it out
196     //separately because the fully configured policy is used for multiple things
197     @Override
198     public boolean prepareToSave() throws PAPException {
199
200         if (isPreparedToSave()) {
201             return true;
202         }
203
204         int version = 0;
205         String policyID = policyAdapter.getPolicyID();
206         version = policyAdapter.getHighestVersion();
207
208         // Create the Instance for pojo, PolicyType object is used in marshalling.
209         if (policyAdapter.getPolicyType().equals("Config")) {
210             PolicyType policyConfig = new PolicyType();
211
212             policyConfig.setVersion(Integer.toString(version));
213             policyConfig.setPolicyId(policyID);
214             policyConfig.setTarget(new TargetType());
215             policyAdapter.setData(policyConfig);
216         }
217
218         policyName = policyAdapter.getNewFileName();
219         configBodyData = policyAdapter.getConfigBodyData();
220         saveConfigurations(policyName);
221
222         if (policyAdapter.getData() != null) {
223             PolicyType configPolicy = (PolicyType) policyAdapter.getData();
224
225             configPolicy.setDescription(policyAdapter.getPolicyDescription());
226
227             configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
228             AllOfType allOfOne = new AllOfType();
229
230             String fileName = policyAdapter.getNewFileName();
231             String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
232             if ((name == null) || (name.equals(""))) {
233                 name = fileName.substring(fileName.lastIndexOf("/") + 1);
234             }
235             allOfOne.getMatch().add(createMatch("PolicyName", name));
236             AllOfType allOf = new AllOfType();
237
238             // Adding the matches to AllOfType element Match for Onap
239             allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
240             // Match for riskType
241             allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
242             // Match for riskLevel
243             allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
244             // Match for riskguard
245             allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
246             // Match for ttlDate
247             allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
248             // Match for ConfigName
249             allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
250
251             Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
252
253             // If there is any dynamic field create the matches here
254             for (String keyField : dynamicFieldConfigAttributes.keySet()) {
255                 String key = keyField;
256                 String value = dynamicFieldConfigAttributes.get(key);
257                 MatchType dynamicMatch = createDynamicMatch(key, value);
258                 allOf.getMatch().add(dynamicMatch);
259             }
260
261             AnyOfType anyOf = new AnyOfType();
262             anyOf.getAllOf().add(allOfOne);
263             anyOf.getAllOf().add(allOf);
264
265             TargetType target = new TargetType();
266             ((TargetType) target).getAnyOf().add(anyOf);
267
268             // Adding the target to the policy element
269             configPolicy.setTarget((TargetType) target);
270
271             RuleType rule = new RuleType();
272             rule.setRuleId(policyAdapter.getRuleID());
273             rule.setEffect(EffectType.PERMIT);
274
275             // Create Target in Rule
276             AllOfType allOfInRule = new AllOfType();
277
278             // Creating match for ACCESS in rule target
279             MatchType accessMatch = new MatchType();
280             AttributeValueType accessAttributeValue = new AttributeValueType();
281             accessAttributeValue.setDataType(STRING_DATATYPE);
282             accessAttributeValue.getContent().add("ACCESS");
283             accessMatch.setAttributeValue(accessAttributeValue);
284             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
285             URI accessURI = null;
286             try {
287                 accessURI = new URI(ACTION_ID);
288             } catch (URISyntaxException e) {
289                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
290             }
291             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
292             accessAttributeDesignator.setDataType(STRING_DATATYPE);
293             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
294             accessMatch.setAttributeDesignator(accessAttributeDesignator);
295             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
296
297             // Creating Config Match in rule Target
298             MatchType configMatch = new MatchType();
299             AttributeValueType configAttributeValue = new AttributeValueType();
300             configAttributeValue.setDataType(STRING_DATATYPE);
301             configAttributeValue.getContent().add("Config");
302             configMatch.setAttributeValue(configAttributeValue);
303             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
304             URI configURI = null;
305             try {
306                 configURI = new URI(RESOURCE_ID);
307             } catch (URISyntaxException e) {
308                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
309             }
310             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
311             configAttributeDesignator.setDataType(STRING_DATATYPE);
312             configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
313             configMatch.setAttributeDesignator(configAttributeDesignator);
314             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
315
316             allOfInRule.getMatch().add(accessMatch);
317             allOfInRule.getMatch().add(configMatch);
318
319             AnyOfType anyOfInRule = new AnyOfType();
320             anyOfInRule.getAllOf().add(allOfInRule);
321
322             TargetType targetInRule = new TargetType();
323             targetInRule.getAnyOf().add(anyOfInRule);
324
325             rule.setTarget(targetInRule);
326             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
327
328             configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
329             policyAdapter.setPolicyData(configPolicy);
330
331         } else {
332             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
333         }
334         setPreparedToSave(true);
335         return true;
336     }
337
338     // Data required for Advice part is setting here.
339     private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
340         AdviceExpressionsType advices = new AdviceExpressionsType();
341         AdviceExpressionType advice = new AdviceExpressionType();
342         advice.setAdviceId("configID");
343         advice.setAppliesTo(EffectType.PERMIT);
344
345         // For Configuration
346         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
347         assignment1.setAttributeId("type");
348         assignment1.setCategory(CATEGORY_RESOURCE);
349         assignment1.setIssuer("");
350
351         AttributeValueType configNameAttributeValue = new AttributeValueType();
352         configNameAttributeValue.setDataType(STRING_DATATYPE);
353         configNameAttributeValue.getContent().add("Configuration");
354         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
355
356         advice.getAttributeAssignmentExpression().add(assignment1);
357
358         // For Config file Url if configurations are provided.
359         if (policyAdapter.getConfigType() != null) {
360             AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
361             assignment2.setAttributeId("URLID");
362             assignment2.setCategory(CATEGORY_RESOURCE);
363             assignment2.setIssuer("");
364
365             AttributeValueType AttributeValue = new AttributeValueType();
366             AttributeValue.setDataType(URI_DATATYPE);
367             String content = "$URL" + "/Config/" + getConfigFile(policyName);
368             AttributeValue.getContent().add(content);
369             assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
370
371             advice.getAttributeAssignmentExpression().add(assignment2);
372             AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
373             assignment3.setAttributeId("PolicyName");
374             assignment3.setCategory(CATEGORY_RESOURCE);
375             assignment3.setIssuer("");
376
377             AttributeValueType attributeValue3 = new AttributeValueType();
378             attributeValue3.setDataType(STRING_DATATYPE);
379
380             fileName = FilenameUtils.removeExtension(fileName);
381             fileName = fileName + ".xml";
382             String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
383             if ((name == null) || (name.equals(""))) {
384                 name = fileName.substring(fileName.lastIndexOf("/") + 1);
385             }
386             attributeValue3.getContent().add(name);
387             assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
388             advice.getAttributeAssignmentExpression().add(assignment3);
389
390             AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
391             assignment4.setAttributeId("VersionNumber");
392             assignment4.setCategory(CATEGORY_RESOURCE);
393             assignment4.setIssuer("");
394
395             AttributeValueType configNameAttributeValue4 = new AttributeValueType();
396             configNameAttributeValue4.setDataType(STRING_DATATYPE);
397             configNameAttributeValue4.getContent().add(Integer.toString(version));
398             assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
399
400             advice.getAttributeAssignmentExpression().add(assignment4);
401
402             AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
403             assignment5.setAttributeId("matching:" + ONAPID);
404             assignment5.setCategory(CATEGORY_RESOURCE);
405             assignment5.setIssuer("");
406
407             AttributeValueType configNameAttributeValue5 = new AttributeValueType();
408             configNameAttributeValue5.setDataType(STRING_DATATYPE);
409             configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
410             assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
411
412             advice.getAttributeAssignmentExpression().add(assignment5);
413
414             AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
415             assignment6.setAttributeId("matching:" + CONFIGID);
416             assignment6.setCategory(CATEGORY_RESOURCE);
417             assignment6.setIssuer("");
418
419             AttributeValueType configNameAttributeValue6 = new AttributeValueType();
420             configNameAttributeValue6.setDataType(STRING_DATATYPE);
421             configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
422             assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
423
424             advice.getAttributeAssignmentExpression().add(assignment6);
425
426             Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
427             for (String keyField : dynamicFieldConfigAttributes.keySet()) {
428                 String key = keyField;
429                 String value = dynamicFieldConfigAttributes.get(key);
430                 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
431                 assignment7.setAttributeId("matching:" + key);
432                 assignment7.setCategory(CATEGORY_RESOURCE);
433                 assignment7.setIssuer("");
434
435                 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
436                 configNameAttributeValue7.setDataType(STRING_DATATYPE);
437                 configNameAttributeValue7.getContent().add(value);
438                 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
439
440                 advice.getAttributeAssignmentExpression().add(assignment7);
441             }
442         }
443
444         //Risk Attributes
445         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
446         assignment8.setAttributeId("RiskType");
447         assignment8.setCategory(CATEGORY_RESOURCE);
448         assignment8.setIssuer("");
449
450         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
451         configNameAttributeValue8.setDataType(STRING_DATATYPE);
452         configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
453         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
454
455         advice.getAttributeAssignmentExpression().add(assignment8);
456
457         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
458         assignment9.setAttributeId("RiskLevel");
459         assignment9.setCategory(CATEGORY_RESOURCE);
460         assignment9.setIssuer("");
461
462         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
463         configNameAttributeValue9.setDataType(STRING_DATATYPE);
464         configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
465         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
466
467         advice.getAttributeAssignmentExpression().add(assignment9);
468
469         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
470         assignment10.setAttributeId("guard");
471         assignment10.setCategory(CATEGORY_RESOURCE);
472         assignment10.setIssuer("");
473
474         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
475         configNameAttributeValue10.setDataType(STRING_DATATYPE);
476         configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
477         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
478
479         advice.getAttributeAssignmentExpression().add(assignment10);
480
481         AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
482         assignment11.setAttributeId("TTLDate");
483         assignment11.setCategory(CATEGORY_RESOURCE);
484         assignment11.setIssuer("");
485
486         AttributeValueType configNameAttributeValue11 = new AttributeValueType();
487         configNameAttributeValue11.setDataType(STRING_DATATYPE);
488         configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
489         assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
490
491         advice.getAttributeAssignmentExpression().add(assignment11);
492
493         advices.getAdviceExpression().add(advice);
494         return advices;
495     }
496
497     @Override
498     public Object getCorrectPolicyDataObject() {
499         return policyAdapter.getPolicyData();
500     }
501
502 }