2 * ============LICENSE_START=======================================================
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
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;
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;
64 public class DecisionPolicyController extends RestrictedBaseController {
65 private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
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";
73 protected PolicyRestAdapter policyAdapter = null;
74 private ArrayList<Object> ruleAlgorithmList;
75 private ArrayList<Object> treatmentList = null;
76 protected LinkedList<Integer> ruleAlgoirthmTracker;
78 public DecisionPolicyController() {
79 // This constructor is empty
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);
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<>();
100 boolean rawPolicyCheck = false;
101 if (policyAdapter.getPolicyData() instanceof PolicySetType) {
102 rawPolicyCheck = ((PolicySetType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
104 rawPolicyCheck = ((PolicyType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
107 if (rawPolicyCheck) {
108 rawXACMLPolicy(policyAdapter, entity);
110 RainyDayParams rainydayParams = new RainyDayParams();
111 Object policyData = policyAdapter.getPolicyData();
112 PolicyType policy = (PolicyType) policyData;
113 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
115 policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
116 String description = "";
117 String blackListEntryType = "Use Manual Entry";
119 if (policy.getDescription().contains(BLENTRY)) {
120 blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
121 policy.getDescription().lastIndexOf(BLENTRY));
123 policyAdapter.setBlackListEntryType(blackListEntryType);
124 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
126 } catch (Exception e) {
127 policyLogger.info("General error", e);
128 description = policy.getDescription();
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();
149 if (matchList != null) {
150 Iterator<MatchType> iterMatch = matchList.iterator();
151 while (iterMatch.hasNext()) {
152 MatchType match = iterMatch.next();
154 // Under the match we have attributevalue and
155 // attributeDesignator. So,finally down to the actual attribute.
157 AttributeValueType attributeValue = match.getAttributeValue();
158 String value = (String) attributeValue.getContent().get(0);
160 value = value.replaceAll("\\(\\?i\\)", "");
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);
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.
171 Map<String, String> attribute = new HashMap<>();
172 attribute.put("key", attributeId);
173 attribute.put("value", value);
174 attributeList.add(attribute);
179 policyAdapter.setAttributes(attributeList);
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"));
191 } else if ("BB_ID".equals(map.get("key"))) {
192 rainydayParams.setBbid(map.get("value"));
194 } else if ("ServiceType".equals(map.get("key"))) {
195 rainydayParams.setServiceType(map.get("value"));
197 } else if ("VNFType".equals(map.get("key"))) {
198 rainydayParams.setVnfType(map.get("value"));
204 policyAdapter.setRuleProvider("Rainy_Day");
208 List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
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());
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");
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);
238 policyAdapter.setRuleProvider("Custom");
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"));
262 (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
263 .getExpression().get(0).getValue();
264 yamlParams.setGuardActiveStart(
265 ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
267 yamlParams.setGuardActiveEnd(
268 ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
270 if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
271 apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
272 .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
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());
280 yamlParams.setBlackList(blackList);
281 if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
282 policyAdapter.setBlackListEntries(blackList);
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())
292 yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
293 yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
294 timeWindow.lastIndexOf(':')));
296 policyAdapter.setYamlparams(yamlParams);
297 policyAdapter.setAttributes(new ArrayList<Object>());
298 policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
301 // Populating Rule Algorithms starting from compound.
302 prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
303 policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
305 } else if (policyAdapter.getRuleProvider() != null
306 && "Rainy_Day".equals(policyAdapter.getRuleProvider())
307 && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
309 TargetType ruleTarget = ((RuleType) object).getTarget();
310 AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
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();
319 prePopulateRainyDayTreatments(errorcode, treatment);
326 rainydayParams.setTreatmentTableChoices(treatmentList);
327 policyAdapter.setRainyday(rainydayParams);
328 policyAdapter.setSettings(decisionList);
333 private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
334 Map<String, String> ruleMap = new HashMap<>();
336 ruleMap.put("errorcode", errorcode);
337 ruleMap.put("treatment", treatment);
338 treatmentList.add(ruleMap);
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());
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());
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);
367 } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
368 VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
369 ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId());
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);
377 ruleAlgorithmList.add(ruleMap);
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);
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;
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);
402 // Populate combo box
403 if (policyLogger.isDebugEnabled()) {
404 policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
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);
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);