2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
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;
32 import java.util.Map.Entry;
34 import javax.xml.bind.JAXBElement;
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;
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;
67 public class DecisionPolicyController extends RestrictedBaseController {
68 private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
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";
77 protected PolicyRestAdapter policyAdapter = null;
78 private ArrayList<Object> ruleAlgorithmList;
79 private ArrayList<Object> treatmentList = null;
80 protected LinkedList<Integer> ruleAlgoirthmTracker;
82 public DecisionPolicyController() {
83 // This constructor is empty
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);
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<>();
104 boolean rawPolicyCheck = false;
105 if (policyAdapter.getPolicyData() instanceof PolicySetType) {
106 rawPolicyCheck = ((PolicySetType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
108 rawPolicyCheck = ((PolicyType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
111 if (rawPolicyCheck) {
112 rawXACMLPolicy(policyAdapter, entity);
114 RainyDayParams rainydayParams = new RainyDayParams();
115 Object policyData = policyAdapter.getPolicyData();
116 PolicyType policy = (PolicyType) policyData;
117 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
119 policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
120 String description = "";
121 String blackListEntryType = "Use Manual Entry";
123 if (policy.getDescription().contains(BLENTRY)) {
124 blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
125 policy.getDescription().lastIndexOf(BLENTRY));
127 policyAdapter.setBlackListEntryType(blackListEntryType);
128 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
130 } catch (Exception e) {
131 policyLogger.info("General error", e);
132 description = policy.getDescription();
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();
153 if (matchList != null) {
154 Iterator<MatchType> iterMatch = matchList.iterator();
155 while (iterMatch.hasNext()) {
156 MatchType match = iterMatch.next();
158 // Under the match we have attributevalue and
159 // attributeDesignator. So,finally down to the actual attribute.
161 AttributeValueType attributeValue = match.getAttributeValue();
162 String value = (String) attributeValue.getContent().get(0);
164 value = value.replaceAll("\\(\\?i\\)", "");
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);
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.
175 Map<String, String> attribute = new HashMap<>();
176 attribute.put("key", attributeId);
177 attribute.put("value", value);
178 attributeList.add(attribute);
183 policyAdapter.setAttributes(attributeList);
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"));
195 } else if ("BB_ID".equals(map.get("key"))) {
196 rainydayParams.setBbid(map.get("value"));
198 } else if ("ServiceType".equals(map.get("key"))) {
199 rainydayParams.setServiceType(map.get("value"));
201 } else if ("VNFType".equals(map.get("key"))) {
202 rainydayParams.setVnfType(map.get("value"));
208 policyAdapter.setRuleProvider("Rainy_Day");
212 List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
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());
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");
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);
245 policyAdapter.setRuleProvider("Custom");
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"));
274 (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
275 .getExpression().get(0).getValue();
276 yamlParams.setGuardActiveStart(
277 ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
279 yamlParams.setGuardActiveEnd(
280 ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
282 if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
283 apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
284 .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
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());
292 yamlParams.setBlackList(blackList);
293 if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
294 policyAdapter.setBlackListEntries(blackList);
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())
304 yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
305 yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
306 timeWindow.lastIndexOf(':')));
308 policyAdapter.setYamlparams(yamlParams);
309 policyAdapter.setAttributes(new ArrayList<Object>());
310 policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
313 // Populating Rule Algorithms starting from compound.
314 prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
315 policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
317 } else if (policyAdapter.getRuleProvider() != null
318 && "Rainy_Day".equals(policyAdapter.getRuleProvider())
319 && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
321 TargetType ruleTarget = ((RuleType) object).getTarget();
322 AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
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();
331 prePopulateRainyDayTreatments(errorcode, treatment);
338 rainydayParams.setTreatmentTableChoices(treatmentList);
339 policyAdapter.setRainyday(rainydayParams);
340 policyAdapter.setSettings(decisionList);
345 private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
346 Map<String, String> ruleMap = new HashMap<>();
348 ruleMap.put("errorcode", errorcode);
349 ruleMap.put("treatment", treatment);
350 treatmentList.add(ruleMap);
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());
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());
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);
379 } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
380 VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
381 ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId());
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);
388 ruleAlgorithmList.add(ruleMap);
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);
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;
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);
413 // Populate combo box
414 if (policyLogger.isDebugEnabled()) {
415 policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
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);
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);