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