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