Policy TestSuite Enabled
[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.YAMLParams;
36 import org.openecomp.policy.rest.jpa.PolicyEntity;
37 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
38 import org.springframework.stereotype.Controller;
39 import org.springframework.web.bind.annotation.RequestMapping;
40
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
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 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
54
55 @Controller
56 @RequestMapping("/")
57 public class DecisionPolicyController extends RestrictedBaseController {
58         private static final Logger logger = FlexLogger.getLogger(DecisionPolicyController.class);
59         
60         public DecisionPolicyController(){}
61
62         protected PolicyRestAdapter policyAdapter = null;
63         private ArrayList<Object> attributeList;
64         private ArrayList<Object> decisionList;
65         private ArrayList<Object>  ruleAlgorithmList;
66         protected LinkedList<Integer> ruleAlgoirthmTracker;
67         public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
68
69         @SuppressWarnings("unchecked")
70         public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
71                 attributeList = new ArrayList<Object>();
72                 decisionList = new ArrayList<Object>();
73                 ruleAlgorithmList = new ArrayList<Object>();
74                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
75                         Object policyData = policyAdapter.getPolicyData();
76                         PolicyType policy = (PolicyType) policyData;
77                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
78                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1);
79                         policyAdapter.setPolicyName(policyNameValue);
80                         String description = "";
81                         try{
82                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
83                         }catch(Exception e){
84                                 description = policy.getDescription();
85                         }
86                         policyAdapter.setPolicyDescription(description);
87                         // Get the target data under policy for Action.
88                         TargetType target = policy.getTarget();
89                         if (target != null) {
90                                 // under target we have AnyOFType
91                                 List<AnyOfType> anyOfList = target.getAnyOf();
92                                 if (anyOfList != null) {
93                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
94                                         while (iterAnyOf.hasNext()) {
95                                                 AnyOfType anyOf = iterAnyOf.next();
96                                                 // Under AntOfType we have AllOfType
97                                                 List<AllOfType> allOfList = anyOf.getAllOf();
98                                                 if (allOfList != null) {
99                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
100                                                         while (iterAllOf.hasNext()) {
101                                                                 AllOfType allOf = iterAllOf.next();
102                                                                 // Under AllOfType we have Mathch.
103                                                                 List<MatchType> matchList = allOf.getMatch();
104                                                                 int index = 0;
105                                                                 if (matchList != null) {
106                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
107                                                                         while (iterMatch.hasNext()) {
108                                                                                 MatchType match = iterMatch.next();
109                                                                                 //
110                                                                                 // Under the match we have attributevalue and
111                                                                                 // attributeDesignator. So,finally down to the actual attribute.
112                                                                                 //
113                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
114                                                                                 String value = (String) attributeValue.getContent().get(0);
115                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
116                                                                                 String attributeId = designator.getAttributeId();
117                                                                                 // First match in the target is EcompName, so set that value.
118                                                                                 if (attributeId.equals("ECOMPName")) {
119                                                                                         policyAdapter.setEcompName(value);
120                                                                                 }
121                                                                                 // Component attributes are saved under Target here we are fetching  them back.
122                                                                                 // One row is default so we are not adding dynamic component at index 0.
123                                                                                 if (index >= 1) {       
124                                                                                         Map<String, String> attribute = new HashMap<String, String>();
125                                                                                         attribute.put("key", attributeId);
126                                                                                         attribute.put("value", value);
127                                                                                         attributeList.add(attribute);   
128                                                                                 }
129                                                                                 index++;
130                                                                         }
131                                                                 }
132                                                                 policyAdapter.setAttributes(attributeList);
133                                                         }
134                                                 }
135                                         }
136                                 }
137
138                                 List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
139                                 int index = 0;
140                                 for (Object object : ruleList) {
141                                         if (object instanceof VariableDefinitionType) {
142                                                 VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
143                                                 Map<String, String> settings = new HashMap<String, String>();
144                                                 settings.put("key", variableDefinitionType.getVariableId());
145                                                 JAXBElement<AttributeValueType> attributeValueTypeElement = (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
146                                                 if (attributeValueTypeElement != null) {
147                                                         AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
148                                                         settings.put("value", attributeValueType.getContent().get(0).toString());
149                                                 }
150                                                 decisionList.add(settings);
151                                         } else if (object instanceof RuleType) {
152                                                 // get the condition data under the rule for rule Algorithms.
153                                                 if(((RuleType) object).getEffect().equals(EffectType.DENY)) {
154                                                         if(((RuleType) object).getAdviceExpressions()!=null){
155                                                                 if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){
156                                                                         policyAdapter.setRuleProvider("AAF");
157                                                                         break;
158                                                                 }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){
159                                                                         policyAdapter.setRuleProvider("GUARD_YAML");
160                                                                 }
161                                                         }else{
162                                                                 policyAdapter.setRuleProvider("Custom");
163                                                         }
164                                                         ConditionType condition = ((RuleType) object).getCondition();
165                                                         if (condition != null) {
166                                                                 ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
167                                                                 decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
168                                                                 ruleAlgoirthmTracker = new LinkedList<Integer>();
169                                                                 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("GUARD_YAML")){
170                                                                         YAMLParams yamlParams = new YAMLParams();
171                                                                         for(int i=0; i<attributeList.size() ; i++){
172                                                                                 Map<String, String> map = (Map<String,String>)attributeList.get(i);
173                                                                                 if(map.get("key").equals("actor")){
174                                                                                         yamlParams.setActor(map.get("value"));
175                                                                                 }else if(map.get("key").equals("recipe")){
176                                                                                         yamlParams.setRecipe(map.get("value"));
177                                                                                 }
178                                                                         }
179                                                                         ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue());
180                                                                         yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString());
181                                                                         yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString());
182                                                                         yamlParams.setLimit(((AttributeValueType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(1).getValue()).getContent().get(0).toString());
183                                                                         String timeWindow = ((AttributeDesignatorType)((ApplyType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer();
184                                                                         yamlParams.setTimeWindow(timeWindow.substring(timeWindow.lastIndexOf(":")+1));
185                                                                         policyAdapter.setYamlparams(yamlParams);
186                                                                         policyAdapter.setAttributes(new ArrayList<Object>());
187                                                                         policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
188                                                                         break;
189                                                                 }
190                                                                 // Populating Rule Algorithms starting from compound.
191                                                                 prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
192                                                                 policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
193                                                         }
194                                                 }
195                                         }
196                                 }
197                         }
198                         policyAdapter.setSettings(decisionList);        
199                 }       
200
201         }
202
203         private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List<JAXBElement<?>> jaxbDecisionTypes) {
204                 Map<String, String> ruleMap = new HashMap<String, String>();
205                 ruleMap.put("id", "A" + (index +1));
206                 Map<String, String> dropDownMap = PolicyController.getDropDownMap();
207                 for (String key : dropDownMap.keySet()) {
208                         String keyValue = dropDownMap.get(key);
209                         if (keyValue.equals(decisionApply.getFunctionId())) {
210                                 ruleMap.put("dynamicRuleAlgorithmCombo", key);
211                         }
212                 }
213                 // Populate the key and value fields
214                 if (((jaxbDecisionTypes.get(0).getValue()) instanceof AttributeValueType)) {
215                         ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
216                         List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
217                         if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
218                                 AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue();
219                                 ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
220
221                                 // Get from Attribute Value
222                                 AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue();
223                                 String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
224                                 ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
225                         }
226                 } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
227                         VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();  
228                         ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId());
229
230
231                         // Get from Attribute Value
232                         AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
233                         String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
234                         ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
235                 }
236                 ruleAlgorithmList.add(ruleMap);
237         }
238
239         private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) {
240                 boolean isCompoundRule = true;
241                 List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression();
242                 for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
243                         // If There is Attribute Value under Decision Type that means we came to the final child
244                         if (logger.isDebugEnabled()) {
245                                 logger.debug("Prepopulating rule algoirthm: " + index);
246                         }
247                         // Check to see if Attribute Value exists, if yes then it is not a compound rule
248                         if(jaxbElement.getValue() instanceof AttributeValueType) {
249                                 prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes);
250                                 ruleAlgoirthmTracker.addLast(index);
251                                 isCompoundRule = false;
252                                 index++;
253                         } 
254                 }
255                 if (isCompoundRule) {
256                         // As it's compound rule, Get the Apply types
257                         for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
258                                 ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
259                                 index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
260                         }
261                         // Populate combo box
262                         if (logger.isDebugEnabled()) {
263                                 logger.debug("Prepopulating Compound rule algorithm: " + index);
264                         }
265                         Map<String, String> rule = new HashMap<String, String>();
266                         for (String key : PolicyController.getDropDownMap().keySet()) {
267                                 String keyValue = PolicyController.getDropDownMap().get(key);
268                                 if (keyValue.equals(decisionApply.getFunctionId())) {
269                                         rule.put("dynamicRuleAlgorithmCombo", key);
270                                         break;
271                                 }
272                         }
273
274                         rule.put("id", "A" + (index +1));
275                         // Populate Key and values for Compound Rule
276                         rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 ));
277                         ruleAlgoirthmTracker.removeLast();
278                         rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
279                         ruleAlgoirthmTracker.removeLast();
280                         ruleAlgoirthmTracker.addLast(index);
281                         ruleAlgorithmList.add(rule);
282                         index++;
283                 }
284                 return index;
285         }
286 }