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