Sonar cleanup in controllers etc
[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             return;
126         }
127         RainyDayParams rainydayParams = new RainyDayParams();
128         Object policyData = policyAdapter.getPolicyData();
129         PolicyType policy = (PolicyType) policyData;
130         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
131
132         policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
133         String description = "";
134         String blackListEntryType = "Use Manual Entry";
135         try {
136             if (policy.getDescription().contains(BLENTRY)) {
137                 blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
138                         policy.getDescription().lastIndexOf(BLENTRY));
139             }
140             policyAdapter.setBlackListEntryType(blackListEntryType);
141             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
142
143         } catch (Exception e) {
144             policyLogger.info("General error", e);
145             description = policy.getDescription();
146         }
147         policyAdapter.setPolicyDescription(description);
148         // Get the target data under policy for Action.
149         TargetType target = policy.getTarget();
150         if (target == null) {
151             rainydayParams.setTreatmentTableChoices(treatmentList);
152             policyAdapter.setRainyday(rainydayParams);
153             policyAdapter.setSettings(decisionList);
154             return;
155         }
156         // under target we have AnyOFType
157         for (AnyOfType anyOf : target.getAnyOf()) {
158             for (AllOfType allOf : anyOf.getAllOf()) {
159                 int index = 0;
160                 for (MatchType match : allOf.getMatch()) {
161                     //
162                     // Under the match we have attributevalue and
163                     // attributeDesignator. So,finally down to the actual attribute.
164                     //
165                     AttributeValueType attributeValue = match.getAttributeValue();
166                     String value = (String) attributeValue.getContent().get(0);
167                     if (value != null) {
168                         value = value.replaceAll("\\(\\?i\\)", "");
169                     }
170                     AttributeDesignatorType designator = match.getAttributeDesignator();
171                     String attributeId = designator.getAttributeId();
172                     // First match in the target is OnapName, so set that value.
173                     if ("ONAPName".equals(attributeId)) {
174                         policyAdapter.setOnapName(value);
175                     }
176                     // Component attributes are saved under Target here we are fetching them back.
177                     // One row is default so we are not adding dynamic component at index 0.
178                     if (index >= 1) {
179                         Map<String, String> attribute = new HashMap<>();
180                         attribute.put("key", attributeId);
181                         attribute.put("value", value);
182                         attributeList.add(attribute);
183                     }
184                     index++;
185                 }
186                 policyAdapter.setAttributes(attributeList);
187             }
188         }
189         // Setting rainy day attributes to the parameters object if they exist
190         boolean rainy = false;
191         if (!attributeList.isEmpty()) {
192             for (int i = 0; i < attributeList.size(); i++) {
193                 Map<String, String> map = (Map<String, String>) attributeList.get(i);
194                 String key = map.get("key");
195                 if ("WorkStep".equals(key)) {
196                     rainydayParams.setWorkstep(map.get("value"));
197                     rainy = true;
198                 } else if ("BB_ID".equals(key)) {
199                     rainydayParams.setBbid(map.get("value"));
200                     rainy = true;
201                 } else if ("ServiceType".equals(key)) {
202                     rainydayParams.setServiceType(map.get("value"));
203                     rainy = true;
204                 } else if ("VNFType".equals(key)) {
205                     rainydayParams.setVnfType(map.get("value"));
206                     rainy = true;
207                 }
208             }
209         }
210         if (rainy) {
211             policyAdapter.setRuleProvider("Rainy_Day");
212         }
213
214         List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
215         int index = 0;
216         for (Object object : ruleList) {
217             if (object instanceof VariableDefinitionType) {
218                 VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
219                 Map<String, String> settings = new HashMap<>();
220                 settings.put("key", variableDefinitionType.getVariableId());
221                 JAXBElement<AttributeValueType> attributeValueTypeElement =
222                         (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
223                 if (attributeValueTypeElement != null) {
224                     AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
225                     settings.put("value", attributeValueType.getContent().get(0).toString());
226                 }
227                 decisionList.add(settings);
228             } else if (object instanceof RuleType) {
229                 // get the condition data under the rule for rule Algorithms.
230                 if (((RuleType) object).getEffect().equals(EffectType.DENY)) {
231                     if (((RuleType) object).getAdviceExpressions() != null) {
232                         if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
233                                 .getAdviceExpression().get(0).getAdviceId())) {
234                             policyAdapter.setRuleProvider("AAF");
235                             break;
236                         } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
237                                 .getAdviceExpression().get(0).getAdviceId())) {
238                             policyAdapter.setRuleProvider(GUARD_YAML);
239                         } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
240                                 .getAdviceExpression().get(0).getAdviceId())) {
241                             policyAdapter.setRuleProvider(GUARD_BL_YAML);
242                         } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
243                                 .getAdviceExpression().get(0).getAdviceId())) {
244                             policyAdapter.setRuleProvider(GUARD_MIN_MAX);
245                         }
246                     } else {
247                         policyAdapter.setRuleProvider("Custom");
248                     }
249                     ConditionType condition = ((RuleType) object).getCondition();
250                     if (condition != null) {
251                         ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
252                         decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
253                         ruleAlgoirthmTracker = new LinkedList<>();
254                         if (policyAdapter.getRuleProvider() != null
255                                 && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
256                                         || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
257                                         || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) {
258                             YAMLParams yamlParams = new YAMLParams();
259                             for (int i = 0; i < attributeList.size(); i++) {
260                                 Map<String, String> map = (Map<String, String>) attributeList.get(i);
261                                 String key = map.get("key");
262                                 if ("actor".equals(key)) {
263                                     yamlParams.setActor(map.get("value"));
264                                 } else if ("recipe".equals(key)) {
265                                     yamlParams.setRecipe(map.get("value"));
266                                 } else if ("target".equals(key)) {
267                                     yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
268                                 } else if ("clname".equals(key)) {
269                                     yamlParams.setClname(map.get("value"));
270                                 } else if ("min".equals(key)) {
271                                     yamlParams.setMin(map.get("value"));
272                                 } else if ("max".equals(key)) {
273                                     yamlParams.setMax(map.get("value"));
274                                 }
275                             }
276                             ApplyType apply =
277                                     (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
278                                             .getExpression().get(0).getValue();
279                             yamlParams.setGuardActiveStart(
280                                     ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
281                                             .get(0).toString());
282                             yamlParams.setGuardActiveEnd(
283                                     ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
284                                             .get(0).toString());
285                             if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
286                                 apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
287                                         .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
288                                                 .get(2).getValue();
289                                 List<String> blackList = new ArrayList<>();
290                                 for (JAXBElement<?> attr : apply.getExpression()) {
291                                     blackList.add(((AttributeValueType) attr.getValue())
292                                             .getContent().get(0).toString());
293                                 }
294                                 yamlParams.setBlackList(blackList);
295                                 if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
296                                     policyAdapter.setBlackListEntries(blackList);
297                                 }
298                             } else {
299                                 ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply
300                                         .getExpression().get(0).getValue()).getExpression().get(1).getValue();
301                                 yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression()
302                                         .get(1).getValue()).getContent().get(0).toString());
303                                 String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection
304                                         .getExpression().get(0).getValue()).getExpression().get(0).getValue())
305                                                 .getIssuer();
306                                 yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
307                                 yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
308                                         timeWindow.lastIndexOf(':')));
309                             }
310                             policyAdapter.setYamlparams(yamlParams);
311                             policyAdapter.setAttributes(new ArrayList<Object>());
312                             policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
313                             break;
314                         }
315                         // Populating Rule Algorithms starting from compound.
316                         prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
317                         policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
318                     }
319                 } else if (policyAdapter.getRuleProvider() != null
320                         && "Rainy_Day".equals(policyAdapter.getRuleProvider())
321                         && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
322
323                     TargetType ruleTarget = ((RuleType) object).getTarget();
324                     AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
325
326                     String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
327                             .getAttributeValue().getContent().get(0).toString();
328                     JAXBElement<AttributeValueType> tempTreatmentObj =
329                             (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
330                                     .getAttributeAssignmentExpression().get(0).getExpression();
331                     String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
332
333                     prePopulateRainyDayTreatments(errorcode, treatment);
334
335                 }
336             }
337         }
338
339         rainydayParams.setTreatmentTableChoices(treatmentList);
340         policyAdapter.setRainyday(rainydayParams);
341         policyAdapter.setSettings(decisionList);
342     }
343
344     private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
345         Map<String, String> ruleMap = new HashMap<>();
346
347         ruleMap.put("errorcode", errorcode);
348         ruleMap.put("treatment", treatment);
349         treatmentList.add(ruleMap);
350
351     }
352
353     private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply,
354             List<JAXBElement<?>> jaxbDecisionTypes) {
355         Map<String, String> ruleMap = new HashMap<>();
356         ruleMap.put("id", "A" + (index + 1));
357         Map<String, String> dropDownMap = PolicyController.getDropDownMap();
358         for (Entry<String, String> entry : dropDownMap.entrySet()) {
359             if (entry.getValue().equals(decisionApply.getFunctionId())) {
360                 ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
361             }
362         }
363         // Populate the key and value fields
364         if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) {
365             ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
366             List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
367             if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
368                 AttributeDesignatorType attributeDesignator =
369                         (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue();
370                 ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
371
372                 // Get from Attribute Value
373                 AttributeValueType actionConditionAttributeValue =
374                         (AttributeValueType) jaxbDecisionTypes.get(0).getValue();
375                 String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
376                 ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
377             }
378         } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
379             VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
380             ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId());
381
382             // Get from Attribute Value
383             AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
384             String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
385             ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
386         }
387         ruleAlgorithmList.add(ruleMap);
388     }
389
390     private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) {
391         boolean isCompoundRule = true;
392         List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression();
393         for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
394             // If There is Attribute Value under Decision Type that means we came to the final child
395             if (policyLogger.isDebugEnabled()) {
396                 policyLogger.debug("Prepopulating rule algoirthm: " + index);
397             }
398             // Check to see if Attribute Value exists, if yes then it is not a compound rule
399             if (jaxbElement.getValue() instanceof AttributeValueType) {
400                 prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes);
401                 ruleAlgoirthmTracker.addLast(index);
402                 isCompoundRule = false;
403                 index++;
404             }
405         }
406         if (! isCompoundRule) {
407             return index;
408         }
409         // As it's compound rule, Get the Apply types
410         for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
411             ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
412             index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
413         }
414         // Populate combo box
415         if (policyLogger.isDebugEnabled()) {
416             policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
417         }
418         Map<String, String> rule = new HashMap<>();
419         for (String key : PolicyController.getDropDownMap().keySet()) {
420             String keyValue = PolicyController.getDropDownMap().get(key);
421             if (keyValue.equals(decisionApply.getFunctionId())) {
422                 rule.put("dynamicRuleAlgorithmCombo", key);
423                 break;
424             }
425         }
426
427         rule.put("id", "A" + (index + 1));
428         // Populate Key and values for Compound Rule
429         rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1));
430         ruleAlgoirthmTracker.removeLast();
431         rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
432         ruleAlgoirthmTracker.removeLast();
433         ruleAlgoirthmTracker.addLast(index);
434         ruleAlgorithmList.add(rule);
435
436         return ++index;
437     }
438 }