2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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 com.att.research.xacml.api.XACML3;
24 import com.att.research.xacml.api.pap.PAPException;
25 import com.att.research.xacml.std.IdentifierImpl;
26 import java.io.ByteArrayInputStream;
28 import java.io.IOException;
29 import java.io.PrintWriter;
31 import java.net.URISyntaxException;
32 import java.nio.charset.StandardCharsets;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.HashMap;
39 import java.util.LinkedList;
40 import java.util.List;
42 import java.util.UUID;
43 import javax.script.SimpleBindings;
44 import org.apache.commons.lang3.StringEscapeUtils;
45 import org.apache.commons.lang3.StringUtils;
46 import org.onap.policy.common.logging.eelf.MessageCodes;
47 import org.onap.policy.common.logging.eelf.PolicyLogger;
48 import org.onap.policy.common.logging.flexlogger.FlexLogger;
49 import org.onap.policy.common.logging.flexlogger.Logger;
50 import org.onap.policy.controlloop.policy.builder.BuilderException;
51 import org.onap.policy.controlloop.policy.builder.Results;
52 import org.onap.policy.controlloop.policy.guard.Constraint;
53 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
54 import org.onap.policy.controlloop.policy.guard.Guard;
55 import org.onap.policy.controlloop.policy.guard.GuardPolicy;
56 import org.onap.policy.controlloop.policy.guard.MatchParameters;
57 import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder;
58 import org.onap.policy.rest.adapter.PolicyRestAdapter;
59 import org.onap.policy.rest.dao.CommonClassDao;
60 import org.onap.policy.rest.jpa.DecisionSettings;
61 import org.onap.policy.rest.jpa.FunctionDefinition;
62 import org.onap.policy.utils.PolicyUtils;
63 import org.onap.policy.xacml.api.XACMLErrorConstants;
64 import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
65 import org.onap.policy.xacml.util.XACMLPolicyScanner;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.stereotype.Component;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
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;
89 public class DecisionPolicy extends Policy {
91 private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class);
93 public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
94 private static final String AAFPROVIDER = "AAF";
95 public static final String GUARD_YAML = "GUARD_YAML";
96 public static final String GUARD_BL_YAML = "GUARD_BL_YAML";
97 public static final String GUARD_MIN_MAX = "GUARD_MIN_MAX";
98 public static final String RAINY_DAY = "Rainy_Day";
99 public static final String MS_MODEL = "MicroService_Model";
100 private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml";
101 private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml";
102 private static final String XACML_GUARD_MIN_MAX_TEMPLATE = "Decision_GuardMinMaxPolicyTemplate.xml";
104 private static final String ONAPNAME = "ONAPName";
105 private static final String POLICY_NAME = "PolicyName";
106 private static final String DESCRIPTION = "description";
109 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
110 List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
111 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
112 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
113 List<String> dataTypeList = new LinkedList<>();
115 private static CommonClassDao commonClassDao;
117 public DecisionPolicy() {
122 public DecisionPolicy(CommonClassDao commonClassDao) {
123 DecisionPolicy.commonClassDao = commonClassDao;
126 public DecisionPolicy(PolicyRestAdapter policyAdapter) {
127 this.policyAdapter = policyAdapter;
128 this.commonClassDao = commonClassDao;
132 public Map<String, String> savePolicies() throws PAPException {
134 Map<String, String> successMap = new HashMap<>();
135 if (isPolicyExists()) {
136 successMap.put("EXISTS", "This Policy already exist on the PAP");
140 if (!isPreparedToSave()) {
141 // Prep and configure the policy for saving
145 // Until here we prepared the data and here calling the method to create xml.
146 Path newPolicyPath = null;
147 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
149 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
154 * Scan the Raw Policy data and set to PolicyAdapter.
156 private void readRawPolicyData() {
158 if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) {
159 policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils
160 .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
162 policy = XACMLPolicyScanner.readPolicy(
163 new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8)));
165 String policyRawDesc;
166 if (policy instanceof PolicySetType) {
168 ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
169 ((PolicySetType) policy).setDescription(policyRawDesc);
171 policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
172 ((PolicyType) policy).setDescription(policyRawDesc);
174 policyAdapter.setPolicyData(policy);
175 policyAdapter.setData(policy);
176 setPreparedToSave(true);
180 // This is the method for preparing the policy for saving. We have broken it out
181 // separately because the fully configured policy is used for multiple things
183 public boolean prepareToSave() throws PAPException {
185 if (isPreparedToSave()) {
186 // we have already done this
191 String policyID = policyAdapter.getPolicyID();
192 version = policyAdapter.getHighestVersion();
194 if ("Raw".equals(policyAdapter.getRuleProvider())) {
198 // Create the Instance for pojo, PolicyType object is used in marshalling.
199 if ("Decision".equals(policyAdapter.getPolicyType())) {
200 PolicyType policyConfig = new PolicyType();
202 policyConfig.setVersion(Integer.toString(version));
203 policyConfig.setPolicyId(policyID);
204 policyConfig.setTarget(new TargetType());
205 policyAdapter.setData(policyConfig);
207 policyName = policyAdapter.getNewFileName();
209 if(policyAdapter.getRuleProvider().equals(GUARD_YAML) ||
210 policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) ||
211 policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){
213 Map<String, String> yamlParams = new HashMap<>();
214 String blackListEntryType = policyAdapter.getBlackListEntryType() != null
215 ? policyAdapter.getBlackListEntryType() : "Use Manual Entry";
216 String description = policyAdapter.getPolicyDescription() != null ? policyAdapter.getPolicyDescription()
217 : "YAML Guard Policy";
218 yamlParams.put(DESCRIPTION, description + "@blEntry@" + blackListEntryType + "@blEntry@");
219 String fileName = policyAdapter.getNewFileName();
220 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
221 if ((name == null) || ("".equals(name))) {
222 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
224 yamlParams.put(POLICY_NAME, name);
225 yamlParams.put(ONAPNAME, policyAdapter.getOnapName());
226 Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes();
227 yamlParams.putAll(params);
228 // Call YAML to XACML
230 PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider());
231 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
232 decisionPolicy.setVersion(Integer.toString(version));
233 policyAdapter.setPolicyData(decisionPolicy);
234 policyAdapter.setData(decisionPolicy);
235 } catch (BuilderException e) {
237 throw new PAPException(e);
239 } else if (policyAdapter.getData() != null) {
240 PolicyType decisionPolicy = (PolicyType) policyAdapter.getData();
242 decisionPolicy.setDescription(policyAdapter.getPolicyDescription());
244 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
245 AllOfType allOfOne = new AllOfType();
246 String fileName = policyAdapter.getNewFileName();
247 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
248 if ((name == null) || ("".equals(name))) {
249 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
251 allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
253 AllOfType allOf = new AllOfType();
256 allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName())));
258 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
259 if (policyAdapter.getRuleProvider() != null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)) {
260 dynamicFieldComponentAttributes = new HashMap<>();
263 // If there is any dynamic field attributes create the matches here
264 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
265 String key = keyField;
266 String value = dynamicFieldComponentAttributes.get(key);
267 MatchType dynamicMatch = createDynamicMatch(key, value);
268 allOf.getMatch().add(dynamicMatch);
271 AnyOfType anyOf = new AnyOfType();
272 anyOf.getAllOf().add(allOfOne);
273 anyOf.getAllOf().add(allOf);
275 TargetType target = new TargetType();
276 target.getAnyOf().add(anyOf);
277 decisionPolicy.setTarget(target);
279 Map<String, String> dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap();
280 if (policyAdapter.getRuleProvider() != null && (policyAdapter.getRuleProvider().equals(AAFPROVIDER)
281 || policyAdapter.getRuleProvider().equals(RAINY_DAY))) {
282 dynamicFieldDecisionSettings = new HashMap<>();
285 // settings are dynamic so check how many rows are added and add all
286 for (String keyField : dynamicFieldDecisionSettings.keySet()) {
287 String key = keyField;
288 String value = dynamicFieldDecisionSettings.get(key);
289 String dataType = getDataType(key);
290 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
291 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
294 Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
295 if (policyAdapter.getRuleProvider().equals(RAINY_DAY)) {
296 for (String keyField : dynamicFieldTreatmentAttributes.keySet()) {
297 String errorcode = keyField;
298 String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
299 createRainydayRule(decisionPolicy, errorcode, treatment, true);
302 createRule(decisionPolicy, true);
303 createRule(decisionPolicy, false);
307 setPreparedToSave(true);
311 public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException {
313 ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
314 MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
315 matchParameters.setControlLoopName(yamlParams.get("clname"));
316 if (yamlParams.containsKey("targets")) {
317 String targetString = yamlParams.get("targets");
318 List<String> targets = null;
319 if (targetString != null && !targetString.isEmpty()) {
320 if (targetString.contains(",")) {
321 targets = Arrays.asList(targetString.split(","));
323 targets = new ArrayList<>();
324 targets.add(targetString);
327 matchParameters.setTargets(targets);
329 GuardPolicy policy1 = new GuardPolicy(
330 (policyAdapter.getUuid() != null ? policyAdapter.getUuid() : UUID.randomUUID().toString()),
331 yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
332 builder = builder.addGuardPolicy(policy1);
333 Map<String, String> activeTimeRange = new HashMap<>();
334 activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
335 activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
336 String blackListString = yamlParams.get("blackList");
337 List<String> blackList = null;
338 if (blackListString != null && !blackListString.trim().isEmpty()) {
339 if (blackListString.contains(",")) {
340 blackList = Arrays.asList(blackListString.split(","));
342 blackList = new ArrayList<>();
343 blackList.add(blackListString);
346 if (yamlParams.containsKey("appendBlackList")) {
347 String appendBlackListString = yamlParams.get("appendBlackList");
348 List<String> appendBlackList = null;
349 if (appendBlackListString != null && !appendBlackListString.trim().isEmpty()) {
350 appendBlackList = Arrays.asList(appendBlackListString.split(","));
351 for (int i = 0; i < appendBlackList.size(); i++) {
352 blackList.remove(appendBlackList.get(i));
357 Path xacmlTemplatePath;
358 ClassLoader classLoader = getClass().getClassLoader();
359 Constraint cons = new Constraint();
360 switch (ruleProvider) {
362 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
363 xacmlTemplatePath = templateFile.toPath();
364 cons.setActive_time_range(activeTimeRange);
365 if (blackList == null || blackList.isEmpty()) {
366 throw new BuilderException("blackList is required");
368 cons.setBlacklist(blackList);
371 templateFile = new File(classLoader.getResource(XACML_GUARD_MIN_MAX_TEMPLATE).getFile());
372 xacmlTemplatePath = templateFile.toPath();
373 cons = new Constraint(Integer.parseInt(yamlParams.get("min")),
374 Integer.parseInt(yamlParams.get("max")), activeTimeRange);
377 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
378 xacmlTemplatePath = templateFile.toPath();
379 Map<String, String> timeWindow = new HashMap<>();
380 if (!PolicyUtils.isInteger(yamlParams.get("timeWindow"))) {
381 throw new BuilderException("time window is not in Integer format.");
383 String timeUnits = yamlParams.get("timeUnits");
384 if (timeUnits == null
385 || !("minute".equalsIgnoreCase(timeUnits) || "hour".equalsIgnoreCase(timeUnits)
386 || "day".equalsIgnoreCase(timeUnits) || "week".equalsIgnoreCase(timeUnits)
387 || "month".equalsIgnoreCase(timeUnits) || "year".equalsIgnoreCase(timeUnits))) {
388 throw new BuilderException("time Units is not in proper format.");
390 timeWindow.put("value", yamlParams.get("timeWindow"));
391 timeWindow.put("units", yamlParams.get("timeUnits"));
392 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), timeWindow, activeTimeRange);
396 builder = builder.addLimitConstraint(policy1.getId(), cons);
397 // Build the specification
398 Results results = builder.buildSpecification();
400 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
401 String xacmlTemplateContent;
403 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
404 HashMap<String, String> yamlSpecs = new HashMap<>();
405 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
406 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
407 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
408 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
409 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
410 yamlSpecs.put("clname",
411 yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
412 if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
413 .getFreq_limit_per_target() != null) {
414 yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
415 .getFreq_limit_per_target().toString());
417 if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window() != null) {
418 yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
419 .getTime_window().get("value"));
420 yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
421 .getTime_window().get("units"));
424 if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().
425 getFirst().getMaxVnfCount() != null) {
426 yamlSpecs.put("max", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
427 .getMaxVnfCount().toString());
429 if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().
430 getFirst().getMinVnfCount() != null) {
431 yamlSpecs.put("min", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
432 .getMinVnfCount().toString());
435 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints()
436 .getFirst().getActive_time_range().get("start"));
437 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
438 .getActive_time_range().get("end"));
439 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs,
440 yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(),
441 yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
443 // Convert the Policy into Stream input to Policy Adapter.
444 Object policy = XACMLPolicyScanner
445 .readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
447 return (PolicyType) policy;
448 } catch (IOException e) {
449 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(),
452 } catch (BuilderException e) {
453 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(), e);
459 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
460 return (DecisionSettings) commonClassDao.getEntityItem(DecisionSettings.class, "xacmlId", settingId);
463 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
464 RuleType rule = new RuleType();
466 rule.setRuleId(policyAdapter.getRuleID());
469 rule.setEffect(EffectType.PERMIT);
471 rule.setEffect(EffectType.DENY);
473 rule.setTarget(new TargetType());
475 // Create Target in Rule
476 AllOfType allOfInRule = new AllOfType();
478 // Creating match for ACCESS in rule target
479 MatchType accessMatch = new MatchType();
480 AttributeValueType accessAttributeValue = new AttributeValueType();
481 accessAttributeValue.setDataType(STRING_DATATYPE);
482 accessAttributeValue.getContent().add("DECIDE");
483 accessMatch.setAttributeValue(accessAttributeValue);
484 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
485 URI accessURI = null;
487 accessURI = new URI(ACTION_ID);
488 } catch (URISyntaxException e) {
489 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
491 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
492 accessAttributeDesignator.setDataType(STRING_DATATYPE);
493 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
494 accessMatch.setAttributeDesignator(accessAttributeDesignator);
495 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
497 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
498 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
499 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
500 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
502 if (policyAdapter.getRuleProvider() != null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)) {
503 // Values for AAF Provider are here for XML Creation.
504 ConditionType condition = new ConditionType();
505 ApplyType decisionApply = new ApplyType();
507 AttributeValueType value1 = new AttributeValueType();
508 value1.setDataType(BOOLEAN_DATATYPE);
509 value1.getContent().add("true");
511 AttributeDesignatorType value2 = new AttributeDesignatorType();
512 value2.setAttributeId(AAFEngine.AAF_RESULT);
513 value2.setCategory(CATEGORY_RESOURCE);
514 value2.setDataType(BOOLEAN_DATATYPE);
515 value2.setMustBePresent(false);
517 ApplyType innerDecisionApply = new ApplyType();
518 innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
519 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
521 decisionApply.setFunctionId(XACML3.ID_FUNCTION_BOOLEAN_EQUAL.stringValue());
522 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
523 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
524 condition.setExpression(new ObjectFactory().createApply(decisionApply));
526 ApplyType notOuterApply = new ApplyType();
527 notOuterApply.setFunctionId(FUNCTION_NOT);
528 notOuterApply.getExpression().add(condition.getExpression());
529 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
531 rule.setCondition(condition);
532 allOfInRule.getMatch().add(accessMatch);
534 AnyOfType anyOfInRule = new AnyOfType();
535 anyOfInRule.getAllOf().add(allOfInRule);
537 TargetType targetInRule = new TargetType();
538 targetInRule.getAnyOf().add(anyOfInRule);
540 rule.setTarget(targetInRule);
542 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
543 AdviceExpressionType adviceExpression = new AdviceExpressionType();
544 adviceExpression.setAdviceId(AAFPROVIDER);
545 adviceExpression.setAppliesTo(EffectType.DENY);
546 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
547 assignment.setAttributeId("aaf.response");
548 assignment.setCategory(CATEGORY_RESOURCE);
549 AttributeDesignatorType value = new AttributeDesignatorType();
550 value.setAttributeId(AAFEngine.AAF_RESPONSE);
551 value.setCategory(CATEGORY_RESOURCE);
552 value.setDataType(STRING_DATATYPE);
553 value.setMustBePresent(false);
554 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
555 adviceExpression.getAttributeAssignmentExpression().add(assignment);
556 adviceExpressions.getAdviceExpression().add(adviceExpression);
557 rule.setAdviceExpressions(adviceExpressions);
559 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
560 policyAdapter.setPolicyData(decisionPolicy);
562 } else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
563 boolean isCompound = false;
564 ConditionType condition = new ConditionType();
565 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
567 for (String labelAttr : dynamicLabelRuleAlgorithms) {
568 // if the rule algorithm as a label means it is a compound
569 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
570 ApplyType decisionApply = new ApplyType();
572 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
573 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
574 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
575 decisionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
576 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
577 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
578 condition.setExpression(new ObjectFactory().createApply(decisionApply));
582 // if rule algorithm not a compound
584 condition.setExpression(new ObjectFactory()
585 .createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
589 ApplyType notOuterApply = new ApplyType();
590 notOuterApply.setFunctionId(FUNCTION_NOT);
591 notOuterApply.getExpression().add(condition.getExpression());
592 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
594 rule.setCondition(condition);
595 allOfInRule.getMatch().add(accessMatch);
597 AnyOfType anyOfInRule = new AnyOfType();
598 anyOfInRule.getAllOf().add(allOfInRule);
600 TargetType targetInRule = new TargetType();
601 targetInRule.getAnyOf().add(anyOfInRule);
603 rule.setTarget(targetInRule);
605 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
606 policyAdapter.setPolicyData(decisionPolicy);
609 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."
610 + policyAdapter.getData().getClass().getCanonicalName());
615 private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
616 RuleType rule = new RuleType();
618 rule.setRuleId(UUID.randomUUID().toString());
621 rule.setEffect(EffectType.PERMIT);
623 rule.setEffect(EffectType.DENY);
625 rule.setTarget(new TargetType());
627 // Create Target in Rule
628 AllOfType allOfInRule = new AllOfType();
630 // Creating match for DECIDE in rule target
631 MatchType accessMatch = new MatchType();
632 AttributeValueType accessAttributeValue = new AttributeValueType();
633 accessAttributeValue.setDataType(STRING_DATATYPE);
634 accessAttributeValue.getContent().add("DECIDE");
635 accessMatch.setAttributeValue(accessAttributeValue);
636 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
637 URI accessURI = null;
639 accessURI = new URI(ACTION_ID);
640 } catch (URISyntaxException e) {
641 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
643 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
644 accessAttributeDesignator.setDataType(STRING_DATATYPE);
645 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
646 accessMatch.setAttributeDesignator(accessAttributeDesignator);
647 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
649 allOfInRule.getMatch().add(accessMatch);
651 // Creating match for ErrorCode in rule target
652 MatchType errorcodeMatch = new MatchType();
653 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
654 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
655 errorcodeAttributeValue.getContent().add(errorcode);
656 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
657 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
658 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
659 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
660 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
661 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
662 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
664 allOfInRule.getMatch().add(errorcodeMatch);
666 AnyOfType anyOfInRule = new AnyOfType();
667 anyOfInRule.getAllOf().add(allOfInRule);
669 TargetType targetInRule = new TargetType();
670 targetInRule.getAnyOf().add(anyOfInRule);
672 rule.setTarget(targetInRule);
674 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
675 AdviceExpressionType adviceExpression = new AdviceExpressionType();
676 adviceExpression.setAdviceId(RAINY_DAY);
677 adviceExpression.setAppliesTo(EffectType.PERMIT);
679 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
680 assignment.setAttributeId("treatment");
681 assignment.setCategory(CATEGORY_RESOURCE);
683 AttributeValueType treatmentAttributeValue = new AttributeValueType();
684 treatmentAttributeValue.setDataType(STRING_DATATYPE);
685 treatmentAttributeValue.getContent().add(treatment);
686 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
688 adviceExpression.getAttributeAssignmentExpression().add(assignment);
689 adviceExpressions.getAdviceExpression().add(adviceExpression);
690 rule.setAdviceExpressions(adviceExpressions);
691 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
692 policyAdapter.setPolicyData(decisionPolicy);
696 // if compound setting the inner apply here
697 protected ApplyType getInnerDecisionApply(String value1Label) {
698 ApplyType decisionApply = new ApplyType();
700 // check the index for the label.
701 for (String labelAttr : dynamicLabelRuleAlgorithms) {
702 if (labelAttr.equals(value1Label)) {
703 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
704 populateDataTypeList(value1);
706 // check if the row contains label again
707 for (String labelValue : dynamicLabelRuleAlgorithms) {
708 if (labelValue.equals(value1)) {
709 return getCompoundDecisionApply(index);
713 // Getting the values from the form.
714 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
715 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
716 decisionApply.setFunctionId(getFunctionDefinitionId(functionKey));
717 // if two text field are rule attributes.
718 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
719 ApplyType innerDecisionApply1 = new ApplyType();
720 ApplyType innerDecisionApply2 = new ApplyType();
721 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
722 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
723 // If selected function is Integer function set integer functionID
724 if (functionKey.toLowerCase().contains("integer")) {
725 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
726 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
727 attributeDesignator1.setDataType(INTEGER_DATATYPE);
728 attributeDesignator2.setDataType(INTEGER_DATATYPE);
730 // If selected function is not a Integer function set String functionID
731 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
732 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
733 attributeDesignator1.setDataType(STRING_DATATYPE);
734 attributeDesignator2.setDataType(STRING_DATATYPE);
736 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
737 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
738 // Here set actual field values
740 .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
742 .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
743 innerDecisionApply1.getExpression()
744 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator1));
745 innerDecisionApply2.getExpression()
746 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator2));
747 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
748 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));
750 // if either of one text field is rule attribute.
751 if (!value1.startsWith("S_")) {
752 ApplyType innerDecisionApply = new ApplyType();
753 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
754 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
756 if (functionKey.toLowerCase().contains("integer")) {
757 innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
758 decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
759 attributeDesignator.setDataType(INTEGER_DATATYPE);
761 innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
762 decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
763 attributeDesignator.setDataType(STRING_DATATYPE);
766 String attributeId = null;
767 String attributeValue = null;
769 // Find which textField has rule attribute and set it as
770 // attributeId and the other as attributeValue.
771 attributeId = value1;
772 attributeValue = value2;
774 if (attributeId != null) {
775 attributeDesignator.setCategory(CATEGORY_RESOURCE);
776 attributeDesignator.setAttributeId(attributeId);
778 decisionConditionAttributeValue.getContent().add(attributeValue);
779 innerDecisionApply.getExpression()
780 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
781 decisionApply.getExpression()
782 .add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
783 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
785 value1 = value1.substring(2, value1.length());
786 VariableReferenceType variableReferenceType = new VariableReferenceType();
787 variableReferenceType.setVariableId(value1);
789 String dataType = dataTypeList.get(index);
791 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
792 decisionConditionAttributeValue.setDataType(dataType);
793 decisionConditionAttributeValue.getContent().add(value2);
794 decisionApply.getExpression()
795 .add(new ObjectFactory().createVariableReference(variableReferenceType));
796 decisionApply.getExpression()
797 .add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
803 return decisionApply;
806 // if the rule algorithm is multiple compound one setting the apply
807 protected ApplyType getCompoundDecisionApply(int index) {
808 ApplyType decisionApply = new ApplyType();
809 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
810 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
811 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
812 decisionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
813 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
814 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
815 return decisionApply;
818 private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
819 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
820 AttributeValueType dynamicAttributeValue = new AttributeValueType();
822 dynamicAttributeValue.setDataType(dataType);
823 dynamicAttributeValue.getContent().add(value);
825 dynamicVariable.setVariableId(key);
826 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
828 return dynamicVariable;
832 private void populateDataTypeList(String value1) {
833 String dataType = null;
834 if (value1.contains("S_")) {
835 value1 = value1.substring(2, value1.length());
836 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
837 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
838 dataType = STRING_DATATYPE;
839 } else if (decisionSettings != null
840 && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
841 dataType = BOOLEAN_DATATYPE;
843 dataType = INTEGER_DATATYPE;
849 dataTypeList.add(dataType);
853 private String getDataType(String key) {
855 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
856 String dataType = null;
858 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
859 dataType = STRING_DATATYPE;
860 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
861 dataType = BOOLEAN_DATATYPE;
863 dataType = INTEGER_DATATYPE;
870 public Object getCorrectPolicyDataObject() {
871 return policyAdapter.getData();
874 public String getFunctionDefinitionId(String key) {
875 FunctionDefinition object =
876 (FunctionDefinition) commonClassDao.getEntityItem(FunctionDefinition.class, "shortname", key);
877 if (object != null) {
878 return object.getXacmlid();