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.pap.xacml.rest.components;
23 import java.io.ByteArrayInputStream;
25 import java.io.IOException;
27 import java.net.URISyntaxException;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.HashMap;
35 import java.util.LinkedList;
36 import java.util.List;
38 import java.util.UUID;
40 import javax.persistence.EntityManager;
41 import javax.persistence.Query;
43 import org.onap.policy.common.logging.eelf.MessageCodes;
44 import org.onap.policy.common.logging.eelf.PolicyLogger;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.controlloop.policy.builder.BuilderException;
48 import org.onap.policy.controlloop.policy.builder.Results;
49 import org.onap.policy.controlloop.policy.guard.Constraint;
50 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
51 import org.onap.policy.controlloop.policy.guard.Guard;
52 import org.onap.policy.controlloop.policy.guard.GuardPolicy;
53 import org.onap.policy.controlloop.policy.guard.MatchParameters;
54 import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder;
55 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
56 import org.onap.policy.rest.adapter.PolicyRestAdapter;
57 import org.onap.policy.rest.dao.CommonClassDao;
58 import org.onap.policy.rest.jpa.DecisionSettings;
59 import org.onap.policy.rest.jpa.FunctionDefinition;
60 import org.onap.policy.utils.PolicyUtils;
61 import org.onap.policy.xacml.api.XACMLErrorConstants;
62 import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
63 import org.onap.policy.xacml.util.XACMLPolicyScanner;
65 import com.att.research.xacml.api.XACML3;
66 import com.att.research.xacml.api.pap.PAPException;
67 import com.att.research.xacml.std.IdentifierImpl;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
85 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
87 public class DecisionPolicy extends Policy {
89 private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class);
91 public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
92 private static final String AAFPROVIDER = "AAF";
93 public static final String GUARD_YAML = "GUARD_YAML";
94 public static final String GUARD_BL_YAML = "GUARD_BL_YAML";
95 public static final String RAINY_DAY = "Rainy_Day";
96 private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml";
97 private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml";
99 private static final String ONAPNAME = "ONAPName";
100 private static final String POLICY_NAME = "PolicyName";
101 private static final String DESCRIPTION = "description";
104 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
105 List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
106 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
107 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
108 List<String> dataTypeList = new LinkedList<>();
110 private CommonClassDao commonClassDao;
112 public DecisionPolicy() {
116 public DecisionPolicy(PolicyRestAdapter policyAdapter, CommonClassDao commonClassDao){
117 this.policyAdapter = policyAdapter;
118 this.commonClassDao = commonClassDao;
122 public Map<String, String> savePolicies() throws PAPException {
124 Map<String, String> successMap = new HashMap<>();
125 if(isPolicyExists()){
126 successMap.put("EXISTS", "This Policy already exist on the PAP");
130 if(!isPreparedToSave()){
131 //Prep and configure the policy for saving
135 // Until here we prepared the data and here calling the method to create xml.
136 Path newPolicyPath = null;
137 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
139 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
143 //This is the method for preparing the policy for saving. We have broken it out
144 //separately because the fully configured policy is used for multiple things
146 public boolean prepareToSave() throws PAPException{
148 if(isPreparedToSave()){
149 //we have already done this
154 String policyID = policyAdapter.getPolicyID();
155 version = policyAdapter.getHighestVersion();
157 // Create the Instance for pojo, PolicyType object is used in marshalling.
158 if ("Decision".equals(policyAdapter.getPolicyType())) {
159 PolicyType policyConfig = new PolicyType();
161 policyConfig.setVersion(Integer.toString(version));
162 policyConfig.setPolicyId(policyID);
163 policyConfig.setTarget(new TargetType());
164 policyAdapter.setData(policyConfig);
166 policyName = policyAdapter.getNewFileName();
168 if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){
169 Map<String, String> yamlParams = new HashMap<>();
170 yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy");
171 String fileName = policyAdapter.getNewFileName();
172 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
173 if ((name == null) || ("".equals(name))) {
174 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
176 yamlParams.put(POLICY_NAME, name);
177 yamlParams.put(ONAPNAME, policyAdapter.getOnapName());
178 Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes();
179 yamlParams.putAll(params);
180 // Call YAML to XACML
182 PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider());
183 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
184 decisionPolicy.setVersion(Integer.toString(version));
185 policyAdapter.setPolicyData(decisionPolicy);
186 policyAdapter.setData(decisionPolicy);
187 } catch (BuilderException e) {
189 throw new PAPException(e);
191 }else if (policyAdapter.getData() != null) {
192 PolicyType decisionPolicy = (PolicyType) policyAdapter.getData();
194 decisionPolicy.setDescription(policyAdapter.getPolicyDescription());
196 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
197 AllOfType allOfOne = new AllOfType();
198 String fileName = policyAdapter.getNewFileName();
199 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
200 if ((name == null) || ("".equals(name))) {
201 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
203 allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
205 AllOfType allOf = new AllOfType();
208 allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName())));
210 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
211 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
212 dynamicFieldComponentAttributes = new HashMap<>();
215 // If there is any dynamic field attributes create the matches here
216 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
217 String key = keyField;
218 String value = dynamicFieldComponentAttributes.get(key);
219 MatchType dynamicMatch = createDynamicMatch(key, value);
220 allOf.getMatch().add(dynamicMatch);
223 AnyOfType anyOf = new AnyOfType();
224 anyOf.getAllOf().add(allOfOne);
225 anyOf.getAllOf().add(allOf);
227 TargetType target = new TargetType();
228 target.getAnyOf().add(anyOf);
229 decisionPolicy.setTarget(target);
231 Map<String, String> dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap();
232 if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals(AAFPROVIDER)||
233 policyAdapter.getRuleProvider().equals(RAINY_DAY))){
234 dynamicFieldDecisionSettings = new HashMap<>();
237 // settings are dynamic so check how many rows are added and add all
238 for (String keyField : dynamicFieldDecisionSettings.keySet()) {
239 String key = keyField;
240 String value = dynamicFieldDecisionSettings.get(key);
241 String dataType = getDataType(key);
242 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
243 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
246 Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
247 if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){
248 for(String keyField : dynamicFieldTreatmentAttributes.keySet()) {
249 String errorcode = keyField;
250 String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
251 createRainydayRule(decisionPolicy, errorcode, treatment, true);
254 createRule(decisionPolicy, true);
255 createRule(decisionPolicy, false);
259 setPreparedToSave(true);
263 public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException{
265 ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
266 MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
267 matchParameters.setControlLoopName(yamlParams.get("clname"));
268 if(yamlParams.containsKey("targets")){
269 String targetString = yamlParams.get("targets");
270 List<String> targets = null;
271 if(targetString!=null && !targetString.isEmpty()){
272 if (targetString.contains(",")){
273 targets = Arrays.asList(targetString.split(","));
276 targets = new ArrayList<>();
277 targets.add(targetString);
280 matchParameters.setTargets(targets);
282 GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
283 builder = builder.addGuardPolicy(policy1);
284 Map<String, String> activeTimeRange = new HashMap<>();
285 activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
286 activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
287 String blackListString = yamlParams.get("blackList");
288 List<String> blackList = null;
289 if(blackListString!=null && !blackListString.trim().isEmpty()){
290 if (blackListString.contains(",")){
291 blackList = Arrays.asList(blackListString.split(","));
294 blackList = new ArrayList<>();
295 blackList.add(blackListString);
299 Path xacmlTemplatePath;
300 ClassLoader classLoader = getClass().getClassLoader();
301 Constraint cons = new Constraint();
302 switch (ruleProvider){
304 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
305 xacmlTemplatePath = templateFile.toPath();
306 cons.setActive_time_range(activeTimeRange);
307 if(blackList==null || blackList.isEmpty()){
308 throw new BuilderException("blackList is required");
310 cons.setBlacklist(blackList);
313 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
314 xacmlTemplatePath = templateFile.toPath();
315 Map<String,String> timeWindow = new HashMap<>();
316 if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){
317 throw new BuilderException("time window is not in Integer format.");
319 String timeUnits = yamlParams.get("timeUnits");
320 if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day")
321 || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){
322 throw new BuilderException("time Units is not in proper format.");
324 timeWindow.put("value", yamlParams.get("timeWindow"));
325 timeWindow.put("units", yamlParams.get("timeUnits"));
326 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange);
329 builder = builder.addLimitConstraint(policy1.getId(), cons);
330 // Build the specification
331 Results results = builder.buildSpecification();
333 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
334 String xacmlTemplateContent;
336 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
337 HashMap<String, String> yamlSpecs = new HashMap<>();
338 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
339 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
340 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
341 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
342 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
343 yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
344 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){
345 yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString());
347 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){
348 yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value"));
349 yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units"));
351 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start"));
352 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end"));
353 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
354 // Convert the Policy into Stream input to Policy Adapter.
355 Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
356 return (PolicyType) policy;
357 } catch (IOException e) {
358 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e);
360 } catch (BuilderException e) {
361 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e);
367 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
368 DecisionSettings decisionSetting = null;
370 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
371 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
372 List<?> decisionSettingsList = getDecisionSettings.getResultList();
374 for (Object id : decisionSettingsList) {
375 decisionSetting = (DecisionSettings) id;
376 if (decisionSetting.getXacmlId().equals(settingId)) {
380 return decisionSetting;
383 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
384 RuleType rule = new RuleType();
386 rule.setRuleId(policyAdapter.getRuleID());
389 rule.setEffect(EffectType.PERMIT);
391 rule.setEffect(EffectType.DENY);
393 rule.setTarget(new TargetType());
395 // Create Target in Rule
396 AllOfType allOfInRule = new AllOfType();
398 // Creating match for ACCESS in rule target
399 MatchType accessMatch = new MatchType();
400 AttributeValueType accessAttributeValue = new AttributeValueType();
401 accessAttributeValue.setDataType(STRING_DATATYPE);
402 accessAttributeValue.getContent().add("DECIDE");
403 accessMatch.setAttributeValue(accessAttributeValue);
404 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
405 URI accessURI = null;
407 accessURI = new URI(ACTION_ID);
408 } catch (URISyntaxException e) {
409 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
411 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
412 accessAttributeDesignator.setDataType(STRING_DATATYPE);
413 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
414 accessMatch.setAttributeDesignator(accessAttributeDesignator);
415 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
417 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
418 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
419 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
420 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
422 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
423 // Values for AAF Provider are here for XML Creation.
424 ConditionType condition = new ConditionType();
425 ApplyType decisionApply = new ApplyType();
427 AttributeValueType value1 = new AttributeValueType();
428 value1.setDataType(BOOLEAN_DATATYPE);
429 value1.getContent().add("true");
431 AttributeDesignatorType value2 = new AttributeDesignatorType();
432 value2.setAttributeId(AAFEngine.AAF_RESULT);
433 value2.setCategory(CATEGORY_RESOURCE);
434 value2.setDataType(BOOLEAN_DATATYPE);
435 value2.setMustBePresent(false);
437 ApplyType innerDecisionApply = new ApplyType();
438 innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
439 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
441 decisionApply.setFunctionId(XACML3.ID_FUNCTION_BOOLEAN_EQUAL.stringValue());
442 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
443 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
444 condition.setExpression(new ObjectFactory().createApply(decisionApply));
446 ApplyType notOuterApply = new ApplyType();
447 notOuterApply.setFunctionId(FUNCTION_NOT);
448 notOuterApply.getExpression().add(condition.getExpression());
449 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
451 rule.setCondition(condition);
452 allOfInRule.getMatch().add(accessMatch);
454 AnyOfType anyOfInRule = new AnyOfType();
455 anyOfInRule.getAllOf().add(allOfInRule);
457 TargetType targetInRule = new TargetType();
458 targetInRule.getAnyOf().add(anyOfInRule);
460 rule.setTarget(targetInRule);
462 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
463 AdviceExpressionType adviceExpression = new AdviceExpressionType();
464 adviceExpression.setAdviceId(AAFPROVIDER);
465 adviceExpression.setAppliesTo(EffectType.DENY);
466 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
467 assignment.setAttributeId("aaf.response");
468 assignment.setCategory(CATEGORY_RESOURCE);
469 AttributeDesignatorType value = new AttributeDesignatorType();
470 value.setAttributeId(AAFEngine.AAF_RESPONSE);
471 value.setCategory(CATEGORY_RESOURCE);
472 value.setDataType(STRING_DATATYPE);
473 value.setMustBePresent(false);
474 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
475 adviceExpression.getAttributeAssignmentExpression().add(assignment);
476 adviceExpressions.getAdviceExpression().add(adviceExpression);
477 rule.setAdviceExpressions(adviceExpressions);
479 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
480 policyAdapter.setPolicyData(decisionPolicy);
482 }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
483 boolean isCompound = false;
484 ConditionType condition = new ConditionType();
485 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
487 for (String labelAttr : dynamicLabelRuleAlgorithms) {
488 // if the rule algorithm as a label means it is a compound
489 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
490 ApplyType decisionApply = new ApplyType();
492 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
493 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
494 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
495 decisionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
496 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
497 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
498 condition.setExpression(new ObjectFactory().createApply(decisionApply));
502 // if rule algorithm not a compound
504 condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
508 ApplyType notOuterApply = new ApplyType();
509 notOuterApply.setFunctionId(FUNCTION_NOT);
510 notOuterApply.getExpression().add(condition.getExpression());
511 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
513 rule.setCondition(condition);
514 allOfInRule.getMatch().add(accessMatch);
516 AnyOfType anyOfInRule = new AnyOfType();
517 anyOfInRule.getAllOf().add(allOfInRule);
519 TargetType targetInRule = new TargetType();
520 targetInRule.getAnyOf().add(anyOfInRule);
522 rule.setTarget(targetInRule);
524 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
525 policyAdapter.setPolicyData(decisionPolicy);
528 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
533 private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
534 RuleType rule = new RuleType();
536 rule.setRuleId(UUID.randomUUID().toString());
539 rule.setEffect(EffectType.PERMIT);
541 rule.setEffect(EffectType.DENY);
543 rule.setTarget(new TargetType());
545 // Create Target in Rule
546 AllOfType allOfInRule = new AllOfType();
548 // Creating match for DECIDE in rule target
549 MatchType accessMatch = new MatchType();
550 AttributeValueType accessAttributeValue = new AttributeValueType();
551 accessAttributeValue.setDataType(STRING_DATATYPE);
552 accessAttributeValue.getContent().add("DECIDE");
553 accessMatch.setAttributeValue(accessAttributeValue);
554 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
555 URI accessURI = null;
557 accessURI = new URI(ACTION_ID);
558 } catch (URISyntaxException e) {
559 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
561 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
562 accessAttributeDesignator.setDataType(STRING_DATATYPE);
563 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
564 accessMatch.setAttributeDesignator(accessAttributeDesignator);
565 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
567 allOfInRule.getMatch().add(accessMatch);
569 // Creating match for ErrorCode in rule target
570 MatchType errorcodeMatch = new MatchType();
571 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
572 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
573 errorcodeAttributeValue.getContent().add(errorcode);
574 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
575 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
576 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
577 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
578 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
579 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
580 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
582 allOfInRule.getMatch().add(errorcodeMatch);
584 AnyOfType anyOfInRule = new AnyOfType();
585 anyOfInRule.getAllOf().add(allOfInRule);
587 TargetType targetInRule = new TargetType();
588 targetInRule.getAnyOf().add(anyOfInRule);
590 rule.setTarget(targetInRule);
592 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
593 AdviceExpressionType adviceExpression = new AdviceExpressionType();
594 adviceExpression.setAdviceId(RAINY_DAY);
595 adviceExpression.setAppliesTo(EffectType.PERMIT);
597 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
598 assignment.setAttributeId("treatment");
599 assignment.setCategory(CATEGORY_RESOURCE);
601 AttributeValueType treatmentAttributeValue = new AttributeValueType();
602 treatmentAttributeValue.setDataType(STRING_DATATYPE);
603 treatmentAttributeValue.getContent().add(treatment);
604 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
606 adviceExpression.getAttributeAssignmentExpression().add(assignment);
607 adviceExpressions.getAdviceExpression().add(adviceExpression);
608 rule.setAdviceExpressions(adviceExpressions);
609 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
610 policyAdapter.setPolicyData(decisionPolicy);
614 // if compound setting the inner apply here
615 protected ApplyType getInnerDecisionApply(String value1Label) {
616 ApplyType decisionApply = new ApplyType();
618 // check the index for the label.
619 for (String labelAttr : dynamicLabelRuleAlgorithms) {
620 if (labelAttr.equals(value1Label)) {
621 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
622 populateDataTypeList(value1);
624 // check if the row contains label again
625 for (String labelValue : dynamicLabelRuleAlgorithms) {
626 if (labelValue.equals(value1)) {
627 return getCompoundDecisionApply(index);
631 // Getting the values from the form.
632 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
633 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
634 decisionApply.setFunctionId(getFunctionDefinitionId(functionKey));
635 // if two text field are rule attributes.
636 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
637 ApplyType innerDecisionApply1 = new ApplyType();
638 ApplyType innerDecisionApply2 = new ApplyType();
639 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
640 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
641 //If selected function is Integer function set integer functionID
642 if(functionKey.toLowerCase().contains("integer")){
643 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
644 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
645 attributeDesignator1.setDataType(INTEGER_DATATYPE);
646 attributeDesignator2.setDataType(INTEGER_DATATYPE);
648 //If selected function is not a Integer function set String functionID
649 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
650 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
651 attributeDesignator1.setDataType(STRING_DATATYPE);
652 attributeDesignator2.setDataType(STRING_DATATYPE);
654 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
655 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
656 //Here set actual field values
657 attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
658 attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
659 innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
660 innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));
661 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
662 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));
664 // if either of one text field is rule attribute.
665 if (!value1.startsWith("S_")) {
666 ApplyType innerDecisionApply = new ApplyType();
667 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
668 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
670 if (functionKey.toLowerCase().contains("integer")) {
671 innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
672 decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
673 attributeDesignator.setDataType(INTEGER_DATATYPE);
675 innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
676 decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
677 attributeDesignator.setDataType(STRING_DATATYPE);
680 String attributeId = null;
681 String attributeValue = null;
683 // Find which textField has rule attribute and set it as
684 // attributeId and the other as attributeValue.
685 attributeId = value1;
686 attributeValue = value2;
688 if (attributeId != null) {
689 attributeDesignator.setCategory(CATEGORY_RESOURCE);
690 attributeDesignator.setAttributeId(attributeId);
692 decisionConditionAttributeValue.getContent().add(attributeValue);
693 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
694 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
695 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
697 value1 = value1.substring(2, value1.length());
698 VariableReferenceType variableReferenceType = new VariableReferenceType();
699 variableReferenceType.setVariableId(value1);
701 String dataType = dataTypeList.get(index);
703 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
704 decisionConditionAttributeValue.setDataType(dataType);
705 decisionConditionAttributeValue.getContent().add(value2);
706 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
707 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
713 return decisionApply;
716 // if the rule algorithm is multiple compound one setting the apply
717 protected ApplyType getCompoundDecisionApply(int index) {
718 ApplyType decisionApply = new ApplyType();
719 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
720 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
721 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
722 decisionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
723 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
724 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
725 return decisionApply;
728 private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
729 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
730 AttributeValueType dynamicAttributeValue = new AttributeValueType();
732 dynamicAttributeValue.setDataType(dataType);
733 dynamicAttributeValue.getContent().add(value);
735 dynamicVariable.setVariableId(key);
736 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
738 return dynamicVariable;
742 private void populateDataTypeList(String value1) {
743 String dataType = null;
744 if(value1.contains("S_")) {
745 value1 = value1.substring(2, value1.length());
746 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
747 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
748 dataType = STRING_DATATYPE;
749 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
750 dataType = BOOLEAN_DATATYPE;
752 dataType = INTEGER_DATATYPE;
758 dataTypeList.add(dataType);
762 private String getDataType(String key) {
764 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
765 String dataType = null;
767 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
768 dataType = STRING_DATATYPE;
769 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
770 dataType = BOOLEAN_DATATYPE;
772 dataType = INTEGER_DATATYPE;
779 public Object getCorrectPolicyDataObject() {
780 return policyAdapter.getData();
783 public String getFunctionDefinitionId(String key){
784 FunctionDefinition object = (FunctionDefinition) commonClassDao.getDataById(FunctionDefinition.class, "short_name", key);
786 return object.getXacmlid();