Reduce technical debt
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / DecisionPolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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.controller;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.xml.bind.JAXBElement;
32
33 import org.onap.policy.common.logging.flexlogger.FlexLogger;
34 import org.onap.policy.common.logging.flexlogger.Logger;
35 import org.onap.policy.rest.adapter.PolicyRestAdapter;
36 import org.onap.policy.rest.adapter.RainyDayParams;
37 import org.onap.policy.rest.adapter.YAMLParams;
38 import org.onap.policy.rest.jpa.PolicyEntity;
39 import org.onap.portalsdk.core.controller.RestrictedBaseController;
40 import org.springframework.stereotype.Controller;
41 import org.springframework.web.bind.annotation.RequestMapping;
42
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
57
58 @Controller
59 @RequestMapping("/")
60 public class DecisionPolicyController extends RestrictedBaseController {
61         private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
62         
63         public DecisionPolicyController(){
64                 // This constructor is empty
65         }
66
67         protected PolicyRestAdapter policyAdapter = null;
68         private ArrayList<Object> attributeList;
69         private ArrayList<Object> decisionList;
70         private ArrayList<Object>  ruleAlgorithmList;
71         private ArrayList<Object> treatmentList = null;
72         protected LinkedList<Integer> ruleAlgoirthmTracker;
73         public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
74
75         @SuppressWarnings("unchecked")
76         public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
77                 attributeList = new ArrayList<>();
78                 decisionList = new ArrayList<>();
79                 ruleAlgorithmList = new ArrayList<>();
80                 treatmentList = new ArrayList<>();
81                 
82                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
83                         RainyDayParams rainydayParams = new RainyDayParams();
84                         Object policyData = policyAdapter.getPolicyData();
85                         PolicyType policy = (PolicyType) policyData;
86                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
87                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
88                         policyAdapter.setPolicyName(policyNameValue);
89                         String description = "";
90                         try{
91                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
92                         }catch(Exception e){
93                                 policyLogger.info("General error", e);
94                                 description = policy.getDescription();
95                         }
96                         policyAdapter.setPolicyDescription(description);
97                         // Get the target data under policy for Action.
98                         TargetType target = policy.getTarget();
99                         if (target != null) {
100                                 // under target we have AnyOFType
101                                 List<AnyOfType> anyOfList = target.getAnyOf();
102                                 if (anyOfList != null) {
103                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
104                                         while (iterAnyOf.hasNext()) {
105                                                 AnyOfType anyOf = iterAnyOf.next();
106                                                 // Under AntOfType we have AllOfType
107                                                 List<AllOfType> allOfList = anyOf.getAllOf();
108                                                 if (allOfList != null) {
109                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
110                                                         while (iterAllOf.hasNext()) {
111                                                                 AllOfType allOf = iterAllOf.next();
112                                                                 // Under AllOfType we have Mathch.
113                                                                 List<MatchType> matchList = allOf.getMatch();
114                                                                 int index = 0;
115                                                                 if (matchList != null) {
116                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
117                                                                         while (iterMatch.hasNext()) {
118                                                                                 MatchType match = iterMatch.next();
119                                                                                 //
120                                                                                 // Under the match we have attributevalue and
121                                                                                 // attributeDesignator. So,finally down to the actual attribute.
122                                                                                 //
123                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
124                                                                                 String value = (String) attributeValue.getContent().get(0);
125                                         if(value!=null){
126                                             value = value.replaceAll("\\(\\?i\\)", "");
127                                         }
128                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
129                                                                                 String attributeId = designator.getAttributeId();
130                                                                                 // First match in the target is OnapName, so set that value.
131                                                                                 if ("ONAPName".equals(attributeId)) {
132                                                                                         policyAdapter.setOnapName(value);
133                                                                                 }
134                                                                                 // Component attributes are saved under Target here we are fetching  them back.
135                                                                                 // One row is default so we are not adding dynamic component at index 0.
136                                                                                 if (index >= 1) {       
137                                                                                         Map<String, String> attribute = new HashMap<>();
138                                                                                         attribute.put("key", attributeId);
139                                                                                         attribute.put("value", value);
140                                                                                         attributeList.add(attribute);   
141                                                                                 }
142                                                                                 index++;
143                                                                         }
144                                                                 }
145                                                                 policyAdapter.setAttributes(attributeList);
146                                                         }
147                                                 }
148                                         }
149                                         // Setting rainy day attributes to the parameters object if they exist 
150                                         boolean rainy = false;
151                                         if(!attributeList.isEmpty()) {
152                                                 for(int i=0; i<attributeList.size() ; i++){
153                                                         Map<String, String> map = (Map<String,String>)attributeList.get(i);
154                                                         if("WorkStep".equals(map.get("key"))){
155                                                                 rainydayParams.setWorkstep(map.get("value"));
156                                                                 rainy=true;
157                                                         }else if("BB_ID".equals(map.get("key"))){
158                                                                 rainydayParams.setBbid(map.get("value"));
159                                                                 rainy=true;
160                                                         }else if("ServiceType".equals(map.get("key"))){
161                                                                 rainydayParams.setServiceType(map.get("value"));
162                                                                 rainy=true;
163                                                         }else if("VNFType".equals(map.get("key"))){
164                                                                 rainydayParams.setVnfType(map.get("value"));
165                                                                 rainy=true;
166                                                         }
167                                                 }       
168                                         }
169                                         if(rainy){
170                                                 policyAdapter.setRuleProvider("Rainy_Day");
171                                         }
172                                 }
173
174                                 List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
175                                 int index = 0;
176                                 for (Object object : ruleList) {
177                                         if (object instanceof VariableDefinitionType) {
178                                                 VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
179                                                 Map<String, String> settings = new HashMap<>();
180                                                 settings.put("key", variableDefinitionType.getVariableId());
181                                                 JAXBElement<AttributeValueType> attributeValueTypeElement = (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
182                                                 if (attributeValueTypeElement != null) {
183                                                         AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
184                                                         settings.put("value", attributeValueType.getContent().get(0).toString());
185                                                 }
186                                                 decisionList.add(settings);
187                                         } else if (object instanceof RuleType) {
188                                                 // get the condition data under the rule for rule Algorithms.
189                                                 if(((RuleType) object).getEffect().equals(EffectType.DENY)) {
190                                                         if(((RuleType) object).getAdviceExpressions()!=null){
191                                                                 if("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
192                                                                         policyAdapter.setRuleProvider("AAF");
193                                                                         break;
194                                                                 }else if("GUARD_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
195                                                                         policyAdapter.setRuleProvider("GUARD_YAML");
196                                                                 }else if("GUARD_BL_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
197                                                                         policyAdapter.setRuleProvider("GUARD_BL_YAML");
198                                                                 }
199                                                         }else{
200                                                                 policyAdapter.setRuleProvider("Custom");
201                                                         }
202                                                         ConditionType condition = ((RuleType) object).getCondition();
203                                                         if (condition != null) {
204                                                                 ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
205                                                                 decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
206                                                                 ruleAlgoirthmTracker = new LinkedList<>();
207                                                                 if(policyAdapter.getRuleProvider()!=null && ("GUARD_YAML".equals(policyAdapter.getRuleProvider())||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
208                                                                         YAMLParams yamlParams = new YAMLParams();
209                                                                         for(int i=0; i<attributeList.size() ; i++){
210                                                                                 Map<String, String> map = (Map<String,String>)attributeList.get(i);
211                                                                                 if("actor".equals(map.get("key"))){
212                                                                                         yamlParams.setActor(map.get("value"));
213                                                                                 }else if("recipe".equals(map.get("key"))){
214                                                                                         yamlParams.setRecipe(map.get("value"));
215                                                                                 }else if("target".equals(map.get("key"))){
216                                                                                         yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
217                                                                                 }else if("clname".equals(map.get("key"))){
218                                                                                         yamlParams.setClname(map.get("value"));
219                                                                                 }
220                                                                         }
221                                                                         ApplyType apply = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue();
222                                                                         yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString());
223                                                                         yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString());
224                                                                         if("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())){
225                                                                                 apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue();
226                                                                                 Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
227                                                                                 List<String> blackList = new ArrayList<>();
228                                                                                 while(attributes.hasNext()){
229                                                                                         blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString());
230                                                                                 }
231                                                                                 yamlParams.setBlackList(blackList);
232                                                                         }else{
233                                                                                 ApplyType timeWindowSection = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue();
234                                                                                 yamlParams.setLimit(((AttributeValueType)timeWindowSection.getExpression().get(1).getValue()).getContent().get(0).toString());
235                                                                                 String timeWindow = ((AttributeDesignatorType)((ApplyType)timeWindowSection.getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer();
236                                                                                 yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':')+1));
237                                                                                 yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:")+4,timeWindow.lastIndexOf(':')));
238                                                                         }
239                                                                         policyAdapter.setYamlparams(yamlParams);
240                                                                         policyAdapter.setAttributes(new ArrayList<Object>());
241                                                                         policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
242                                                                         break;
243                                                                 }
244                                                                 // Populating Rule Algorithms starting from compound.
245                                                                 prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
246                                                                 policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
247                                                         }
248                                                 } else if(policyAdapter.getRuleProvider()!=null && "Rainy_Day".equals(policyAdapter.getRuleProvider())&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
249                                                         
250                                                         TargetType ruleTarget = ((RuleType) object).getTarget();
251                                                         AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
252                                                         
253                                                         String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().
254                                                                         get(1).getAttributeValue().getContent().get(0).toString();
255                                                         JAXBElement<AttributeValueType> tempTreatmentObj = (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().
256                                                                         get(0).getAttributeAssignmentExpression().get(0).getExpression();
257                                                         String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
258                                                         
259                                                         prePopulateRainyDayTreatments(errorcode, treatment);                                            
260
261                                                 }
262                                         }
263                                 }
264                         }
265                         
266                         rainydayParams.setTreatmentTableChoices(treatmentList);
267                         policyAdapter.setRainyday(rainydayParams);
268                         policyAdapter.setSettings(decisionList);        
269                 }       
270
271         }
272
273         private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
274                 Map<String, String> ruleMap = new HashMap<>();
275                 
276                 ruleMap.put("errorcode", errorcode);
277                 ruleMap.put("treatment", treatment);
278                 treatmentList.add(ruleMap);
279                 
280         }
281         
282         private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List<JAXBElement<?>> jaxbDecisionTypes) {
283                 Map<String, String> ruleMap = new HashMap<>();
284                 ruleMap.put("id", "A" + (index +1));
285                 Map<String, String> dropDownMap = PolicyController.getDropDownMap();
286                 for (String key : dropDownMap.keySet()) {
287                         String keyValue = dropDownMap.get(key);
288                         if (keyValue.equals(decisionApply.getFunctionId())) {
289                                 ruleMap.put("dynamicRuleAlgorithmCombo", key);
290                         }
291                 }
292                 // Populate the key and value fields
293                 if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) {
294                         ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
295                         List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
296                         if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
297                                 AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue();
298                                 ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
299
300                                 // Get from Attribute Value
301                                 AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue();
302                                 String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
303                                 ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
304                         }
305                 } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
306                         VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();  
307                         ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId());
308
309
310                         // Get from Attribute Value
311                         AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
312                         String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
313                         ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
314                 }
315                 ruleAlgorithmList.add(ruleMap);
316         }
317
318         private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) {
319                 boolean isCompoundRule = true;
320                 List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression();
321                 for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
322                         // If There is Attribute Value under Decision Type that means we came to the final child
323                         if (policyLogger.isDebugEnabled()) {
324                                 policyLogger.debug("Prepopulating rule algoirthm: " + index);
325                         }
326                         // Check to see if Attribute Value exists, if yes then it is not a compound rule
327                         if(jaxbElement.getValue() instanceof AttributeValueType) {
328                                 prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes);
329                                 ruleAlgoirthmTracker.addLast(index);
330                                 isCompoundRule = false;
331                                 index++;
332                         } 
333                 }
334                 if (isCompoundRule) {
335                         // As it's compound rule, Get the Apply types
336                         for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
337                                 ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
338                                 index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
339                         }
340                         // Populate combo box
341                         if (policyLogger.isDebugEnabled()) {
342                                 policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
343                         }
344                         Map<String, String> rule = new HashMap<>();
345                         for (String key : PolicyController.getDropDownMap().keySet()) {
346                                 String keyValue = PolicyController.getDropDownMap().get(key);
347                                 if (keyValue.equals(decisionApply.getFunctionId())) {
348                                         rule.put("dynamicRuleAlgorithmCombo", key);
349                                         break;
350                                 }
351                         }
352
353                         rule.put("id", "A" + (index +1));
354                         // Populate Key and values for Compound Rule
355                         rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 ));
356                         ruleAlgoirthmTracker.removeLast();
357                         rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
358                         ruleAlgoirthmTracker.removeLast();
359                         ruleAlgoirthmTracker.addLast(index);
360                         ruleAlgorithmList.add(rule);
361                         index++;
362                 }
363                 
364                 return index;
365         }
366 }