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