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.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.pap.xacml.rest.util.JPAUtils;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
58 import org.onap.policy.rest.jpa.Datatype;
59 import org.onap.policy.rest.jpa.DecisionSettings;
60 import org.onap.policy.rest.jpa.FunctionDefinition;
61 import org.onap.policy.utils.PolicyUtils;
62 import org.onap.policy.xacml.api.XACMLErrorConstants;
63 import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
64 import org.onap.policy.xacml.util.XACMLPolicyScanner;
66 import com.att.research.xacml.api.XACML3;
67 import com.att.research.xacml.api.pap.PAPException;
68 import com.att.research.xacml.std.IdentifierImpl;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
85 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
86 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
88 public class DecisionPolicy extends Policy {
90 private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class);
92 public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
93 private static final String AAFPROVIDER = "AAF";
94 public static final String GUARD_YAML = "GUARD_YAML";
95 public static final String GUARD_BL_YAML = "GUARD_BL_YAML";
96 public static final String RAINY_DAY = "Rainy_Day";
97 private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml";
98 private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml";
100 private static final String ONAPNAME = "ONAPName";
101 private static final String POLICY_NAME = "PolicyName";
102 private static final String DESCRIPTION = "description";
105 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
106 List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
107 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
108 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
109 List<String> dataTypeList = new LinkedList<>();
111 protected Map<String, String> dropDownMap = new HashMap<>();
114 public DecisionPolicy() {
118 public DecisionPolicy(PolicyRestAdapter policyAdapter){
119 this.policyAdapter = policyAdapter;
123 public Map<String, String> savePolicies() throws PAPException {
125 Map<String, String> successMap = new HashMap<>();
126 if(isPolicyExists()){
127 successMap.put("EXISTS", "This Policy already exist on the PAP");
131 if(!isPreparedToSave()){
132 //Prep and configure the policy for saving
136 // Until here we prepared the data and here calling the method to create xml.
137 Path newPolicyPath = null;
138 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
140 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
144 //This is the method for preparing the policy for saving. We have broken it out
145 //separately because the fully configured policy is used for multiple things
147 public boolean prepareToSave() throws PAPException{
149 if(isPreparedToSave()){
150 //we have already done this
155 String policyID = policyAdapter.getPolicyID();
156 version = policyAdapter.getHighestVersion();
158 // Create the Instance for pojo, PolicyType object is used in marshalling.
159 if ("Decision".equals(policyAdapter.getPolicyType())) {
160 PolicyType policyConfig = new PolicyType();
162 policyConfig.setVersion(Integer.toString(version));
163 policyConfig.setPolicyId(policyID);
164 policyConfig.setTarget(new TargetType());
165 policyAdapter.setData(policyConfig);
167 policyName = policyAdapter.getNewFileName();
169 if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){
170 Map<String, String> yamlParams = new HashMap<>();
171 yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy");
172 String fileName = policyAdapter.getNewFileName();
173 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
174 if ((name == null) || ("".equals(name))) {
175 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
177 yamlParams.put(POLICY_NAME, name);
178 yamlParams.put(ONAPNAME, policyAdapter.getOnapName());
179 Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes();
180 yamlParams.putAll(params);
181 // Call YAML to XACML
183 PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider());
184 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
185 decisionPolicy.setVersion(Integer.toString(version));
186 policyAdapter.setPolicyData(decisionPolicy);
187 policyAdapter.setData(decisionPolicy);
188 } catch (BuilderException e) {
190 throw new PAPException(e);
192 }else if (policyAdapter.getData() != null) {
193 PolicyType decisionPolicy = (PolicyType) policyAdapter.getData();
195 decisionPolicy.setDescription(policyAdapter.getPolicyDescription());
197 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
198 AllOfType allOfOne = new AllOfType();
199 String fileName = policyAdapter.getNewFileName();
200 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
201 if ((name == null) || ("".equals(name))) {
202 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
204 allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
206 AllOfType allOf = new AllOfType();
209 allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName())));
211 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
212 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
213 dynamicFieldComponentAttributes = new HashMap<>();
216 // If there is any dynamic field attributes create the matches here
217 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
218 String key = keyField;
219 String value = dynamicFieldComponentAttributes.get(key);
220 MatchType dynamicMatch = createDynamicMatch(key, value);
221 allOf.getMatch().add(dynamicMatch);
224 AnyOfType anyOf = new AnyOfType();
225 anyOf.getAllOf().add(allOfOne);
226 anyOf.getAllOf().add(allOf);
228 TargetType target = new TargetType();
229 target.getAnyOf().add(anyOf);
230 decisionPolicy.setTarget(target);
232 Map<String, String> dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap();
233 if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals(AAFPROVIDER)||
234 policyAdapter.getRuleProvider().equals(RAINY_DAY))){
235 dynamicFieldDecisionSettings = new HashMap<>();
238 // settings are dynamic so check how many rows are added and add all
239 for (String keyField : dynamicFieldDecisionSettings.keySet()) {
240 String key = keyField;
241 String value = dynamicFieldDecisionSettings.get(key);
242 String dataType = getDataType(key);
243 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
244 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
247 Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
248 if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){
249 for(String keyField : dynamicFieldTreatmentAttributes.keySet()) {
250 String errorcode = keyField;
251 String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
252 createRainydayRule(decisionPolicy, errorcode, treatment, true);
255 createRule(decisionPolicy, true);
256 createRule(decisionPolicy, false);
260 setPreparedToSave(true);
264 public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException{
266 ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
267 MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
268 matchParameters.setControlLoopName(yamlParams.get("clname"));
269 if(yamlParams.containsKey("targets")){
270 String targetString = yamlParams.get("targets");
271 List<String> targets = null;
272 if(targetString!=null && !targetString.isEmpty()){
273 if (targetString.contains(",")){
274 targets = Arrays.asList(targetString.split(","));
277 targets = new ArrayList<>();
278 targets.add(targetString);
281 matchParameters.setTargets(targets);
283 GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
284 builder = builder.addGuardPolicy(policy1);
285 Map<String, String> activeTimeRange = new HashMap<>();
286 activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
287 activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
288 String blackListString = yamlParams.get("blackList");
289 List<String> blackList = null;
290 if(blackListString!=null && !blackListString.trim().isEmpty()){
291 if (blackListString.contains(",")){
292 blackList = Arrays.asList(blackListString.split(","));
295 blackList = new ArrayList<>();
296 blackList.add(blackListString);
300 Path xacmlTemplatePath;
301 ClassLoader classLoader = getClass().getClassLoader();
302 Constraint cons = new Constraint();
303 switch (ruleProvider){
305 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
306 xacmlTemplatePath = templateFile.toPath();
307 cons.setActive_time_range(activeTimeRange);
308 if(blackList==null || blackList.isEmpty()){
309 throw new BuilderException("blackList is required");
311 cons.setBlacklist(blackList);
314 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
315 xacmlTemplatePath = templateFile.toPath();
316 Map<String,String> timeWindow = new HashMap<>();
317 if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){
318 throw new BuilderException("time window is not in Integer format.");
320 String timeUnits = yamlParams.get("timeUnits");
321 if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day")
322 || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){
323 throw new BuilderException("time Units is not in proper format.");
325 timeWindow.put("value", yamlParams.get("timeWindow"));
326 timeWindow.put("units", yamlParams.get("timeUnits"));
327 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange);
330 builder = builder.addLimitConstraint(policy1.getId(), cons);
331 // Build the specification
332 Results results = builder.buildSpecification();
334 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
335 String xacmlTemplateContent;
337 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
338 HashMap<String, String> yamlSpecs = new HashMap<>();
339 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
340 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
341 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
342 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
343 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
344 yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
345 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){
346 yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString());
348 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){
349 yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value"));
350 yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units"));
352 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start"));
353 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end"));
354 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
355 // Convert the Policy into Stream input to Policy Adapter.
356 Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
357 return (PolicyType) policy;
358 } catch (IOException e) {
359 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e);
361 } catch (BuilderException e) {
362 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e);
368 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
369 DecisionSettings decisionSetting = null;
371 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
372 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
373 List<?> decisionSettingsList = getDecisionSettings.getResultList();
375 for (Object id : decisionSettingsList) {
376 decisionSetting = (DecisionSettings) id;
377 if (decisionSetting.getXacmlId().equals(settingId)) {
381 return decisionSetting;
384 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
385 RuleType rule = new RuleType();
387 rule.setRuleId(policyAdapter.getRuleID());
390 rule.setEffect(EffectType.PERMIT);
392 rule.setEffect(EffectType.DENY);
394 rule.setTarget(new TargetType());
396 // Create Target in Rule
397 AllOfType allOfInRule = new AllOfType();
399 // Creating match for ACCESS in rule target
400 MatchType accessMatch = new MatchType();
401 AttributeValueType accessAttributeValue = new AttributeValueType();
402 accessAttributeValue.setDataType(STRING_DATATYPE);
403 accessAttributeValue.getContent().add("DECIDE");
404 accessMatch.setAttributeValue(accessAttributeValue);
405 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
406 URI accessURI = null;
408 accessURI = new URI(ACTION_ID);
409 } catch (URISyntaxException e) {
410 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
412 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
413 accessAttributeDesignator.setDataType(STRING_DATATYPE);
414 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
415 accessMatch.setAttributeDesignator(accessAttributeDesignator);
416 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
418 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
419 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
420 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
421 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
422 dropDownMap = createDropDownMap();
424 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
425 // Values for AAF Provider are here for XML Creation.
426 ConditionType condition = new ConditionType();
427 ApplyType decisionApply = new ApplyType();
429 AttributeValueType value1 = new AttributeValueType();
430 value1.setDataType(BOOLEAN_DATATYPE);
431 value1.getContent().add("true");
433 AttributeDesignatorType value2 = new AttributeDesignatorType();
434 value2.setAttributeId(AAFEngine.AAF_RESULT);
435 value2.setCategory(CATEGORY_RESOURCE);
436 value2.setDataType(BOOLEAN_DATATYPE);
437 value2.setMustBePresent(false);
439 ApplyType innerDecisionApply = new ApplyType();
440 innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
441 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
443 decisionApply.setFunctionId(XACML3.ID_FUNCTION_BOOLEAN_EQUAL.stringValue());
444 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
445 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
446 condition.setExpression(new ObjectFactory().createApply(decisionApply));
448 ApplyType notOuterApply = new ApplyType();
449 notOuterApply.setFunctionId(FUNCTION_NOT);
450 notOuterApply.getExpression().add(condition.getExpression());
451 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
453 rule.setCondition(condition);
454 allOfInRule.getMatch().add(accessMatch);
456 AnyOfType anyOfInRule = new AnyOfType();
457 anyOfInRule.getAllOf().add(allOfInRule);
459 TargetType targetInRule = new TargetType();
460 targetInRule.getAnyOf().add(anyOfInRule);
462 rule.setTarget(targetInRule);
464 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
465 AdviceExpressionType adviceExpression = new AdviceExpressionType();
466 adviceExpression.setAdviceId(AAFPROVIDER);
467 adviceExpression.setAppliesTo(EffectType.DENY);
468 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
469 assignment.setAttributeId("aaf.response");
470 assignment.setCategory(CATEGORY_RESOURCE);
471 AttributeDesignatorType value = new AttributeDesignatorType();
472 value.setAttributeId(AAFEngine.AAF_RESPONSE);
473 value.setCategory(CATEGORY_RESOURCE);
474 value.setDataType(STRING_DATATYPE);
475 value.setMustBePresent(false);
476 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
477 adviceExpression.getAttributeAssignmentExpression().add(assignment);
478 adviceExpressions.getAdviceExpression().add(adviceExpression);
479 rule.setAdviceExpressions(adviceExpressions);
481 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
482 policyAdapter.setPolicyData(decisionPolicy);
484 }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
485 boolean isCompound = false;
486 ConditionType condition = new ConditionType();
487 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
489 for (String labelAttr : dynamicLabelRuleAlgorithms) {
490 // if the rule algorithm as a label means it is a compound
491 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
492 ApplyType decisionApply = new ApplyType();
494 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
495 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
496 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
497 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
498 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
499 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
500 condition.setExpression(new ObjectFactory().createApply(decisionApply));
504 // if rule algorithm not a compound
506 condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
510 ApplyType notOuterApply = new ApplyType();
511 notOuterApply.setFunctionId(FUNCTION_NOT);
512 notOuterApply.getExpression().add(condition.getExpression());
513 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
515 rule.setCondition(condition);
516 allOfInRule.getMatch().add(accessMatch);
518 AnyOfType anyOfInRule = new AnyOfType();
519 anyOfInRule.getAllOf().add(allOfInRule);
521 TargetType targetInRule = new TargetType();
522 targetInRule.getAnyOf().add(anyOfInRule);
524 rule.setTarget(targetInRule);
526 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
527 policyAdapter.setPolicyData(decisionPolicy);
530 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
535 private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
536 RuleType rule = new RuleType();
538 rule.setRuleId(UUID.randomUUID().toString());
541 rule.setEffect(EffectType.PERMIT);
543 rule.setEffect(EffectType.DENY);
545 rule.setTarget(new TargetType());
547 // Create Target in Rule
548 AllOfType allOfInRule = new AllOfType();
550 // Creating match for DECIDE in rule target
551 MatchType accessMatch = new MatchType();
552 AttributeValueType accessAttributeValue = new AttributeValueType();
553 accessAttributeValue.setDataType(STRING_DATATYPE);
554 accessAttributeValue.getContent().add("DECIDE");
555 accessMatch.setAttributeValue(accessAttributeValue);
556 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
557 URI accessURI = null;
559 accessURI = new URI(ACTION_ID);
560 } catch (URISyntaxException e) {
561 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
563 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
564 accessAttributeDesignator.setDataType(STRING_DATATYPE);
565 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
566 accessMatch.setAttributeDesignator(accessAttributeDesignator);
567 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
569 allOfInRule.getMatch().add(accessMatch);
571 // Creating match for ErrorCode in rule target
572 MatchType errorcodeMatch = new MatchType();
573 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
574 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
575 errorcodeAttributeValue.getContent().add(errorcode);
576 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
577 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
578 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
579 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
580 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
581 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
582 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
584 allOfInRule.getMatch().add(errorcodeMatch);
586 AnyOfType anyOfInRule = new AnyOfType();
587 anyOfInRule.getAllOf().add(allOfInRule);
589 TargetType targetInRule = new TargetType();
590 targetInRule.getAnyOf().add(anyOfInRule);
592 rule.setTarget(targetInRule);
594 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
595 AdviceExpressionType adviceExpression = new AdviceExpressionType();
596 adviceExpression.setAdviceId(RAINY_DAY);
597 adviceExpression.setAppliesTo(EffectType.PERMIT);
599 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
600 assignment.setAttributeId("treatment");
601 assignment.setCategory(CATEGORY_RESOURCE);
603 AttributeValueType treatmentAttributeValue = new AttributeValueType();
604 treatmentAttributeValue.setDataType(STRING_DATATYPE);
605 treatmentAttributeValue.getContent().add(treatment);
606 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
608 adviceExpression.getAttributeAssignmentExpression().add(assignment);
609 adviceExpressions.getAdviceExpression().add(adviceExpression);
610 rule.setAdviceExpressions(adviceExpressions);
611 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
612 policyAdapter.setPolicyData(decisionPolicy);
616 // if compound setting the inner apply here
617 protected ApplyType getInnerDecisionApply(String value1Label) {
618 ApplyType decisionApply = new ApplyType();
620 // check the index for the label.
621 for (String labelAttr : dynamicLabelRuleAlgorithms) {
622 if (labelAttr.equals(value1Label)) {
623 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
624 populateDataTypeList(value1);
626 // check if the row contains label again
627 for (String labelValue : dynamicLabelRuleAlgorithms) {
628 if (labelValue.equals(value1)) {
629 return getCompoundDecisionApply(index);
633 // Getting the values from the form.
634 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
635 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
636 decisionApply.setFunctionId(dropDownMap.get(functionKey));
637 // if two text field are rule attributes.
638 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
639 ApplyType innerDecisionApply1 = new ApplyType();
640 ApplyType innerDecisionApply2 = new ApplyType();
641 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
642 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
643 //If selected function is Integer function set integer functionID
644 if(functionKey.toLowerCase().contains("integer")){
645 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
646 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
647 attributeDesignator1.setDataType(INTEGER_DATATYPE);
648 attributeDesignator2.setDataType(INTEGER_DATATYPE);
650 //If selected function is not a Integer function set String functionID
651 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
652 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
653 attributeDesignator1.setDataType(STRING_DATATYPE);
654 attributeDesignator2.setDataType(STRING_DATATYPE);
656 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
657 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
658 //Here set actual field values
659 attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
660 attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
661 innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
662 innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));
663 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
664 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));
666 // if either of one text field is rule attribute.
667 if (!value1.startsWith("S_")) {
668 ApplyType innerDecisionApply = new ApplyType();
669 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
670 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
672 if (functionKey.toLowerCase().contains("integer")) {
673 innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
674 decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
675 attributeDesignator.setDataType(INTEGER_DATATYPE);
677 innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
678 decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
679 attributeDesignator.setDataType(STRING_DATATYPE);
682 String attributeId = null;
683 String attributeValue = null;
685 // Find which textField has rule attribute and set it as
686 // attributeId and the other as attributeValue.
687 attributeId = value1;
688 attributeValue = value2;
690 if (attributeId != null) {
691 attributeDesignator.setCategory(CATEGORY_RESOURCE);
692 attributeDesignator.setAttributeId(attributeId);
694 decisionConditionAttributeValue.getContent().add(attributeValue);
695 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
696 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
697 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
699 value1 = value1.substring(2, value1.length());
700 VariableReferenceType variableReferenceType = new VariableReferenceType();
701 variableReferenceType.setVariableId(value1);
703 String dataType = dataTypeList.get(index);
705 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
706 decisionConditionAttributeValue.setDataType(dataType);
707 decisionConditionAttributeValue.getContent().add(value2);
708 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
709 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
715 return decisionApply;
718 // if the rule algorithm is multiple compound one setting the apply
719 protected ApplyType getCompoundDecisionApply(int index) {
720 ApplyType decisionApply = new ApplyType();
721 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
722 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
723 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
724 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
725 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
726 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
727 return decisionApply;
730 private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
731 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
732 AttributeValueType dynamicAttributeValue = new AttributeValueType();
734 dynamicAttributeValue.setDataType(dataType);
735 dynamicAttributeValue.getContent().add(value);
737 dynamicVariable.setVariableId(key);
738 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
740 return dynamicVariable;
744 private void populateDataTypeList(String value1) {
745 String dataType = null;
746 if(value1.contains("S_")) {
747 value1 = value1.substring(2, value1.length());
748 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
749 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
750 dataType = STRING_DATATYPE;
751 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
752 dataType = BOOLEAN_DATATYPE;
754 dataType = INTEGER_DATATYPE;
760 dataTypeList.add(dataType);
763 private Map<String,String> createDropDownMap(){
764 JPAUtils jpaUtils = null;
766 jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
767 } catch (Exception e) {
768 LOGGER.error("Exception Occured"+e);
770 Map<String, String> dropDownOptions = new HashMap<>();
772 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
773 for (Map.Entry<Datatype,List<FunctionDefinition>> map: functionMap.entrySet()) {
774 for (FunctionDefinition functionDef : map.getValue()) {
775 dropDownOptions.put(functionDef.getShortname(),functionDef.getXacmlid());
779 return dropDownOptions;
782 private String getDataType(String key) {
784 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
785 String dataType = null;
787 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
788 dataType = STRING_DATATYPE;
789 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
790 dataType = BOOLEAN_DATATYPE;
792 dataType = INTEGER_DATATYPE;
799 public Object getCorrectPolicyDataObject() {
800 return policyAdapter.getData();