Consolidate PolicyRestAdapter setup
[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, 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.std.IdentifierImpl;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.io.PrintWriter;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.nio.charset.Charset;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.ArrayList;
36 import java.util.HashMap;
37 import java.util.Map;
38
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
52
53 import org.apache.commons.io.FilenameUtils;
54 import org.onap.policy.common.logging.eelf.MessageCodes;
55 import org.onap.policy.common.logging.eelf.PolicyLogger;
56 import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
58
59 public class CreateBrmsRawPolicy extends Policy {
60
61     private static final String EMPTY_STRING = "";
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, policyName.lastIndexOf(".xml"));
78         }
79         try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
80             out.println(jsonBody);
81         } catch (Exception e) {
82             PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy",
83                     "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() {
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 ("Config".equals(policyAdapter.getPolicyType())) {
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 configBody = policyAdapter.getConfigBodyData();
174             saveConfigurations(policyName, configBody);
175
176             // Make sure the filename ends with an extension
177             if (!policyName.endsWith(".xml")) {
178                 policyName = policyName + ".xml";
179             }
180
181             PolicyType configPolicy = (PolicyType) policyAdapter.getData();
182
183             configPolicy.setDescription(policyAdapter.getPolicyDescription());
184
185             configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
186
187             AllOfType allOfOne = new AllOfType();
188             String fileName = policyAdapter.getNewFileName();
189             String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
190             if (EMPTY_STRING.equals(name)) {
191                 name = fileName.substring(fileName.lastIndexOf("/") + 1);
192             }
193             allOfOne.getMatch().add(createMatch("PolicyName", name));
194
195             AllOfType allOf = new AllOfType();
196
197             // Match for ONAPName
198             allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
199             allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
200             // Match for riskType
201             allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
202             // Match for riskLevel
203             allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
204             // Match for riskguard
205             allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
206             // Match for ttlDate
207             allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
208             AnyOfType anyOf = new AnyOfType();
209             anyOf.getAllOf().add(allOfOne);
210             anyOf.getAllOf().add(allOf);
211
212             TargetType target = new TargetType();
213             target.getAnyOf().add(anyOf);
214
215             // Adding the target to the policy element
216             configPolicy.setTarget(target);
217
218             RuleType rule = new RuleType();
219             rule.setRuleId(policyAdapter.getRuleID());
220
221             rule.setEffect(EffectType.PERMIT);
222
223             // Create Target in Rule
224             AllOfType allOfInRule = new AllOfType();
225
226             // Creating match for ACCESS in rule target
227             MatchType accessMatch = new MatchType();
228             AttributeValueType accessAttributeValue = new AttributeValueType();
229             accessAttributeValue.setDataType(STRING_DATATYPE);
230             accessAttributeValue.getContent().add("ACCESS");
231             accessMatch.setAttributeValue(accessAttributeValue);
232             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
233             URI accessURI = null;
234             try {
235                 accessURI = new URI(ACTION_ID);
236             } catch (URISyntaxException e) {
237                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy",
238                         "Exception creating ACCESS URI");
239             }
240             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
241             accessAttributeDesignator.setDataType(STRING_DATATYPE);
242             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
243             accessMatch.setAttributeDesignator(accessAttributeDesignator);
244             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
245
246             // Creating Config Match in rule Target
247             MatchType configMatch = new MatchType();
248             AttributeValueType configAttributeValue = new AttributeValueType();
249             configAttributeValue.setDataType(STRING_DATATYPE);
250
251             configAttributeValue.getContent().add("Config");
252
253             configMatch.setAttributeValue(configAttributeValue);
254             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
255             URI configURI = null;
256             try {
257                 configURI = new URI(RESOURCE_ID);
258             } catch (URISyntaxException e) {
259                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy",
260                         "Exception creating Config URI");
261             }
262
263             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
264             configAttributeDesignator.setDataType(STRING_DATATYPE);
265             configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
266             configMatch.setAttributeDesignator(configAttributeDesignator);
267             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
268
269             allOfInRule.getMatch().add(accessMatch);
270             allOfInRule.getMatch().add(configMatch);
271
272             AnyOfType anyOfInRule = new AnyOfType();
273             anyOfInRule.getAllOf().add(allOfInRule);
274
275             TargetType targetInRule = new TargetType();
276             targetInRule.getAnyOf().add(anyOfInRule);
277
278             rule.setTarget(targetInRule);
279             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
280
281             configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
282             policyAdapter.setPolicyData(configPolicy);
283
284         } else {
285             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
286         }
287         setPreparedToSave(true);
288         return true;
289     }
290
291     // Data required for Advice part is setting here.
292     private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
293
294         // Policy Config ID Assignment
295         AdviceExpressionsType advices = new AdviceExpressionsType();
296         AdviceExpressionType advice = new AdviceExpressionType();
297         advice.setAdviceId("BRMSRAWID");
298         advice.setAppliesTo(EffectType.PERMIT);
299         // For Configuration
300         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
301         assignment1.setAttributeId("type");
302         assignment1.setCategory(CATEGORY_RESOURCE);
303         assignment1.setIssuer(EMPTY_STRING);
304         AttributeValueType configNameAttributeValue = new AttributeValueType();
305         configNameAttributeValue.setDataType(STRING_DATATYPE);
306         configNameAttributeValue.getContent().add("Configuration");
307         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
308         advice.getAttributeAssignmentExpression().add(assignment1);
309
310         // For Config file Url if configurations are provided.
311         // URL ID Assignment
312         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
313         assignment2.setAttributeId("URLID");
314         assignment2.setCategory(CATEGORY_RESOURCE);
315         assignment2.setIssuer(EMPTY_STRING);
316         AttributeValueType AttributeValue = new AttributeValueType();
317         AttributeValue.setDataType(URI_DATATYPE);
318
319         String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
320
321         AttributeValue.getContent().add(content);
322         assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
323         advice.getAttributeAssignmentExpression().add(assignment2);
324
325         // Policy Name Assignment
326         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
327         assignment3.setAttributeId("PolicyName");
328         assignment3.setCategory(CATEGORY_RESOURCE);
329         assignment3.setIssuer(EMPTY_STRING);
330         AttributeValueType attributeValue3 = new AttributeValueType();
331         attributeValue3.setDataType(STRING_DATATYPE);
332         fileName = FilenameUtils.removeExtension(fileName);
333         fileName = fileName + ".xml";
334         System.out.println(fileName);
335         String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
336         if (EMPTY_STRING.equals(name)) {
337             name = fileName.substring(fileName.lastIndexOf("/") + 1);
338         }
339         System.out.println(name);
340         attributeValue3.getContent().add(name);
341         assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
342         advice.getAttributeAssignmentExpression().add(assignment3);
343
344         // Version Number Assignment
345         AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
346         assignment4.setAttributeId("VersionNumber");
347         assignment4.setCategory(CATEGORY_RESOURCE);
348         assignment4.setIssuer(EMPTY_STRING);
349         AttributeValueType configNameAttributeValue4 = new AttributeValueType();
350         configNameAttributeValue4.setDataType(STRING_DATATYPE);
351         configNameAttributeValue4.getContent().add(Integer.toString(version));
352         assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
353         advice.getAttributeAssignmentExpression().add(assignment4);
354
355         // Onap Name Assignment
356         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
357         assignment5.setAttributeId("matching:" + ONAPID);
358         assignment5.setCategory(CATEGORY_RESOURCE);
359         assignment5.setIssuer(EMPTY_STRING);
360         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
361         configNameAttributeValue5.setDataType(STRING_DATATYPE);
362         configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
363         assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
364         advice.getAttributeAssignmentExpression().add(assignment5);
365
366         // Config Name Assignment
367         AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
368         assignment6.setAttributeId("matching:" + CONFIGID);
369         assignment6.setCategory(CATEGORY_RESOURCE);
370         assignment6.setIssuer(EMPTY_STRING);
371         AttributeValueType configNameAttributeValue6 = new AttributeValueType();
372         configNameAttributeValue6.setDataType(STRING_DATATYPE);
373         configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
374         assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
375         advice.getAttributeAssignmentExpression().add(assignment6);
376
377         // Adding Controller Information.
378         if (policyAdapter.getBrmsController() != null) {
379             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
380             advice.getAttributeAssignmentExpression().add(createResponseAttributes(
381                     "controller:" + policyAdapter.getBrmsController(),
382                     brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
383         }
384
385         // Adding Dependencies.
386         if (policyAdapter.getBrmsDependency() != null) {
387             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
388             ArrayList<String> dependencies = new ArrayList<>();
389             StringBuilder key = new StringBuilder();
390             for (String dependencyName : policyAdapter.getBrmsDependency()) {
391                 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
392                 key.append(dependencyName).append(",");
393             }
394             advice.getAttributeAssignmentExpression()
395                     .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString()));
396         }
397
398         // Dynamic Field Config Attributes.
399         Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
400         for (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) {
401             String keyField = entry.getKey();
402             advice.getAttributeAssignmentExpression()
403                     .add(createResponseAttributes("key:" + keyField, entry.getValue()));
404         }
405
406         // Risk Attributes
407         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
408         assignment8.setAttributeId("RiskType");
409         assignment8.setCategory(CATEGORY_RESOURCE);
410         assignment8.setIssuer(EMPTY_STRING);
411
412         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
413         configNameAttributeValue8.setDataType(STRING_DATATYPE);
414         configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
415         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
416
417         advice.getAttributeAssignmentExpression().add(assignment8);
418
419         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
420         assignment9.setAttributeId("RiskLevel");
421         assignment9.setCategory(CATEGORY_RESOURCE);
422         assignment9.setIssuer(EMPTY_STRING);
423
424         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
425         configNameAttributeValue9.setDataType(STRING_DATATYPE);
426         configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
427         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
428
429         advice.getAttributeAssignmentExpression().add(assignment9);
430
431         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
432         assignment10.setAttributeId("guard");
433         assignment10.setCategory(CATEGORY_RESOURCE);
434         assignment10.setIssuer(EMPTY_STRING);
435
436         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
437         configNameAttributeValue10.setDataType(STRING_DATATYPE);
438         configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
439         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
440
441         advice.getAttributeAssignmentExpression().add(assignment10);
442
443         AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
444         assignment11.setAttributeId("TTLDate");
445         assignment11.setCategory(CATEGORY_RESOURCE);
446         assignment11.setIssuer(EMPTY_STRING);
447
448         AttributeValueType configNameAttributeValue11 = new AttributeValueType();
449         configNameAttributeValue11.setDataType(STRING_DATATYPE);
450         configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
451         assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
452
453         advice.getAttributeAssignmentExpression().add(assignment11);
454
455         advices.getAdviceExpression().add(advice);
456         return advices;
457     }
458
459     @Override
460     public Object getCorrectPolicyDataObject() {
461         return policyAdapter.getData();
462     }
463
464     private AttributeAssignmentExpressionType createResponseAttributes(String key, String value) {
465         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
466         assignment7.setAttributeId(key);
467         assignment7.setCategory(CATEGORY_RESOURCE);
468         assignment7.setIssuer(EMPTY_STRING);
469         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
470         configNameAttributeValue7.setDataType(STRING_DATATYPE);
471         configNameAttributeValue7.getContent().add(value);
472         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
473         return assignment7;
474     }
475 }