Format java POLICY-SDK-APP
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / ActionPolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Bell Canada
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controller;
23
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30
31 import javax.xml.bind.JAXBElement;
32
33 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
34 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
46
47 import org.onap.policy.common.logging.flexlogger.FlexLogger;
48 import org.onap.policy.common.logging.flexlogger.Logger;
49 import org.onap.policy.rest.adapter.PolicyRestAdapter;
50 import org.onap.portalsdk.core.controller.RestrictedBaseController;
51 import org.springframework.stereotype.Controller;
52 import org.springframework.web.bind.annotation.RequestMapping;
53
54 @Controller
55 @RequestMapping({"/"})
56 public class ActionPolicyController extends RestrictedBaseController {
57     private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class);
58     private static final String PERFORMER_ATTRIBUTE_ID = "performer";
59     private static final String DYNAMIC_RULE_ALGORITHM_FIELD_1 = "dynamicRuleAlgorithmField1";
60     private static final String DYNAMIC_RULE_ALGORITHM_FIELD_2 = "dynamicRuleAlgorithmField2";
61     private LinkedList<Integer> ruleAlgorithmTracker;
62     private Map<String, String> performer = new HashMap<>();
63     private List<Object> ruleAlgorithmList;
64
65     public ActionPolicyController() {
66         // Default Constructor
67     }
68
69     public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) {
70         ruleAlgorithmList = new ArrayList<>();
71         performer.put("PDP", "PDPAction");
72         performer.put("PEP", "PEPAction");
73
74         if (policyAdapter.getPolicyData() instanceof PolicyType) {
75             PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
76
77             // 1. Set policy-name, policy-filename and description to Policy Adapter
78             setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy);
79
80             // 2a. Get the target data under policy for Action.
81             TargetType target = policy.getTarget();
82             if (target == null) {
83                 return;
84             }
85
86             // 2b. Set attributes to Policy Adapter
87             setPolicyAdapterAttributes(policyAdapter, target.getAnyOf());
88
89             List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
90             // Under rule we have Condition and obligation.
91             for (Object o : ruleList) {
92                 if (!(o instanceof RuleType)) {
93                     continue;
94                 }
95                 // 3. Set rule-algorithm choices to Policy Adapter
96                 setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o);
97
98                 // 4a. Get the Obligation data under the rule for Form elements.
99                 ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
100
101                 // 4b. Set action attribute-value and action-performer to Policy Adapter
102                 setPolicyAdapterActionData(policyAdapter, obligations);
103             }
104         }
105     }
106
107     private void setPolicyAdapterActionData(PolicyRestAdapter policyAdapter, ObligationExpressionsType obligations) {
108         if (obligations == null) {
109             return;
110         }
111         // Under the obligationExpressions we have obligationExpression.
112         List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
113         if (obligationList == null) {
114             return;
115         }
116         for (ObligationExpressionType obligation : obligationList) {
117             policyAdapter.setActionAttributeValue(obligation.getObligationId());
118             // Under the obligationExpression we have attributeAssignmentExpression.
119             List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList =
120                     obligation.getAttributeAssignmentExpression();
121             if (attributeAssignmentExpressionList == null) {
122                 continue;
123             }
124             for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) {
125                 String attributeID = attributeAssignmentExpression.getAttributeId();
126                 AttributeValueType attributeValue =
127                         (AttributeValueType) attributeAssignmentExpression.getExpression().getValue();
128                 if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) {
129                     continue;
130                 }
131                 performer.forEach((key, keyValue) -> {
132                     if (keyValue.equals(attributeValue.getContent().get(0))) {
133                         policyAdapter.setActionPerformer(key);
134                     }
135                 });
136             }
137         }
138     }
139
140     private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) {
141         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
142         String policyNameValue =
143                 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
144         policyAdapter.setPolicyName(policyNameValue);
145         String description;
146         try {
147             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
148         } catch (Exception e) {
149             LOGGER.error("Error while collecting the description tag in ActionPolicy " + policyNameValue, e);
150             description = policy.getDescription();
151         }
152         policyAdapter.setPolicyDescription(description);
153     }
154
155     private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) {
156         ConditionType condition = o.getCondition();
157         if (condition != null) {
158             int index = 0;
159             ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
160             ruleAlgorithmTracker = new LinkedList<>();
161             // Populating Rule Algorithms starting from compound.
162             prePopulateCompoundRuleAlgorithm(index, actionApply);
163         }
164         policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
165     }
166
167     private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
168         List<Object> attributeList = new ArrayList<>();
169         if (anyOfList == null) {
170             return;
171         }
172         // under target we have AnyOFType
173         for (AnyOfType anyOf : anyOfList) {
174             // Under AntOfType we have AllOfType
175             List<AllOfType> allOfList = anyOf.getAllOf();
176             if (allOfList == null) {
177                 continue;
178             }
179             // Under AllOfType we have Match.
180             for (AllOfType allOfType : allOfList) {
181                 List<MatchType> matchList = allOfType.getMatch();
182                 if (matchList != null) {
183                     //
184                     // Under the match we have attributeValue and
185                     // attributeDesignator. So,finally down to the actual attribute.
186                     //
187                     // Component attributes are saved under Target here we are fetching them back.
188                     // One row is default so we are not adding dynamic component at index 0.
189                     matchList.forEach(match -> {
190                         AttributeValueType attributeValue = match.getAttributeValue();
191                         String value = (String) attributeValue.getContent().get(0);
192                         AttributeDesignatorType designator = match.getAttributeDesignator();
193                         String attributeId = designator.getAttributeId();
194                         Map<String, String> attribute = new HashMap<>();
195                         attribute.put("key", attributeId);
196                         attribute.put("value", value);
197                         attributeList.add(attribute);
198                     });
199                 }
200                 policyAdapter.setAttributes(attributeList);
201             }
202         }
203     }
204
205     private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) {
206         boolean isCompoundRule = true;
207         List<JAXBElement<?>> jaxbActionTypes = actionApply.getExpression();
208         for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
209             // If There is Attribute Value under Action Type that means we came to the final child
210             if (LOGGER.isDebugEnabled()) {
211                 LOGGER.debug("Prepopulating rule algoirthm: " + index);
212             }
213             // Check to see if Attribute Value exists, if yes then it is not a compound rule
214             if (jaxbElement.getValue() instanceof AttributeValueType) {
215                 prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes);
216                 ruleAlgorithmTracker.addLast(index);
217                 isCompoundRule = false;
218                 index++;
219             }
220         }
221         if (isCompoundRule) {
222             // As it's compound rule, Get the Apply types
223             for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
224                 ApplyType innerActionApply = (ApplyType) jaxbElement.getValue();
225                 index = prePopulateCompoundRuleAlgorithm(index, innerActionApply);
226             }
227             // Populate combo box
228             if (LOGGER.isDebugEnabled()) {
229                 LOGGER.debug("Prepopulating Compound rule algorithm: " + index);
230             }
231             Map<String, String> rule = new HashMap<>();
232             for (String key : PolicyController.getDropDownMap().keySet()) {
233                 String keyValue = PolicyController.getDropDownMap().get(key);
234                 if (keyValue.equals(actionApply.getFunctionId())) {
235                     rule.put("dynamicRuleAlgorithmCombo", key);
236                 }
237             }
238             rule.put("id", "A" + (index + 1));
239             // Populate Key and values for Compound Rule
240             rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1));
241             ruleAlgorithmTracker.removeLast();
242             rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1));
243             ruleAlgorithmTracker.removeLast();
244             ruleAlgorithmTracker.addLast(index);
245             ruleAlgorithmList.add(rule);
246             index++;
247         }
248         return index;
249     }
250
251     private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) {
252         Map<String, String> ruleMap = new HashMap<>();
253         ruleMap.put("id", "A" + (index + 1));
254         // Populate combo box
255         Map<String, String> dropDownMap = PolicyController.getDropDownMap();
256         for (Entry<String, String> entry : dropDownMap.entrySet()) {
257             if (entry.getValue().equals(actionApply.getFunctionId())) {
258                 ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
259             }
260         }
261         // Populate the key and value fields
262         // Rule Attribute added as key
263         if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) {
264             // Get from Attribute Designator
265             ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue();
266             List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
267             AttributeDesignatorType attributeDesignator =
268                     (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
269             ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
270
271             // Get from Attribute Value
272             AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue();
273             String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
274             ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue);
275         }
276         // Rule Attribute added as value
277         else if ((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType) {
278             AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue();
279             String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
280             ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue);
281
282             ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
283             List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
284             AttributeDesignatorType attributeDesignator =
285                     (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
286             ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
287         }
288         ruleAlgorithmList.add(ruleMap);
289     }
290 }