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.LinkedList;
29 import java.util.List;
31 import java.util.Map.Entry;
33 import javax.xml.bind.JAXBElement;
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
51 import org.apache.commons.io.IOUtils;
52 import org.apache.commons.lang3.StringUtils;
53 import org.onap.policy.common.logging.flexlogger.FlexLogger;
54 import org.onap.policy.common.logging.flexlogger.Logger;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.rest.adapter.RainyDayParams;
57 import org.onap.policy.rest.adapter.YAMLParams;
58 import org.onap.policy.rest.jpa.PolicyEntity;
59 import org.onap.policy.xacml.util.XACMLPolicyWriter;
60 import org.onap.portalsdk.core.controller.RestrictedBaseController;
61 import org.springframework.stereotype.Controller;
62 import org.springframework.web.bind.annotation.RequestMapping;
66 public class DecisionPolicyController extends RestrictedBaseController {
67 private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
69 public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
70 private static final String BLENTRY = "@blEntry@";
71 private static final String DECISIONRAWTYPE = "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
72 private static final String GUARD_YAML = "GUARD_YAML";
73 private static final String GUARD_BL_YAML = "GUARD_BL_YAML";
74 private static final String GUARD_MIN_MAX = "GUARD_MIN_MAX";
76 protected PolicyRestAdapter policyAdapter = null;
77 private ArrayList<Object> ruleAlgorithmList;
78 private ArrayList<Object> treatmentList = null;
79 protected LinkedList<Integer> ruleAlgoirthmTracker;
81 public DecisionPolicyController() {
82 // This constructor is empty
86 * rawXacmlPolicy. Should this method be private?
88 * @param policyAdapter PolicyRestAdapter
89 * @param entity PolicyEntity
91 public void rawXacmlPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
92 try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) {
93 String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_");
94 policyAdapter.setPolicyName(name.substring(0, name.indexOf('.')));
95 policyAdapter.setRuleProvider("Raw");
96 policyAdapter.setRawXacmlPolicy(IOUtils.toString(policyXmlStream).replaceAll(DECISIONRAWTYPE, ""));
97 } catch (IOException e) {
98 policyLogger.error("Exception Occured while setting XACML Raw Object" + e);
103 * prePopulateDecisionPolicyData.
105 * @param policyAdapter PolicyRestAdapter
106 * @param entity PolicyEntity
108 @SuppressWarnings("unchecked")
109 public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
110 List<Object> attributeList = new ArrayList<>();
111 List<Object> decisionList = new ArrayList<>();
112 ruleAlgorithmList = new ArrayList<>();
113 treatmentList = new ArrayList<>();
115 boolean rawPolicyCheck = false;
116 if (policyAdapter.getPolicyData() instanceof PolicySetType) {
117 rawPolicyCheck = ((PolicySetType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
119 rawPolicyCheck = ((PolicyType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
122 if (rawPolicyCheck) {
123 rawXacmlPolicy(policyAdapter, entity);
126 RainyDayParams rainydayParams = new RainyDayParams();
127 Object policyData = policyAdapter.getPolicyData();
128 PolicyType policy = (PolicyType) policyData;
129 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
131 policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
132 String description = "";
133 String blackListEntryType = "Use Manual Entry";
135 if (policy.getDescription().contains(BLENTRY)) {
136 blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
137 policy.getDescription().lastIndexOf(BLENTRY));
139 policyAdapter.setBlackListEntryType(blackListEntryType);
140 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
142 } catch (Exception e) {
143 policyLogger.info("General error", e);
144 description = policy.getDescription();
146 policyAdapter.setPolicyDescription(description);
147 // Get the target data under policy for Action.
148 TargetType target = policy.getTarget();
149 if (target == null) {
150 rainydayParams.setTreatmentTableChoices(treatmentList);
151 policyAdapter.setRainyday(rainydayParams);
152 policyAdapter.setSettings(decisionList);
155 // under target we have AnyOFType
156 for (AnyOfType anyOf : target.getAnyOf()) {
157 for (AllOfType allOf : anyOf.getAllOf()) {
159 for (MatchType match : allOf.getMatch()) {
161 // Under the match we have attributevalue and
162 // attributeDesignator. So,finally down to the actual attribute.
164 AttributeValueType attributeValue = match.getAttributeValue();
165 String value = (String) attributeValue.getContent().get(0);
167 value = value.replaceAll("\\(\\?i\\)", "");
169 AttributeDesignatorType designator = match.getAttributeDesignator();
170 String attributeId = designator.getAttributeId();
171 // First match in the target is OnapName, so set that value.
172 policyAdapter.setupUsingAttribute(attributeId, value);
173 // Component attributes are saved under Target here we are fetching them back.
174 // One row is default so we are not adding dynamic component at index 0.
176 Map<String, String> attribute = new HashMap<>();
177 attribute.put("key", attributeId);
178 attribute.put("value", value);
179 attributeList.add(attribute);
183 policyAdapter.setAttributes(attributeList);
186 // Setting rainy day attributes to the parameters object if they exist
187 boolean rainy = false;
188 if (!attributeList.isEmpty()) {
189 for (int i = 0; i < attributeList.size(); i++) {
190 Map<String, String> map = (Map<String, String>) attributeList.get(i);
191 String key = map.get("key");
192 if ("WorkStep".equals(key)) {
193 rainydayParams.setWorkstep(map.get("value"));
195 } else if ("BB_ID".equals(key)) {
196 rainydayParams.setBbid(map.get("value"));
198 } else if ("ServiceType".equals(key)) {
199 rainydayParams.setServiceType(map.get("value"));
201 } else if ("VNFType".equals(key)) {
202 rainydayParams.setVnfType(map.get("value"));
208 policyAdapter.setRuleProvider("Rainy_Day");
211 List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
213 for (Object object : ruleList) {
214 if (object instanceof VariableDefinitionType) {
215 VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
216 Map<String, String> settings = new HashMap<>();
217 settings.put("key", variableDefinitionType.getVariableId());
218 JAXBElement<AttributeValueType> attributeValueTypeElement =
219 (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
220 if (attributeValueTypeElement != null) {
221 AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
222 settings.put("value", attributeValueType.getContent().get(0).toString());
224 decisionList.add(settings);
225 } else if (object instanceof RuleType) {
226 // get the condition data under the rule for rule Algorithms.
227 if (((RuleType) object).getEffect().equals(EffectType.DENY)) {
228 if (((RuleType) object).getAdviceExpressions() != null) {
229 if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
230 .getAdviceExpression().get(0).getAdviceId())) {
231 policyAdapter.setRuleProvider("AAF");
233 } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
234 .getAdviceExpression().get(0).getAdviceId())) {
235 policyAdapter.setRuleProvider(GUARD_YAML);
236 } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
237 .getAdviceExpression().get(0).getAdviceId())) {
238 policyAdapter.setRuleProvider(GUARD_BL_YAML);
239 } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
240 .getAdviceExpression().get(0).getAdviceId())) {
241 policyAdapter.setRuleProvider(GUARD_MIN_MAX);
244 policyAdapter.setRuleProvider("Custom");
246 ConditionType condition = ((RuleType) object).getCondition();
247 if (condition != null) {
248 ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
249 decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
250 ruleAlgoirthmTracker = new LinkedList<>();
251 if (policyAdapter.getRuleProvider() != null
252 && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
253 || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
254 || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) {
255 YAMLParams yamlParams = new YAMLParams();
256 for (int i = 0; i < attributeList.size(); i++) {
257 Map<String, String> map = (Map<String, String>) attributeList.get(i);
258 String key = map.get("key");
259 if ("actor".equals(key)) {
260 yamlParams.setActor(map.get("value"));
261 } else if ("recipe".equals(key)) {
262 yamlParams.setRecipe(map.get("value"));
263 } else if ("target".equals(key)) {
264 yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
265 } else if ("clname".equals(key)) {
266 yamlParams.setClname(map.get("value"));
267 } else if ("min".equals(key)) {
268 yamlParams.setMin(map.get("value"));
269 } else if ("max".equals(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 List<String> blackList = new ArrayList<>();
287 for (JAXBElement<?> attr : apply.getExpression()) {
288 blackList.add(((AttributeValueType) attr.getValue())
289 .getContent().get(0).toString());
291 yamlParams.setBlackList(blackList);
292 if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
293 policyAdapter.setBlackListEntries(blackList);
296 ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply
297 .getExpression().get(0).getValue()).getExpression().get(1).getValue();
298 yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression()
299 .get(1).getValue()).getContent().get(0).toString());
300 String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection
301 .getExpression().get(0).getValue()).getExpression().get(0).getValue())
303 yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
304 yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
305 timeWindow.lastIndexOf(':')));
307 policyAdapter.setYamlparams(yamlParams);
308 policyAdapter.setAttributes(new ArrayList<Object>());
309 policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
312 // Populating Rule Algorithms starting from compound.
313 prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
314 policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
316 } else if (policyAdapter.getRuleProvider() != null
317 && "Rainy_Day".equals(policyAdapter.getRuleProvider())
318 && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
320 TargetType ruleTarget = ((RuleType) object).getTarget();
321 AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
323 String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
324 .getAttributeValue().getContent().get(0).toString();
325 JAXBElement<AttributeValueType> tempTreatmentObj =
326 (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
327 .getAttributeAssignmentExpression().get(0).getExpression();
328 String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
330 prePopulateRainyDayTreatments(errorcode, treatment);
336 rainydayParams.setTreatmentTableChoices(treatmentList);
337 policyAdapter.setRainyday(rainydayParams);
338 policyAdapter.setSettings(decisionList);
341 private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
342 Map<String, String> ruleMap = new HashMap<>();
344 ruleMap.put("errorcode", errorcode);
345 ruleMap.put("treatment", treatment);
346 treatmentList.add(ruleMap);
350 private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply,
351 List<JAXBElement<?>> jaxbDecisionTypes) {
352 Map<String, String> ruleMap = new HashMap<>();
353 ruleMap.put("id", "A" + (index + 1));
354 Map<String, String> dropDownMap = PolicyController.getDropDownMap();
355 for (Entry<String, String> entry : dropDownMap.entrySet()) {
356 if (entry.getValue().equals(decisionApply.getFunctionId())) {
357 ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
360 // Populate the key and value fields
361 if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) {
362 ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
363 List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
364 if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
365 AttributeDesignatorType attributeDesignator =
366 (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue();
367 ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
369 // Get from Attribute Value
370 AttributeValueType actionConditionAttributeValue =
371 (AttributeValueType) jaxbDecisionTypes.get(0).getValue();
372 String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
373 ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
375 } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
376 VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
377 ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId());
379 // Get from Attribute Value
380 AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
381 String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
382 ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
384 ruleAlgorithmList.add(ruleMap);
387 private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) {
388 boolean isCompoundRule = true;
389 List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression();
390 for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
391 // If There is Attribute Value under Decision Type that means we came to the final child
392 if (policyLogger.isDebugEnabled()) {
393 policyLogger.debug("Prepopulating rule algoirthm: " + index);
395 // Check to see if Attribute Value exists, if yes then it is not a compound rule
396 if (jaxbElement.getValue() instanceof AttributeValueType) {
397 prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes);
398 ruleAlgoirthmTracker.addLast(index);
399 isCompoundRule = false;
403 if (! isCompoundRule) {
406 // As it's compound rule, Get the Apply types
407 for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
408 ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
409 index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
411 // Populate combo box
412 if (policyLogger.isDebugEnabled()) {
413 policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
415 Map<String, String> rule = new HashMap<>();
416 for (String key : PolicyController.getDropDownMap().keySet()) {
417 String keyValue = PolicyController.getDropDownMap().get(key);
418 if (keyValue.equals(decisionApply.getFunctionId())) {
419 rule.put("dynamicRuleAlgorithmCombo", key);
424 rule.put("id", "A" + (index + 1));
425 // Populate Key and values for Compound Rule
426 rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1));
427 ruleAlgoirthmTracker.removeLast();
428 rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
429 ruleAlgoirthmTracker.removeLast();
430 ruleAlgoirthmTracker.addLast(index);
431 ruleAlgorithmList.add(rule);