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