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 && !blackListString.trim().isEmpty()){
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 if(blackList==null || blackList.isEmpty()){
307 throw new BuilderException("blackList is required");
309 cons.setBlacklist(blackList);
312 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
313 xacmlTemplatePath = templateFile.toPath();
314 Map<String,String> timeWindow = new HashMap<>();
315 if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){
316 throw new BuilderException("time window is not in Integer format.");
318 String timeUnits = yamlParams.get("timeUnits");
319 if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day")
320 || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){
321 throw new BuilderException("time Units is not in proper format.");
323 timeWindow.put("value", yamlParams.get("timeWindow"));
324 timeWindow.put("units", yamlParams.get("timeUnits"));
325 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange);
328 builder = builder.addLimitConstraint(policy1.getId(), cons);
329 // Build the specification
330 Results results = builder.buildSpecification();
332 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
333 String xacmlTemplateContent;
335 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
336 HashMap<String, String> yamlSpecs = new HashMap<>();
337 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
338 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
339 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
340 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
341 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
342 yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
343 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){
344 yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString());
346 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){
347 yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value"));
348 yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units"));
350 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start"));
351 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end"));
352 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
353 // Convert the Policy into Stream input to Policy Adapter.
354 Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
355 return (PolicyType) policy;
356 } catch (IOException e) {
357 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e);
359 } catch (BuilderException e) {
360 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e);
366 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
367 DecisionSettings decisionSetting = null;
369 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
370 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
371 List<?> decisionSettingsList = getDecisionSettings.getResultList();
373 for (Object id : decisionSettingsList) {
374 decisionSetting = (DecisionSettings) id;
375 if (decisionSetting.getXacmlId().equals(settingId)) {
379 return decisionSetting;
382 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
383 RuleType rule = new RuleType();
385 rule.setRuleId(policyAdapter.getRuleID());
388 rule.setEffect(EffectType.PERMIT);
390 rule.setEffect(EffectType.DENY);
392 rule.setTarget(new TargetType());
394 // Create Target in Rule
395 AllOfType allOfInRule = new AllOfType();
397 // Creating match for ACCESS in rule target
398 MatchType accessMatch = new MatchType();
399 AttributeValueType accessAttributeValue = new AttributeValueType();
400 accessAttributeValue.setDataType(STRING_DATATYPE);
401 accessAttributeValue.getContent().add("DECIDE");
402 accessMatch.setAttributeValue(accessAttributeValue);
403 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
404 URI accessURI = null;
406 accessURI = new URI(ACTION_ID);
407 } catch (URISyntaxException e) {
408 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
410 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
411 accessAttributeDesignator.setDataType(STRING_DATATYPE);
412 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
413 accessMatch.setAttributeDesignator(accessAttributeDesignator);
414 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
416 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
417 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
418 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
419 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
420 dropDownMap = createDropDownMap();
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();
426 String selectedFunction = "boolean-equal";
428 AttributeValueType value1 = new AttributeValueType();
429 value1.setDataType(BOOLEAN_DATATYPE);
430 value1.getContent().add("true");
432 AttributeDesignatorType value2 = new AttributeDesignatorType();
433 value2.setAttributeId(AAFEngine.AAF_RESULT);
434 value2.setCategory(CATEGORY_RESOURCE);
435 value2.setDataType(BOOLEAN_DATATYPE);
436 value2.setMustBePresent(false);
438 ApplyType innerDecisionApply = new ApplyType();
439 innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
440 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
442 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
443 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
444 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
445 condition.setExpression(new ObjectFactory().createApply(decisionApply));
447 ApplyType notOuterApply = new ApplyType();
448 notOuterApply.setFunctionId(FUNCTION_NOT);
449 notOuterApply.getExpression().add(condition.getExpression());
450 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
452 rule.setCondition(condition);
453 allOfInRule.getMatch().add(accessMatch);
455 AnyOfType anyOfInRule = new AnyOfType();
456 anyOfInRule.getAllOf().add(allOfInRule);
458 TargetType targetInRule = new TargetType();
459 targetInRule.getAnyOf().add(anyOfInRule);
461 rule.setTarget(targetInRule);
463 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
464 AdviceExpressionType adviceExpression = new AdviceExpressionType();
465 adviceExpression.setAdviceId(AAFPROVIDER);
466 adviceExpression.setAppliesTo(EffectType.DENY);
467 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
468 assignment.setAttributeId("aaf.response");
469 assignment.setCategory(CATEGORY_RESOURCE);
470 AttributeDesignatorType value = new AttributeDesignatorType();
471 value.setAttributeId(AAFEngine.AAF_RESPONSE);
472 value.setCategory(CATEGORY_RESOURCE);
473 value.setDataType(STRING_DATATYPE);
474 value.setMustBePresent(false);
475 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
476 adviceExpression.getAttributeAssignmentExpression().add(assignment);
477 adviceExpressions.getAdviceExpression().add(adviceExpression);
478 rule.setAdviceExpressions(adviceExpressions);
480 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
481 policyAdapter.setPolicyData(decisionPolicy);
483 }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
484 boolean isCompound = false;
485 ConditionType condition = new ConditionType();
486 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
488 for (String labelAttr : dynamicLabelRuleAlgorithms) {
489 // if the rule algorithm as a label means it is a compound
490 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
491 ApplyType decisionApply = new ApplyType();
493 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
494 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
495 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
496 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
497 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
498 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
499 condition.setExpression(new ObjectFactory().createApply(decisionApply));
503 // if rule algorithm not a compound
505 condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
509 ApplyType notOuterApply = new ApplyType();
510 notOuterApply.setFunctionId(FUNCTION_NOT);
511 notOuterApply.getExpression().add(condition.getExpression());
512 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
514 rule.setCondition(condition);
515 allOfInRule.getMatch().add(accessMatch);
517 AnyOfType anyOfInRule = new AnyOfType();
518 anyOfInRule.getAllOf().add(allOfInRule);
520 TargetType targetInRule = new TargetType();
521 targetInRule.getAnyOf().add(anyOfInRule);
523 rule.setTarget(targetInRule);
525 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
526 policyAdapter.setPolicyData(decisionPolicy);
529 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
534 private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
535 RuleType rule = new RuleType();
537 rule.setRuleId(UUID.randomUUID().toString());
540 rule.setEffect(EffectType.PERMIT);
542 rule.setEffect(EffectType.DENY);
544 rule.setTarget(new TargetType());
546 // Create Target in Rule
547 AllOfType allOfInRule = new AllOfType();
549 // Creating match for DECIDE in rule target
550 MatchType accessMatch = new MatchType();
551 AttributeValueType accessAttributeValue = new AttributeValueType();
552 accessAttributeValue.setDataType(STRING_DATATYPE);
553 accessAttributeValue.getContent().add("DECIDE");
554 accessMatch.setAttributeValue(accessAttributeValue);
555 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
556 URI accessURI = null;
558 accessURI = new URI(ACTION_ID);
559 } catch (URISyntaxException e) {
560 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
562 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
563 accessAttributeDesignator.setDataType(STRING_DATATYPE);
564 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
565 accessMatch.setAttributeDesignator(accessAttributeDesignator);
566 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
568 allOfInRule.getMatch().add(accessMatch);
570 // Creating match for ErrorCode in rule target
571 MatchType errorcodeMatch = new MatchType();
572 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
573 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
574 errorcodeAttributeValue.getContent().add(errorcode);
575 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
576 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
577 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
578 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
579 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
580 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
581 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
583 allOfInRule.getMatch().add(errorcodeMatch);
585 AnyOfType anyOfInRule = new AnyOfType();
586 anyOfInRule.getAllOf().add(allOfInRule);
588 TargetType targetInRule = new TargetType();
589 targetInRule.getAnyOf().add(anyOfInRule);
591 rule.setTarget(targetInRule);
593 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
594 AdviceExpressionType adviceExpression = new AdviceExpressionType();
595 adviceExpression.setAdviceId(RAINY_DAY);
596 adviceExpression.setAppliesTo(EffectType.PERMIT);
598 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
599 assignment.setAttributeId("treatment");
600 assignment.setCategory(CATEGORY_RESOURCE);
602 AttributeValueType treatmentAttributeValue = new AttributeValueType();
603 treatmentAttributeValue.setDataType(STRING_DATATYPE);
604 treatmentAttributeValue.getContent().add(treatment);
605 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
607 adviceExpression.getAttributeAssignmentExpression().add(assignment);
608 adviceExpressions.getAdviceExpression().add(adviceExpression);
609 rule.setAdviceExpressions(adviceExpressions);
610 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
611 policyAdapter.setPolicyData(decisionPolicy);
615 // if compound setting the inner apply here
616 protected ApplyType getInnerDecisionApply(String value1Label) {
617 ApplyType decisionApply = new ApplyType();
619 // check the index for the label.
620 for (String labelAttr : dynamicLabelRuleAlgorithms) {
621 if (labelAttr.equals(value1Label)) {
622 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
623 populateDataTypeList(value1);
625 // check if the row contains label again
626 for (String labelValue : dynamicLabelRuleAlgorithms) {
627 if (labelValue.equals(value1)) {
628 return getCompoundDecisionApply(index);
632 // Getting the values from the form.
633 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
634 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
635 decisionApply.setFunctionId(dropDownMap.get(functionKey));
636 // if two text field are rule attributes.
637 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
638 ApplyType innerDecisionApply1 = new ApplyType();
639 ApplyType innerDecisionApply2 = new ApplyType();
640 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
641 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
642 //If selected function is Integer function set integer functionID
643 if(functionKey.toLowerCase().contains("integer")){
644 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
645 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
646 attributeDesignator1.setDataType(INTEGER_DATATYPE);
647 attributeDesignator2.setDataType(INTEGER_DATATYPE);
649 //If selected function is not a Integer function set String functionID
650 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
651 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
652 attributeDesignator1.setDataType(STRING_DATATYPE);
653 attributeDesignator2.setDataType(STRING_DATATYPE);
655 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
656 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
657 //Here set actual field values
658 attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
659 attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
660 innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
661 innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));
662 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
663 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));
665 // if either of one text field is rule attribute.
666 if (!value1.startsWith("S_")) {
667 ApplyType innerDecisionApply = new ApplyType();
668 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
669 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
671 if (functionKey.toLowerCase().contains("integer")) {
672 innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
673 decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
674 attributeDesignator.setDataType(INTEGER_DATATYPE);
676 innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
677 decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
678 attributeDesignator.setDataType(STRING_DATATYPE);
681 String attributeId = null;
682 String attributeValue = null;
684 // Find which textField has rule attribute and set it as
685 // attributeId and the other as attributeValue.
686 attributeId = value1;
687 attributeValue = value2;
689 if (attributeId != null) {
690 attributeDesignator.setCategory(CATEGORY_RESOURCE);
691 attributeDesignator.setAttributeId(attributeId);
693 decisionConditionAttributeValue.getContent().add(attributeValue);
694 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
695 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
696 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
698 value1 = value1.substring(2, value1.length());
699 VariableReferenceType variableReferenceType = new VariableReferenceType();
700 variableReferenceType.setVariableId(value1);
702 String dataType = dataTypeList.get(index);
704 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
705 decisionConditionAttributeValue.setDataType(dataType);
706 decisionConditionAttributeValue.getContent().add(value2);
707 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
708 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
714 return decisionApply;
717 // if the rule algorithm is multiple compound one setting the apply
718 protected ApplyType getCompoundDecisionApply(int index) {
719 ApplyType decisionApply = new ApplyType();
720 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
721 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
722 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
723 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
724 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
725 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
726 return decisionApply;
729 private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
730 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
731 AttributeValueType dynamicAttributeValue = new AttributeValueType();
733 dynamicAttributeValue.setDataType(dataType);
734 dynamicAttributeValue.getContent().add(value);
736 dynamicVariable.setVariableId(key);
737 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
739 return dynamicVariable;
743 private void populateDataTypeList(String value1) {
744 String dataType = null;
745 if(value1.contains("S_")) {
746 value1 = value1.substring(2, value1.length());
747 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
748 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
749 dataType = STRING_DATATYPE;
750 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
751 dataType = BOOLEAN_DATATYPE;
753 dataType = INTEGER_DATATYPE;
759 dataTypeList.add(dataType);
762 private Map<String,String> createDropDownMap(){
763 JPAUtils jpaUtils = null;
765 jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
766 } catch (Exception e) {
767 LOGGER.error("Exception Occured"+e);
769 Map<String, String> dropDownOptions = new HashMap<>();
771 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
772 for (Map.Entry<Datatype,List<FunctionDefinition>> map: functionMap.entrySet()) {
773 for (FunctionDefinition functionDef : map.getValue()) {
774 dropDownOptions.put(functionDef.getShortname(),functionDef.getXacmlid());
778 return dropDownOptions;
781 private String getDataType(String key) {
783 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
784 String dataType = null;
786 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
787 dataType = STRING_DATATYPE;
788 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
789 dataType = BOOLEAN_DATATYPE;
791 dataType = INTEGER_DATATYPE;
798 public Object getCorrectPolicyDataObject() {
799 return policyAdapter.getData();