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