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 dynamicFieldDecisionSettings = new HashMap<>();
237 // settings are dynamic so check how many rows are added and add all
238 for (String keyField : dynamicFieldDecisionSettings.keySet()) {
239 String key = keyField;
240 String value = dynamicFieldDecisionSettings.get(key);
241 String dataType = getDataType(key);
242 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
243 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
245 Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
247 if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){
248 for(String keyField : dynamicFieldTreatmentAttributes.keySet()) {
249 String errorcode = keyField;
250 String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
251 createRainydayRule(decisionPolicy, errorcode, treatment, true);
254 createRule(decisionPolicy, true);
255 createRule(decisionPolicy, false);
259 setPreparedToSave(true);
263 public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException{
265 ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
266 MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
267 matchParameters.setControlLoopName(yamlParams.get("clname"));
268 if(yamlParams.containsKey("targets")){
269 String targetString = yamlParams.get("targets");
270 List<String> targets = null;
271 if(targetString!=null && !targetString.isEmpty()){
272 if (targetString.contains(",")){
273 targets = Arrays.asList(targetString.split(","));
276 targets = new ArrayList<>();
277 targets.add(targetString);
280 matchParameters.setTargets(targets);
282 GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
283 builder = builder.addGuardPolicy(policy1);
284 Map<String, String> activeTimeRange = new HashMap<>();
285 activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
286 activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
287 String blackListString = yamlParams.get("blackList");
288 List<String> blackList = null;
289 if(blackListString!=null && !blackListString.trim().isEmpty()){
290 if (blackListString.contains(",")){
291 blackList = Arrays.asList(blackListString.split(","));
294 blackList = new ArrayList<>();
295 blackList.add(blackListString);
299 Path xacmlTemplatePath;
300 ClassLoader classLoader = getClass().getClassLoader();
301 Constraint cons = new Constraint();
302 switch (ruleProvider){
304 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
305 xacmlTemplatePath = templateFile.toPath();
306 cons.setActive_time_range(activeTimeRange);
307 if(blackList==null || blackList.isEmpty()){
308 throw new BuilderException("blackList is required");
310 cons.setBlacklist(blackList);
313 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
314 xacmlTemplatePath = templateFile.toPath();
315 Map<String,String> timeWindow = new HashMap<>();
316 if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){
317 throw new BuilderException("time window is not in Integer format.");
319 String timeUnits = yamlParams.get("timeUnits");
320 if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day")
321 || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){
322 throw new BuilderException("time Units is not in proper format.");
324 timeWindow.put("value", yamlParams.get("timeWindow"));
325 timeWindow.put("units", yamlParams.get("timeUnits"));
326 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange);
329 builder = builder.addLimitConstraint(policy1.getId(), cons);
330 // Build the specification
331 Results results = builder.buildSpecification();
333 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
334 String xacmlTemplateContent;
336 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
337 HashMap<String, String> yamlSpecs = new HashMap<>();
338 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
339 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
340 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
341 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
342 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
343 yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
344 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){
345 yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString());
347 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){
348 yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value"));
349 yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units"));
351 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start"));
352 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end"));
353 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
354 // Convert the Policy into Stream input to Policy Adapter.
355 Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
356 return (PolicyType) policy;
357 } catch (IOException e) {
358 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e);
360 } catch (BuilderException e) {
361 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e);
367 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
368 DecisionSettings decisionSetting = null;
370 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
371 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
372 List<?> decisionSettingsList = getDecisionSettings.getResultList();
374 for (Object id : decisionSettingsList) {
375 decisionSetting = (DecisionSettings) id;
376 if (decisionSetting.getXacmlId().equals(settingId)) {
380 return decisionSetting;
383 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
384 RuleType rule = new RuleType();
386 rule.setRuleId(policyAdapter.getRuleID());
389 rule.setEffect(EffectType.PERMIT);
391 rule.setEffect(EffectType.DENY);
393 rule.setTarget(new TargetType());
395 // Create Target in Rule
396 AllOfType allOfInRule = new AllOfType();
398 // Creating match for ACCESS in rule target
399 MatchType accessMatch = new MatchType();
400 AttributeValueType accessAttributeValue = new AttributeValueType();
401 accessAttributeValue.setDataType(STRING_DATATYPE);
402 accessAttributeValue.getContent().add("DECIDE");
403 accessMatch.setAttributeValue(accessAttributeValue);
404 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
405 URI accessURI = null;
407 accessURI = new URI(ACTION_ID);
408 } catch (URISyntaxException e) {
409 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
411 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
412 accessAttributeDesignator.setDataType(STRING_DATATYPE);
413 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
414 accessMatch.setAttributeDesignator(accessAttributeDesignator);
415 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
417 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
418 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
419 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
420 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
421 dropDownMap = createDropDownMap();
423 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
424 // Values for AAF Provider are here for XML Creation.
425 ConditionType condition = new ConditionType();
426 ApplyType decisionApply = new ApplyType();
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(XACML3.ID_FUNCTION_BOOLEAN_EQUAL.stringValue());
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();