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