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