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