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