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