Consolidate PolicyRestAdapter setup
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / ActionPolicy.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
25 import java.io.BufferedWriter;
26 import java.io.File;
27 import java.io.FileWriter;
28 import java.io.IOException;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.HashMap;
32 import java.util.LinkedList;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Objects;
36
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
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.onap.policy.common.logging.eelf.MessageCodes;
54 import org.onap.policy.common.logging.eelf.PolicyLogger;
55 import org.onap.policy.common.logging.flexlogger.FlexLogger;
56 import org.onap.policy.common.logging.flexlogger.Logger;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
58 import org.onap.policy.rest.dao.CommonClassDao;
59 import org.onap.policy.rest.jpa.FunctionDefinition;
60 import org.onap.policy.xacml.api.XACMLErrorConstants;
61
62 public class ActionPolicy extends Policy {
63
64     private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicy.class);
65
66     public static final String JSON_CONFIG = "JSON";
67
68     public static final String PDP_ACTION = "PDP";
69     public static final String PEP_ACTION = "PEP";
70     public static final String TYPE_ACTION = "REST";
71
72     public static final String GET_METHOD = "GET";
73     public static final String PUT_METHOD = "PUT";
74     public static final String POST_METHOD = "POST";
75
76     public static final String PERFORMER_ATTRIBUTEID = "performer";
77     public static final String TYPE_ATTRIBUTEID = "type";
78     public static final String METHOD_ATTRIBUTEID = "method";
79     public static final String HEADERS_ATTRIBUTEID = "headers";
80     public static final String URL_ATTRIBUTEID = "url";
81     public static final String BODY_ATTRIBUTEID = "body";
82
83     List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
84     List<String> dynamicFieldFunctionRuleAlgorithms = new LinkedList<>();
85     List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
86     List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
87
88     private CommonClassDao commonClassDao;
89
90     private static boolean isAttribute = false;
91
92     private static synchronized boolean getAttribute() {
93         return isAttribute;
94
95     }
96
97     public ActionPolicy() {
98         super();
99     }
100
101     public ActionPolicy(PolicyRestAdapter policyAdapter, CommonClassDao commonClassDao) {
102         this.policyAdapter = policyAdapter;
103         this.commonClassDao = commonClassDao;
104     }
105
106     @Override
107     public Map<String, String> savePolicies() throws PAPException {
108
109         Map<String, String> successMap = new HashMap<>();
110         if (isPolicyExists()) {
111             successMap.put("EXISTS", "This Policy already exist on the PAP");
112             return successMap;
113         }
114
115         if (!ActionPolicy.getAttribute()) {
116             successMap.put("invalidAttribute", "Action Attrbute was not in the database.");
117             return successMap;
118         }
119
120         if (!isPreparedToSave()) {
121             // Prep and configure the policy for saving
122             prepareToSave();
123         }
124
125         // Until here we prepared the data and here calling the method to create xml.
126         Path newPolicyPath = null;
127         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
128         successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
129         return successMap;
130     }
131
132     // This is the method for preparing the policy for saving. We have broken it out
133     // separately because the fully configured policy is used for multiple things
134     @Override
135     public boolean prepareToSave() throws PAPException {
136
137         if (isPreparedToSave()) {
138             // we have already done this
139             return true;
140         }
141
142         int version = 0;
143         String policyID = policyAdapter.getPolicyID();
144         version = policyAdapter.getHighestVersion();
145
146         // Create the Instance for pojo, PolicyType object is used in marshalling.
147         if (policyAdapter.getPolicyType().equals("Action")) {
148             PolicyType policyConfig = new PolicyType();
149
150             policyConfig.setVersion(Integer.toString(version));
151             policyConfig.setPolicyId(policyID);
152             policyConfig.setTarget(new TargetType());
153             policyAdapter.setData(policyConfig);
154         }
155
156         policyName = policyAdapter.getNewFileName();
157
158         if (policyAdapter.getData() != null) {
159             // Action body is optional so checking value provided or not
160             String comboDictValue = policyAdapter.getActionAttribute();
161             String actionBody = policyAdapter.getActionBody();
162             setAttribute(false);
163
164             // if actionBody is null or empty then we know the ActionAttribute in the request does not exist in the
165             // dictionary
166             if (!(actionBody == null || "".equals(actionBody))) {
167                 saveActionBody(policyName, actionBody);
168                 setAttribute(true);
169             } else {
170                 if (!getAttribute()) {
171                     LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue
172                             + " in the ActionPolicyDict table.");
173                     return false;
174                 }
175             }
176
177             PolicyType actionPolicy = (PolicyType) policyAdapter.getData();
178             actionPolicy.setDescription(policyAdapter.getPolicyDescription());
179             actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
180
181             AllOfType allOf = new AllOfType();
182
183             Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
184
185             // If there is any dynamic field attributes create the matches here
186             for (String keyField : dynamicFieldComponentAttributes.keySet()) {
187                 String key = keyField;
188                 String value = dynamicFieldComponentAttributes.get(key);
189                 MatchType dynamicMatch = createDynamicMatch(key, value);
190                 allOf.getMatch().add(dynamicMatch);
191             }
192
193             AnyOfType anyOf = new AnyOfType();
194             anyOf.getAllOf().add(allOf);
195
196             TargetType target = new TargetType();
197             target.getAnyOf().add(anyOf);
198
199             // Adding the target to the policy element
200             actionPolicy.setTarget(target);
201
202             RuleType rule = new RuleType();
203             rule.setRuleId(policyAdapter.getRuleID());
204
205             rule.setEffect(EffectType.PERMIT);
206             rule.setTarget(new TargetType());
207
208             dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
209             dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
210             dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
211             dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
212
213             // Rule attributes are optional and dynamic so check and add them to condition.
214             if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
215                 boolean isCompound = false;
216                 ConditionType condition = new ConditionType();
217                 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
218
219                 for (String labelAttr : dynamicLabelRuleAlgorithms) {
220                     // if the rule algorithm as a label means it is a compound
221                     if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
222                         ApplyType actionApply = new ApplyType();
223
224                         String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index);
225                         String value1 = dynamicFieldOneRuleAlgorithms.get(index);
226                         String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
227                         actionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
228                         actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
229                         actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
230                         condition.setExpression(new ObjectFactory().createApply(actionApply));
231                         isCompound = true;
232                     }
233                 }
234                 // if rule algorithm not a compound
235                 if (!isCompound) {
236                     condition.setExpression(new ObjectFactory()
237                             .createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index))));
238                 }
239                 rule.setCondition(condition);
240             }
241             // set the obligations to rule
242             rule.setObligationExpressions(getObligationExpressions());
243             actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
244             policyAdapter.setPolicyData(actionPolicy);
245         } else {
246             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."
247                     + Objects.requireNonNull(policyAdapter.getData()).getClass().getCanonicalName());
248         }
249
250         setPreparedToSave(true);
251         return true;
252     }
253
254     private static synchronized void setAttribute(boolean b) {
255         isAttribute = b;
256     }
257
258     // Saving the json Configurations file if exists at server location for action policy.
259     private void saveActionBody(String policyName, String actionBodyData) {
260         if (policyName.endsWith(".xml")) {
261             policyName = policyName.replace(".xml", "");
262         }
263         File file = new File(ACTION_HOME + File.separator + policyName + ".json");
264         try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()))) {
265             bw.write(actionBodyData);
266             if (LOGGER.isInfoEnabled()) {
267                 LOGGER.info("Action Body is succesfully saved at " + file.getAbsolutePath());
268             }
269         } catch (IOException e) {
270             LOGGER.error("Exception Occured" + e);
271         }
272     }
273
274     // Data required for obligation part is setting here.
275     private ObligationExpressionsType getObligationExpressions() {
276         ObligationExpressionsType obligations = new ObligationExpressionsType();
277
278         ObligationExpressionType obligation = new ObligationExpressionType();
279         String comboDictValue = policyAdapter.getActionAttribute();
280         obligation.setObligationId(comboDictValue);
281         obligation.setFulfillOn(EffectType.PERMIT);
282
283         // Add Action Assignment:
284         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
285         assignment1.setAttributeId(PERFORMER_ATTRIBUTEID);
286         assignment1.setCategory(CATEGORY_RECIPIENT_SUBJECT);
287
288         AttributeValueType actionNameAttributeValue = new AttributeValueType();
289         actionNameAttributeValue.setDataType(STRING_DATATYPE);
290         actionNameAttributeValue.getContent().add(performer.get(policyAdapter.getActionPerformer()));
291
292         assignment1.setExpression(new ObjectFactory().createAttributeValue(actionNameAttributeValue));
293         obligation.getAttributeAssignmentExpression().add(assignment1);
294
295         // Add Type Assignment:
296         AttributeAssignmentExpressionType assignmentType = new AttributeAssignmentExpressionType();
297         assignmentType.setAttributeId(TYPE_ATTRIBUTEID);
298         assignmentType.setCategory(CATEGORY_RESOURCE);
299
300         AttributeValueType typeAttributeValue = new AttributeValueType();
301         typeAttributeValue.setDataType(STRING_DATATYPE);
302         String actionDictType = policyAdapter.getActionDictType();
303         typeAttributeValue.getContent().add(actionDictType);
304
305         assignmentType.setExpression(new ObjectFactory().createAttributeValue(typeAttributeValue));
306         obligation.getAttributeAssignmentExpression().add(assignmentType);
307
308         // Add Rest_URL Assignment:
309         AttributeAssignmentExpressionType assignmentURL = new AttributeAssignmentExpressionType();
310         assignmentURL.setAttributeId(URL_ATTRIBUTEID);
311         assignmentURL.setCategory(CATEGORY_RESOURCE);
312
313         AttributeValueType actionURLAttributeValue = new AttributeValueType();
314         actionURLAttributeValue.setDataType(URI_DATATYPE);
315         String actionDictUrl = policyAdapter.getActionDictUrl();
316         actionURLAttributeValue.getContent().add(actionDictUrl);
317
318         assignmentURL.setExpression(new ObjectFactory().createAttributeValue(actionURLAttributeValue));
319         obligation.getAttributeAssignmentExpression().add(assignmentURL);
320
321         // Add Method Assignment:
322         AttributeAssignmentExpressionType assignmentMethod = new AttributeAssignmentExpressionType();
323         assignmentMethod.setAttributeId(METHOD_ATTRIBUTEID);
324         assignmentMethod.setCategory(CATEGORY_RESOURCE);
325
326         AttributeValueType methodAttributeValue = new AttributeValueType();
327         methodAttributeValue.setDataType(STRING_DATATYPE);
328         String actionDictMethod = policyAdapter.getActionDictMethod();
329         methodAttributeValue.getContent().add(actionDictMethod);
330
331         assignmentMethod.setExpression(new ObjectFactory().createAttributeValue(methodAttributeValue));
332         obligation.getAttributeAssignmentExpression().add(assignmentMethod);
333
334         // Add JSON_URL Assignment:
335         String actionBody = policyAdapter.getActionBody();
336         if (actionBody != null) {
337             AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType();
338             assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID);
339             assignmentJsonURL.setCategory(CATEGORY_RESOURCE);
340
341             AttributeValueType jsonURLAttributeValue = new AttributeValueType();
342             jsonURLAttributeValue.setDataType(URI_DATATYPE);
343             jsonURLAttributeValue.getContent().add(CONFIG_URL + "/Action/" + policyName + ".json");
344
345             assignmentJsonURL.setExpression(new ObjectFactory().createAttributeValue(jsonURLAttributeValue));
346             obligation.getAttributeAssignmentExpression().add(assignmentJsonURL);
347         }
348
349         String headerVal = policyAdapter.getActionDictHeader();
350         if (headerVal != null && !headerVal.trim().isEmpty()) {
351             // parse it on : to get number of headers
352             String[] result = headerVal.split(":");
353             for (String eachString : result) {
354                 // parse each value on =
355                 String[] textFieldVals = eachString.split("=");
356                 obligation.getAttributeAssignmentExpression()
357                         .add(addDynamicHeaders(textFieldVals[0], textFieldVals[1]));
358             }
359         }
360
361         obligations.getObligationExpression().add(obligation);
362         return obligations;
363     }
364
365     // if compound setting the inner apply here
366     protected ApplyType getInnerActionApply(String value1Label) {
367         ApplyType actionApply = new ApplyType();
368         int index = 0;
369         // check the index for the label.
370         for (String labelAttr : dynamicLabelRuleAlgorithms) {
371             if (labelAttr.equals(value1Label)) {
372                 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
373                 // check if the row contains label again
374                 for (String labelValue : dynamicLabelRuleAlgorithms) {
375                     if (labelValue.equals(value1)) {
376                         return getCompoundApply(index);
377                     }
378                 }
379
380                 // Getting the values from the form.
381                 String functionKey = dynamicFieldFunctionRuleAlgorithms.get(index);
382                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
383                 actionApply.setFunctionId(getFunctionDefinitionId(functionKey));
384                 // if two text field are rule attributes.
385                 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
386                     ApplyType innerActionApply1 = new ApplyType();
387                     ApplyType innerActionApply2 = new ApplyType();
388                     AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
389                     AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
390                     // If selected function is Integer function set integer functionID
391                     if (functionKey.toLowerCase().contains("integer")) {
392                         innerActionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
393                         innerActionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
394                         attributeDesignator1.setDataType(INTEGER_DATATYPE);
395                         attributeDesignator2.setDataType(INTEGER_DATATYPE);
396                     } else {
397                         // If selected function is not a Integer function
398                         // set String functionID
399                         innerActionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
400                         innerActionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
401                         attributeDesignator1.setDataType(STRING_DATATYPE);
402                         attributeDesignator2.setDataType(STRING_DATATYPE);
403                     }
404                     attributeDesignator1.setCategory(CATEGORY_RESOURCE);
405                     attributeDesignator2.setCategory(CATEGORY_RESOURCE);
406
407                     // Here set actual field values
408                     attributeDesignator1
409                             .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
410                     attributeDesignator2
411                             .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
412
413                     innerActionApply1.getExpression()
414                             .add(new ObjectFactory().createAttributeDesignator(attributeDesignator1));
415                     innerActionApply2.getExpression()
416                             .add(new ObjectFactory().createAttributeDesignator(attributeDesignator2));
417
418                     actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1));
419                     actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2));
420
421                 } else {// if either of one text field is rule attribute.
422                     ApplyType innerActionApply = new ApplyType();
423                     AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
424                     AttributeValueType actionConditionAttributeValue = new AttributeValueType();
425
426                     if (functionKey.toLowerCase().contains("integer")) {
427                         innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
428                         actionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
429                         attributeDesignator.setDataType(INTEGER_DATATYPE);
430                     } else {
431                         innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
432                         actionConditionAttributeValue.setDataType(STRING_DATATYPE);
433                         attributeDesignator.setDataType(STRING_DATATYPE);
434                     }
435
436                     String attributeId = null;
437                     String attributeValue = null;
438
439                     // Find which textField has rule attribute and set it as
440                     attributeId = value1;
441                     attributeValue = value2;
442
443                     if (attributeId != null) {
444                         attributeDesignator.setCategory(CATEGORY_RESOURCE);
445                         attributeDesignator.setAttributeId(attributeId);
446                     }
447                     actionConditionAttributeValue.getContent().add(attributeValue);
448                     innerActionApply.getExpression()
449                             .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
450                     // Decide the order of element based the values.
451                     if (attributeId.equals(value1)) {
452                         actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
453                         actionApply.getExpression()
454                                 .add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
455                     } else {
456                         actionApply.getExpression()
457                                 .add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
458                         actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
459                     }
460                 }
461             }
462             index++;
463         }
464         return actionApply;
465     }
466
467     // if the rule algorithm is multiple compound one setting the apply
468     protected ApplyType getCompoundApply(int index) {
469         ApplyType actionApply = new ApplyType();
470         String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index);
471         String value1 = dynamicFieldOneRuleAlgorithms.get(index);
472         String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
473         actionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
474         actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
475         actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
476         return actionApply;
477     }
478
479     // Adding the dynamic headers if any
480     private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) {
481         AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType();
482         assignmentHeaders.setAttributeId("headers:" + header);
483         assignmentHeaders.setCategory(CATEGORY_RESOURCE);
484
485         AttributeValueType headersAttributeValue = new AttributeValueType();
486         headersAttributeValue.setDataType(STRING_DATATYPE);
487         headersAttributeValue.getContent().add(value);
488
489         assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue));
490         return assignmentHeaders;
491     }
492
493     @Override
494     public Object getCorrectPolicyDataObject() {
495         return policyAdapter.getPolicyData();
496     }
497
498     public String getFunctionDefinitionId(String key) {
499         FunctionDefinition object =
500                 (FunctionDefinition) commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", key);
501         if (object != null) {
502             return object.getXacmlid();
503         }
504         return null;
505     }
506
507 }