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