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