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