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.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 protected Map<String, String> dropDownMap = new HashMap<>();
113 public DecisionPolicy() {
117 public DecisionPolicy(PolicyRestAdapter policyAdapter){
118 this.policyAdapter = policyAdapter;
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 dynamicFieldDecisionSettings = new HashMap<>();
236 // settings are dynamic so check how many rows are added and add all
237 for (String keyField : dynamicFieldDecisionSettings.keySet()) {
238 String key = keyField;
239 String value = dynamicFieldDecisionSettings.get(key);
240 String dataType = getDataType(key);
241 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
242 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
244 Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
246 if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){
247 for(String keyField : dynamicFieldTreatmentAttributes.keySet()) {
248 String errorcode = keyField;
249 String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
250 createRainydayRule(decisionPolicy, errorcode, treatment, true);
253 createRule(decisionPolicy, true);
254 createRule(decisionPolicy, false);
258 setPreparedToSave(true);
262 public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException{
264 ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
265 MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
266 matchParameters.setControlLoopName(yamlParams.get("clname"));
267 if(yamlParams.containsKey("targets")){
268 String targetString = yamlParams.get("targets");
269 List<String> targets = null;
270 if(targetString!=null && !targetString.isEmpty()){
271 if (targetString.contains(",")){
272 targets = Arrays.asList(targetString.split(","));
275 targets = new ArrayList<>();
276 targets.add(targetString);
279 matchParameters.setTargets(targets);
281 GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
282 builder = builder.addGuardPolicy(policy1);
283 Map<String, String> activeTimeRange = new HashMap<>();
284 activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
285 activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
286 String blackListString = yamlParams.get("blackList");
287 List<String> blackList = null;
288 if(blackListString!=null){
289 if (blackListString.contains(",")){
290 blackList = Arrays.asList(blackListString.split(","));
293 blackList = new ArrayList<>();
294 blackList.add(blackListString);
298 Path xacmlTemplatePath;
299 ClassLoader classLoader = getClass().getClassLoader();
300 Constraint cons = new Constraint();
301 switch (ruleProvider){
303 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
304 xacmlTemplatePath = templateFile.toPath();
305 cons.setActive_time_range(activeTimeRange);
306 cons.setBlacklist(blackList);
309 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
310 xacmlTemplatePath = templateFile.toPath();
311 Map<String,String> timeWindow = new HashMap<>();
312 if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){
313 throw new BuilderException("time window is not in Integer format.");
315 String timeUnits = yamlParams.get("timeUnits");
316 if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day")
317 || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){
318 throw new BuilderException("time Units is not in proper format.");
320 timeWindow.put("value", yamlParams.get("timeWindow"));
321 timeWindow.put("units", yamlParams.get("timeUnits"));
322 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange);
325 builder = builder.addLimitConstraint(policy1.getId(), cons);
326 // Build the specification
327 Results results = builder.buildSpecification();
329 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
330 String xacmlTemplateContent;
332 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
333 HashMap<String, String> yamlSpecs = new HashMap<>();
334 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
335 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
336 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
337 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
338 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
339 yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
340 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){
341 yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString());
343 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){
344 yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value"));
345 yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units"));
347 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start"));
348 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end"));
349 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
350 // Convert the Policy into Stream input to Policy Adapter.
351 Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
352 return (PolicyType) policy;
353 } catch (IOException e) {
354 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e);
356 } catch (BuilderException e) {
357 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e);
363 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
364 DecisionSettings decisionSetting = null;
366 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
367 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
368 List<?> decisionSettingsList = getDecisionSettings.getResultList();
370 for (Object id : decisionSettingsList) {
371 decisionSetting = (DecisionSettings) id;
372 if (decisionSetting.getXacmlId().equals(settingId)) {
376 return decisionSetting;
379 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
380 RuleType rule = new RuleType();
382 rule.setRuleId(policyAdapter.getRuleID());
385 rule.setEffect(EffectType.PERMIT);
387 rule.setEffect(EffectType.DENY);
389 rule.setTarget(new TargetType());
391 // Create Target in Rule
392 AllOfType allOfInRule = new AllOfType();
394 // Creating match for ACCESS in rule target
395 MatchType accessMatch = new MatchType();
396 AttributeValueType accessAttributeValue = new AttributeValueType();
397 accessAttributeValue.setDataType(STRING_DATATYPE);
398 accessAttributeValue.getContent().add("DECIDE");
399 accessMatch.setAttributeValue(accessAttributeValue);
400 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
401 URI accessURI = null;
403 accessURI = new URI(ACTION_ID);
404 } catch (URISyntaxException e) {
405 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
407 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
408 accessAttributeDesignator.setDataType(STRING_DATATYPE);
409 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
410 accessMatch.setAttributeDesignator(accessAttributeDesignator);
411 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
413 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
414 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
415 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
416 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
417 dropDownMap = createDropDownMap();
419 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
420 // Values for AAF Provider are here for XML Creation.
421 ConditionType condition = new ConditionType();
422 ApplyType decisionApply = new ApplyType();
423 String selectedFunction = "boolean-equal";
425 AttributeValueType value1 = new AttributeValueType();
426 value1.setDataType(BOOLEAN_DATATYPE);
427 value1.getContent().add("true");
429 AttributeDesignatorType value2 = new AttributeDesignatorType();
430 value2.setAttributeId(AAFEngine.AAF_RESULT);
431 value2.setCategory(CATEGORY_RESOURCE);
432 value2.setDataType(BOOLEAN_DATATYPE);
433 value2.setMustBePresent(false);
435 ApplyType innerDecisionApply = new ApplyType();
436 innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
437 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
439 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
440 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
441 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
442 condition.setExpression(new ObjectFactory().createApply(decisionApply));
444 ApplyType notOuterApply = new ApplyType();
445 notOuterApply.setFunctionId(FUNCTION_NOT);
446 notOuterApply.getExpression().add(condition.getExpression());
447 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
449 rule.setCondition(condition);
450 allOfInRule.getMatch().add(accessMatch);
452 AnyOfType anyOfInRule = new AnyOfType();
453 anyOfInRule.getAllOf().add(allOfInRule);
455 TargetType targetInRule = new TargetType();
456 targetInRule.getAnyOf().add(anyOfInRule);
458 rule.setTarget(targetInRule);
460 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
461 AdviceExpressionType adviceExpression = new AdviceExpressionType();
462 adviceExpression.setAdviceId(AAFPROVIDER);
463 adviceExpression.setAppliesTo(EffectType.DENY);
464 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
465 assignment.setAttributeId("aaf.response");
466 assignment.setCategory(CATEGORY_RESOURCE);
467 AttributeDesignatorType value = new AttributeDesignatorType();
468 value.setAttributeId(AAFEngine.AAF_RESPONSE);
469 value.setCategory(CATEGORY_RESOURCE);
470 value.setDataType(STRING_DATATYPE);
471 value.setMustBePresent(false);
472 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
473 adviceExpression.getAttributeAssignmentExpression().add(assignment);
474 adviceExpressions.getAdviceExpression().add(adviceExpression);
475 rule.setAdviceExpressions(adviceExpressions);
477 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
478 policyAdapter.setPolicyData(decisionPolicy);
480 }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
481 boolean isCompound = false;
482 ConditionType condition = new ConditionType();
483 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
485 for (String labelAttr : dynamicLabelRuleAlgorithms) {
486 // if the rule algorithm as a label means it is a compound
487 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
488 ApplyType decisionApply = new ApplyType();
490 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
491 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
492 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
493 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
494 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
495 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
496 condition.setExpression(new ObjectFactory().createApply(decisionApply));
500 // if rule algorithm not a compound
502 condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
506 ApplyType notOuterApply = new ApplyType();
507 notOuterApply.setFunctionId(FUNCTION_NOT);
508 notOuterApply.getExpression().add(condition.getExpression());
509 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
511 rule.setCondition(condition);
512 allOfInRule.getMatch().add(accessMatch);
514 AnyOfType anyOfInRule = new AnyOfType();
515 anyOfInRule.getAllOf().add(allOfInRule);
517 TargetType targetInRule = new TargetType();
518 targetInRule.getAnyOf().add(anyOfInRule);
520 rule.setTarget(targetInRule);
522 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
523 policyAdapter.setPolicyData(decisionPolicy);
526 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
531 private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
532 RuleType rule = new RuleType();
534 rule.setRuleId(UUID.randomUUID().toString());
537 rule.setEffect(EffectType.PERMIT);
539 rule.setEffect(EffectType.DENY);
541 rule.setTarget(new TargetType());
543 // Create Target in Rule
544 AllOfType allOfInRule = new AllOfType();
546 // Creating match for DECIDE in rule target
547 MatchType accessMatch = new MatchType();
548 AttributeValueType accessAttributeValue = new AttributeValueType();
549 accessAttributeValue.setDataType(STRING_DATATYPE);
550 accessAttributeValue.getContent().add("DECIDE");
551 accessMatch.setAttributeValue(accessAttributeValue);
552 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
553 URI accessURI = null;
555 accessURI = new URI(ACTION_ID);
556 } catch (URISyntaxException e) {
557 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
559 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
560 accessAttributeDesignator.setDataType(STRING_DATATYPE);
561 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
562 accessMatch.setAttributeDesignator(accessAttributeDesignator);
563 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
565 allOfInRule.getMatch().add(accessMatch);
567 // Creating match for ErrorCode in rule target
568 MatchType errorcodeMatch = new MatchType();
569 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
570 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
571 errorcodeAttributeValue.getContent().add(errorcode);
572 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
573 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
574 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
575 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
576 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
577 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
578 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
580 allOfInRule.getMatch().add(errorcodeMatch);
582 AnyOfType anyOfInRule = new AnyOfType();
583 anyOfInRule.getAllOf().add(allOfInRule);
585 TargetType targetInRule = new TargetType();
586 targetInRule.getAnyOf().add(anyOfInRule);
588 rule.setTarget(targetInRule);
590 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
591 AdviceExpressionType adviceExpression = new AdviceExpressionType();
592 adviceExpression.setAdviceId(RAINY_DAY);
593 adviceExpression.setAppliesTo(EffectType.PERMIT);
595 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
596 assignment.setAttributeId("treatment");
597 assignment.setCategory(CATEGORY_RESOURCE);
599 AttributeValueType treatmentAttributeValue = new AttributeValueType();
600 treatmentAttributeValue.setDataType(STRING_DATATYPE);
601 treatmentAttributeValue.getContent().add(treatment);
602 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
604 adviceExpression.getAttributeAssignmentExpression().add(assignment);
605 adviceExpressions.getAdviceExpression().add(adviceExpression);
606 rule.setAdviceExpressions(adviceExpressions);
607 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
608 policyAdapter.setPolicyData(decisionPolicy);
612 // if compound setting the inner apply here
613 protected ApplyType getInnerDecisionApply(String value1Label) {
614 ApplyType decisionApply = new ApplyType();
616 // check the index for the label.
617 for (String labelAttr : dynamicLabelRuleAlgorithms) {
618 if (labelAttr.equals(value1Label)) {
619 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
620 populateDataTypeList(value1);
622 // check if the row contains label again
623 for (String labelValue : dynamicLabelRuleAlgorithms) {
624 if (labelValue.equals(value1)) {
625 return getCompoundDecisionApply(index);
629 // Getting the values from the form.
630 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
631 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
632 decisionApply.setFunctionId(dropDownMap.get(functionKey));
633 // if two text field are rule attributes.
634 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
635 ApplyType innerDecisionApply1 = new ApplyType();
636 ApplyType innerDecisionApply2 = new ApplyType();
637 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
638 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
639 //If selected function is Integer function set integer functionID
640 if(functionKey.toLowerCase().contains("integer")){
641 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
642 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
643 attributeDesignator1.setDataType(INTEGER_DATATYPE);
644 attributeDesignator2.setDataType(INTEGER_DATATYPE);
646 //If selected function is not a Integer function set String functionID
647 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
648 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
649 attributeDesignator1.setDataType(STRING_DATATYPE);
650 attributeDesignator2.setDataType(STRING_DATATYPE);
652 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
653 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
654 //Here set actual field values
655 attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
656 attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
657 innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
658 innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));
659 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
660 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));
662 // if either of one text field is rule attribute.
663 if (!value1.startsWith("S_")) {
664 ApplyType innerDecisionApply = new ApplyType();
665 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
666 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
668 if (functionKey.toLowerCase().contains("integer")) {
669 innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
670 decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
671 attributeDesignator.setDataType(INTEGER_DATATYPE);
673 innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
674 decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
675 attributeDesignator.setDataType(STRING_DATATYPE);
678 String attributeId = null;
679 String attributeValue = null;
681 // Find which textField has rule attribute and set it as
682 // attributeId and the other as attributeValue.
683 attributeId = value1;
684 attributeValue = value2;
686 if (attributeId != null) {
687 attributeDesignator.setCategory(CATEGORY_RESOURCE);
688 attributeDesignator.setAttributeId(attributeId);
690 decisionConditionAttributeValue.getContent().add(attributeValue);
691 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
692 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
693 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
695 value1 = value1.substring(2, value1.length());
696 VariableReferenceType variableReferenceType = new VariableReferenceType();
697 variableReferenceType.setVariableId(value1);
699 String dataType = dataTypeList.get(index);
701 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
702 decisionConditionAttributeValue.setDataType(dataType);
703 decisionConditionAttributeValue.getContent().add(value2);
704 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
705 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
711 return decisionApply;
714 // if the rule algorithm is multiple compound one setting the apply
715 protected ApplyType getCompoundDecisionApply(int index) {
716 ApplyType decisionApply = new ApplyType();
717 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
718 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
719 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
720 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
721 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
722 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
723 return decisionApply;
726 private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
727 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
728 AttributeValueType dynamicAttributeValue = new AttributeValueType();
730 dynamicAttributeValue.setDataType(dataType);
731 dynamicAttributeValue.getContent().add(value);
733 dynamicVariable.setVariableId(key);
734 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
736 return dynamicVariable;
740 private void populateDataTypeList(String value1) {
741 String dataType = null;
742 if(value1.contains("S_")) {
743 value1 = value1.substring(2, value1.length());
744 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
745 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
746 dataType = STRING_DATATYPE;
747 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
748 dataType = BOOLEAN_DATATYPE;
750 dataType = INTEGER_DATATYPE;
756 dataTypeList.add(dataType);
759 private Map<String,String> createDropDownMap(){
760 JPAUtils jpaUtils = null;
762 jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
763 } catch (Exception e) {
764 LOGGER.error("Exception Occured"+e);
766 Map<String, String> dropDownOptions = new HashMap<>();
768 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
769 for (Map.Entry<Datatype,List<FunctionDefinition>> map: functionMap.entrySet()) {
770 for (FunctionDefinition functionDef : map.getValue()) {
771 dropDownOptions.put(functionDef.getShortname(),functionDef.getXacmlid());
775 return dropDownOptions;
778 private String getDataType(String key) {
780 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
781 String dataType = null;
783 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
784 dataType = STRING_DATATYPE;
785 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
786 dataType = BOOLEAN_DATATYPE;
788 dataType = INTEGER_DATATYPE;
795 public Object getCorrectPolicyDataObject() {
796 return policyAdapter.getData();