efa28b2bbdb96e1b9655cb4ff4e064d47a9c2a7c
[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     private static final String EMPTY_STRING = "";
64
65     public CreateBrmsRawPolicy() {
66         super();
67     }
68
69     public CreateBrmsRawPolicy(PolicyRestAdapter policyAdapter) {
70         this.policyAdapter = policyAdapter;
71         this.policyAdapter.setConfigType(policyAdapter.getConfigType());
72
73     }
74
75     // Saving the Configurations file at server location for CreateBrmsRawPolicy policy.
76     protected void saveConfigurations(String policyName, String jsonBody) {
77
78         if (policyName.endsWith(".xml")) {
79             policyName = policyName.substring(0,
80                     policyName.lastIndexOf(".xml"));
81         }
82         try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
83             out.println(jsonBody);
84         } catch (Exception e) {
85             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy",
86                     "Exception saving configurations file");
87         }
88     }
89
90     // Utility to read json data from the existing file to a string
91     static String readFile(String path, Charset encoding) throws IOException {
92
93         byte[] encoded = Files.readAllBytes(Paths.get(path));
94         return new String(encoded, encoding);
95
96     }
97
98     // Here we are adding the extension for the configurations file based on the
99     // config type selection for saving.
100     private String getConfigFile(String filename) {
101         filename = FilenameUtils.removeExtension(filename);
102         if (filename.endsWith(".txt")) {
103             filename = filename.substring(0, filename.length() - 3);
104         }
105
106         filename = filename + ".txt";
107         return filename;
108     }
109
110     // Validations for Config form
111     public boolean validateConfigForm() {
112
113         // Validating mandatory Fields.
114         isValidForm = true;
115         return isValidForm;
116
117     }
118
119     @Override
120     public Map<String, String> savePolicies() throws PAPException {
121
122         Map<String, String> successMap = new HashMap<>();
123         if (isPolicyExists()) {
124             successMap.put("EXISTS", "This Policy already exist on the PAP");
125             return successMap;
126         }
127
128         if (!isPreparedToSave()) {
129             prepareToSave();
130         }
131         // Until here we prepared the data and here calling the method to create
132         // xml.
133         Path newPolicyPath = null;
134         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
135
136         successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
137         if (successMap == null) {
138             successMap = new HashMap<>();
139             PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
140             successMap.put("error", "DB UPDATE");
141         }
142
143         return successMap;
144     }
145
146     // This is the method for preparing the policy for saving. We have broken it
147     // out
148     // separately because the fully configured policy is used for multiple
149     // things
150     @Override
151     public boolean prepareToSave() {
152
153         if (isPreparedToSave()) {
154             // we have already done this
155             return true;
156         }
157
158         int version = 0;
159         String policyID = policyAdapter.getPolicyID();
160         version = policyAdapter.getHighestVersion();
161
162         // Create the Instance for pojo, PolicyType object is used in
163         // marshalling.
164         if ("Config".equals(policyAdapter.getPolicyType())) {
165             PolicyType policyConfig = new PolicyType();
166
167             policyConfig.setVersion(Integer.toString(version));
168             policyConfig.setPolicyId(policyID);
169             policyConfig.setTarget(new TargetType());
170             policyAdapter.setData(policyConfig);
171         }
172
173         policyName = policyAdapter.getNewFileName();
174
175         if (policyAdapter.getData() != null) {
176             String configBody = policyAdapter.getConfigBodyData();
177             saveConfigurations(policyName, configBody);
178
179             // Make sure the filename ends with an extension
180             if (!policyName.endsWith(".xml")) {
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);
193             if (EMPTY_STRING.equals(name)) {
194                 name = fileName.substring(fileName.lastIndexOf("/") + 1);
195             }
196             allOfOne.getMatch().add(createMatch("PolicyName", name));
197
198
199             AllOfType allOf = new AllOfType();
200
201             // Match for ONAPName
202             allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
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             target.getAnyOf().add(anyOf);
218
219             // Adding the target to the policy element
220             configPolicy.setTarget(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",
242                         "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",
265                         "Exception creating Config URI");
266             }
267
268             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
269             configAttributeDesignator.setDataType(STRING_DATATYPE);
270             configAttributeDesignator.setAttributeId(new IdentifierImpl(
271                     configURI).stringValue());
272             configMatch.setAttributeDesignator(configAttributeDesignator);
273             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
274
275             allOfInRule.getMatch().add(accessMatch);
276             allOfInRule.getMatch().add(configMatch);
277
278             AnyOfType anyOfInRule = new AnyOfType();
279             anyOfInRule.getAllOf().add(allOfInRule);
280
281             TargetType targetInRule = new TargetType();
282             targetInRule.getAnyOf().add(anyOfInRule);
283
284             rule.setTarget(targetInRule);
285             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
286
287             configPolicy
288                     .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
289                     .add(rule);
290             policyAdapter.setPolicyData(configPolicy);
291
292         } else {
293             PolicyLogger.error("Unsupported data object."
294                     + policyAdapter.getData().getClass().getCanonicalName());
295         }
296         setPreparedToSave(true);
297         return true;
298     }
299
300     // Data required for Advice part is setting here.
301     private AdviceExpressionsType getAdviceExpressions(int version,
302                                                        String fileName) {
303
304         // Policy Config ID Assignment
305         AdviceExpressionsType advices = new AdviceExpressionsType();
306         AdviceExpressionType advice = new AdviceExpressionType();
307         advice.setAdviceId("BRMSRAWID");
308         advice.setAppliesTo(EffectType.PERMIT);
309         // For Configuration
310         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
311         assignment1.setAttributeId("type");
312         assignment1.setCategory(CATEGORY_RESOURCE);
313         assignment1.setIssuer(EMPTY_STRING);
314         AttributeValueType configNameAttributeValue = new AttributeValueType();
315         configNameAttributeValue.setDataType(STRING_DATATYPE);
316         configNameAttributeValue.getContent().add("Configuration");
317         assignment1.setExpression(new ObjectFactory()
318                 .createAttributeValue(configNameAttributeValue));
319         advice.getAttributeAssignmentExpression().add(assignment1);
320
321         // For Config file Url if configurations are provided.
322         // URL ID Assignment
323         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
324         assignment2.setAttributeId("URLID");
325         assignment2.setCategory(CATEGORY_RESOURCE);
326         assignment2.setIssuer(EMPTY_STRING);
327         AttributeValueType AttributeValue = new AttributeValueType();
328         AttributeValue.setDataType(URI_DATATYPE);
329
330         String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
331
332         AttributeValue.getContent().add(content);
333         assignment2.setExpression(new ObjectFactory()
334                 .createAttributeValue(AttributeValue));
335         advice.getAttributeAssignmentExpression().add(assignment2);
336
337         // Policy Name Assignment
338         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
339         assignment3.setAttributeId("PolicyName");
340         assignment3.setCategory(CATEGORY_RESOURCE);
341         assignment3.setIssuer(EMPTY_STRING);
342         AttributeValueType attributeValue3 = new AttributeValueType();
343         attributeValue3.setDataType(STRING_DATATYPE);
344         fileName = FilenameUtils.removeExtension(fileName);
345         fileName = fileName + ".xml";
346         System.out.println(fileName);
347         String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
348         if (EMPTY_STRING.equals(name)) {
349             name = fileName.substring(fileName.lastIndexOf("/") + 1);
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(EMPTY_STRING);
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         // Onap Name Assignment
370         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
371         assignment5.setAttributeId("matching:" + ONAPID);
372         assignment5.setCategory(CATEGORY_RESOURCE);
373         assignment5.setIssuer(EMPTY_STRING);
374         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
375         configNameAttributeValue5.setDataType(STRING_DATATYPE);
376         configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
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(EMPTY_STRING);
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())
399                                     .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).append(",");
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 (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) {
418             String keyField = entry.getKey();
419             advice.getAttributeAssignmentExpression()
420                     .add(createResponseAttributes("key:" + keyField, entry.getValue()));
421         }
422
423         //Risk Attributes
424         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
425         assignment8.setAttributeId("RiskType");
426         assignment8.setCategory(CATEGORY_RESOURCE);
427         assignment8.setIssuer(EMPTY_STRING);
428
429         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
430         configNameAttributeValue8.setDataType(STRING_DATATYPE);
431         configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
432         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
433
434         advice.getAttributeAssignmentExpression().add(assignment8);
435
436         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
437         assignment9.setAttributeId("RiskLevel");
438         assignment9.setCategory(CATEGORY_RESOURCE);
439         assignment9.setIssuer(EMPTY_STRING);
440
441         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
442         configNameAttributeValue9.setDataType(STRING_DATATYPE);
443         configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
444         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
445
446         advice.getAttributeAssignmentExpression().add(assignment9);
447
448         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
449         assignment10.setAttributeId("guard");
450         assignment10.setCategory(CATEGORY_RESOURCE);
451         assignment10.setIssuer(EMPTY_STRING);
452
453         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
454         configNameAttributeValue10.setDataType(STRING_DATATYPE);
455         configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
456         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
457
458         advice.getAttributeAssignmentExpression().add(assignment10);
459
460         AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
461         assignment11.setAttributeId("TTLDate");
462         assignment11.setCategory(CATEGORY_RESOURCE);
463         assignment11.setIssuer(EMPTY_STRING);
464
465         AttributeValueType configNameAttributeValue11 = new AttributeValueType();
466         configNameAttributeValue11.setDataType(STRING_DATATYPE);
467         configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
468         assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
469
470         advice.getAttributeAssignmentExpression().add(assignment11);
471
472         advices.getAdviceExpression().add(advice);
473         return advices;
474     }
475
476     @Override
477     public Object getCorrectPolicyDataObject() {
478         return policyAdapter.getData();
479     }
480
481     private AttributeAssignmentExpressionType createResponseAttributes(String key, String value) {
482         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
483         assignment7.setAttributeId(key);
484         assignment7.setCategory(CATEGORY_RESOURCE);
485         assignment7.setIssuer(EMPTY_STRING);
486         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
487         configNameAttributeValue7.setDataType(STRING_DATATYPE);
488         configNameAttributeValue7.getContent().add(value);
489         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
490         return assignment7;
491     }
492 }