2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.LinkedList;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import javax.xml.bind.JAXBElement;
34 import org.onap.policy.common.logging.flexlogger.FlexLogger;
35 import org.onap.policy.common.logging.flexlogger.Logger;
36 import org.onap.policy.rest.adapter.PolicyRestAdapter;
37 import org.onap.policy.rest.adapter.RainyDayParams;
38 import org.onap.policy.rest.adapter.YAMLParams;
39 import org.onap.policy.rest.jpa.PolicyEntity;
40 import org.onap.portalsdk.core.controller.RestrictedBaseController;
41 import org.springframework.stereotype.Controller;
42 import org.springframework.web.bind.annotation.RequestMapping;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
61 public class DecisionPolicyController extends RestrictedBaseController {
62 private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
64 public DecisionPolicyController(){
65 // This constructor is empty
68 protected PolicyRestAdapter policyAdapter = null;
69 private ArrayList<Object> attributeList;
70 private ArrayList<Object> decisionList;
71 private ArrayList<Object> ruleAlgorithmList;
72 private ArrayList<Object> treatmentList = null;
73 protected LinkedList<Integer> ruleAlgoirthmTracker;
74 public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
76 @SuppressWarnings("unchecked")
77 public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
78 attributeList = new ArrayList<>();
79 decisionList = new ArrayList<>();
80 ruleAlgorithmList = new ArrayList<>();
81 treatmentList = new ArrayList<>();
83 if (policyAdapter.getPolicyData() instanceof PolicyType) {
84 RainyDayParams rainydayParams = new RainyDayParams();
85 Object policyData = policyAdapter.getPolicyData();
86 PolicyType policy = (PolicyType) policyData;
87 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
88 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
89 policyAdapter.setPolicyName(policyNameValue);
90 String description = "";
92 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
94 policyLogger.info("General error", e);
95 description = policy.getDescription();
97 policyAdapter.setPolicyDescription(description);
98 // Get the target data under policy for Action.
99 TargetType target = policy.getTarget();
100 if (target != null) {
101 // under target we have AnyOFType
102 List<AnyOfType> anyOfList = target.getAnyOf();
103 if (anyOfList != null) {
104 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
105 while (iterAnyOf.hasNext()) {
106 AnyOfType anyOf = iterAnyOf.next();
107 // Under AntOfType we have AllOfType
108 List<AllOfType> allOfList = anyOf.getAllOf();
109 if (allOfList != null) {
110 Iterator<AllOfType> iterAllOf = allOfList.iterator();
111 while (iterAllOf.hasNext()) {
112 AllOfType allOf = iterAllOf.next();
113 // Under AllOfType we have Mathch.
114 List<MatchType> matchList = allOf.getMatch();
116 if (matchList != null) {
117 Iterator<MatchType> iterMatch = matchList.iterator();
118 while (iterMatch.hasNext()) {
119 MatchType match = iterMatch.next();
121 // Under the match we have attributevalue and
122 // attributeDesignator. So,finally down to the actual attribute.
124 AttributeValueType attributeValue = match.getAttributeValue();
125 String value = (String) attributeValue.getContent().get(0);
127 value = value.replaceAll("\\(\\?i\\)", "");
129 AttributeDesignatorType designator = match.getAttributeDesignator();
130 String attributeId = designator.getAttributeId();
131 // First match in the target is OnapName, so set that value.
132 if ("ONAPName".equals(attributeId)) {
133 policyAdapter.setOnapName(value);
135 // Component attributes are saved under Target here we are fetching them back.
136 // One row is default so we are not adding dynamic component at index 0.
138 Map<String, String> attribute = new HashMap<>();
139 attribute.put("key", attributeId);
140 attribute.put("value", value);
141 attributeList.add(attribute);
146 policyAdapter.setAttributes(attributeList);
150 // Setting rainy day attributes to the parameters object if they exist
151 boolean rainy = false;
152 if(!attributeList.isEmpty()) {
153 for(int i=0; i<attributeList.size() ; i++){
154 Map<String, String> map = (Map<String,String>)attributeList.get(i);
155 if("WorkStep".equals(map.get("key"))){
156 rainydayParams.setWorkstep(map.get("value"));
158 }else if("BB_ID".equals(map.get("key"))){
159 rainydayParams.setBbid(map.get("value"));
161 }else if("ServiceType".equals(map.get("key"))){
162 rainydayParams.setServiceType(map.get("value"));
164 }else if("VNFType".equals(map.get("key"))){
165 rainydayParams.setVnfType(map.get("value"));
171 policyAdapter.setRuleProvider("Rainy_Day");
175 List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
177 for (Object object : ruleList) {
178 if (object instanceof VariableDefinitionType) {
179 VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
180 Map<String, String> settings = new HashMap<>();
181 settings.put("key", variableDefinitionType.getVariableId());
182 JAXBElement<AttributeValueType> attributeValueTypeElement = (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
183 if (attributeValueTypeElement != null) {
184 AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
185 settings.put("value", attributeValueType.getContent().get(0).toString());
187 decisionList.add(settings);
188 } else if (object instanceof RuleType) {
189 // get the condition data under the rule for rule Algorithms.
190 if(((RuleType) object).getEffect().equals(EffectType.DENY)) {
191 if(((RuleType) object).getAdviceExpressions()!=null){
192 if("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
193 policyAdapter.setRuleProvider("AAF");
195 }else if("GUARD_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
196 policyAdapter.setRuleProvider("GUARD_YAML");
197 }else if("GUARD_BL_YAML".equalsIgnoreCase(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId())){
198 policyAdapter.setRuleProvider("GUARD_BL_YAML");
201 policyAdapter.setRuleProvider("Custom");
203 ConditionType condition = ((RuleType) object).getCondition();
204 if (condition != null) {
205 ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
206 decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
207 ruleAlgoirthmTracker = new LinkedList<>();
208 if(policyAdapter.getRuleProvider()!=null && ("GUARD_YAML".equals(policyAdapter.getRuleProvider())||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
209 YAMLParams yamlParams = new YAMLParams();
210 for(int i=0; i<attributeList.size() ; i++){
211 Map<String, String> map = (Map<String,String>)attributeList.get(i);
212 if("actor".equals(map.get("key"))){
213 yamlParams.setActor(map.get("value"));
214 }else if("recipe".equals(map.get("key"))){
215 yamlParams.setRecipe(map.get("value"));
216 }else if("target".equals(map.get("key"))){
217 yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
218 }else if("clname".equals(map.get("key"))){
219 yamlParams.setClname(map.get("value"));
222 ApplyType apply = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue();
223 yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString());
224 yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString());
225 if("GUARD_BL_YAML".equals(policyAdapter.getRuleProvider())){
226 apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue();
227 Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
228 List<String> blackList = new ArrayList<>();
229 while(attributes.hasNext()){
230 blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString());
232 yamlParams.setBlackList(blackList);
234 ApplyType timeWindowSection = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue();
235 yamlParams.setLimit(((AttributeValueType)timeWindowSection.getExpression().get(1).getValue()).getContent().get(0).toString());
236 String timeWindow = ((AttributeDesignatorType)((ApplyType)timeWindowSection.getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer();
237 yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':')+1));
238 yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:")+4,timeWindow.lastIndexOf(':')));
240 policyAdapter.setYamlparams(yamlParams);
241 policyAdapter.setAttributes(new ArrayList<Object>());
242 policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
245 // Populating Rule Algorithms starting from compound.
246 prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
247 policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
249 } else if(policyAdapter.getRuleProvider()!=null && "Rainy_Day".equals(policyAdapter.getRuleProvider())&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
251 TargetType ruleTarget = ((RuleType) object).getTarget();
252 AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
254 String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().
255 get(1).getAttributeValue().getContent().get(0).toString();
256 JAXBElement<AttributeValueType> tempTreatmentObj = (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().
257 get(0).getAttributeAssignmentExpression().get(0).getExpression();
258 String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
260 prePopulateRainyDayTreatments(errorcode, treatment);
267 rainydayParams.setTreatmentTableChoices(treatmentList);
268 policyAdapter.setRainyday(rainydayParams);
269 policyAdapter.setSettings(decisionList);
274 private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
275 Map<String, String> ruleMap = new HashMap<>();
277 ruleMap.put("errorcode", errorcode);
278 ruleMap.put("treatment", treatment);
279 treatmentList.add(ruleMap);
283 private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List<JAXBElement<?>> jaxbDecisionTypes) {
284 Map<String, String> ruleMap = new HashMap<>();
285 ruleMap.put("id", "A" + (index +1));
286 Map<String, String> dropDownMap = PolicyController.getDropDownMap();
287 for (Entry<String, String> entry : dropDownMap.entrySet()) {
288 if (entry.getValue().equals(decisionApply.getFunctionId())) {
289 ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
292 // Populate the key and value fields
293 if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) {
294 ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
295 List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
296 if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
297 AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue();
298 ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
300 // Get from Attribute Value
301 AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue();
302 String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
303 ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
305 } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
306 VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
307 ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId());
310 // Get from Attribute Value
311 AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
312 String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
313 ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
315 ruleAlgorithmList.add(ruleMap);
318 private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) {
319 boolean isCompoundRule = true;
320 List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression();
321 for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
322 // If There is Attribute Value under Decision Type that means we came to the final child
323 if (policyLogger.isDebugEnabled()) {
324 policyLogger.debug("Prepopulating rule algoirthm: " + index);
326 // Check to see if Attribute Value exists, if yes then it is not a compound rule
327 if(jaxbElement.getValue() instanceof AttributeValueType) {
328 prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes);
329 ruleAlgoirthmTracker.addLast(index);
330 isCompoundRule = false;
334 if (isCompoundRule) {
335 // As it's compound rule, Get the Apply types
336 for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
337 ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
338 index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
340 // Populate combo box
341 if (policyLogger.isDebugEnabled()) {
342 policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
344 Map<String, String> rule = new HashMap<>();
345 for (String key : PolicyController.getDropDownMap().keySet()) {
346 String keyValue = PolicyController.getDropDownMap().get(key);
347 if (keyValue.equals(decisionApply.getFunctionId())) {
348 rule.put("dynamicRuleAlgorithmCombo", key);
353 rule.put("id", "A" + (index +1));
354 // Populate Key and values for Compound Rule
355 rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 ));
356 ruleAlgoirthmTracker.removeLast();
357 rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
358 ruleAlgoirthmTracker.removeLast();
359 ruleAlgoirthmTracker.addLast(index);
360 ruleAlgorithmList.add(rule);