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;
30 import java.net.URISyntaxException;
31 import java.nio.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.HashMap;
38 import java.util.LinkedList;
39 import java.util.List;
41 import java.util.UUID;
43 import org.apache.commons.lang3.StringEscapeUtils;
44 import org.onap.policy.common.logging.eelf.MessageCodes;
45 import org.onap.policy.common.logging.eelf.PolicyLogger;
46 import org.onap.policy.common.logging.flexlogger.FlexLogger;
47 import org.onap.policy.common.logging.flexlogger.Logger;
48 import org.onap.policy.controlloop.policy.builder.BuilderException;
49 import org.onap.policy.controlloop.policy.builder.Results;
50 import org.onap.policy.controlloop.policy.guard.Constraint;
51 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
52 import org.onap.policy.controlloop.policy.guard.Guard;
53 import org.onap.policy.controlloop.policy.guard.GuardPolicy;
54 import org.onap.policy.controlloop.policy.guard.MatchParameters;
55 import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder;
56 import org.onap.policy.rest.adapter.PolicyRestAdapter;
57 import org.onap.policy.rest.dao.CommonClassDao;
58 import org.onap.policy.rest.jpa.DecisionSettings;
59 import org.onap.policy.rest.jpa.FunctionDefinition;
60 import org.onap.policy.utils.PolicyUtils;
61 import org.onap.policy.xacml.api.XACMLErrorConstants;
62 import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
63 import org.onap.policy.xacml.util.XACMLPolicyScanner;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.stereotype.Component;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
83 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 GUARD_MIN_MAX = "GUARD_MIN_MAX";
96 public static final String RAINY_DAY = "Rainy_Day";
97 public static final String MS_MODEL = "MicroService_Model";
98 private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml";
99 private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml";
100 private static final String XACML_GUARD_MIN_MAX_TEMPLATE = "Decision_GuardMinMaxPolicyTemplate.xml";
102 private static final String ONAPNAME = "ONAPName";
103 private static final String POLICY_NAME = "PolicyName";
104 private static final String DESCRIPTION = "description";
107 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
108 List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
109 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
110 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
111 List<String> dataTypeList = new LinkedList<>();
113 private static CommonClassDao commonClassDao;
115 public DecisionPolicy() {
120 public DecisionPolicy(CommonClassDao commonClassDao) {
121 DecisionPolicy.commonClassDao = commonClassDao;
124 public DecisionPolicy(PolicyRestAdapter policyAdapter) {
125 this.policyAdapter = policyAdapter;
126 this.commonClassDao = commonClassDao;
130 public Map<String, String> savePolicies() throws PAPException {
132 Map<String, String> successMap = new HashMap<>();
133 if (isPolicyExists()) {
134 successMap.put("EXISTS", "This Policy already exist on the PAP");
138 if (!isPreparedToSave()) {
139 // Prep and configure the policy for saving
143 // Until here we prepared the data and here calling the method to create xml.
144 Path newPolicyPath = null;
145 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
147 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
152 * Scan the Raw Policy data and set to PolicyAdapter.
154 private void readRawPolicyData() {
156 if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) {
157 policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils
158 .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
160 policy = XACMLPolicyScanner.readPolicy(
161 new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8)));
163 String policyRawDesc;
164 if (policy instanceof PolicySetType) {
166 ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
167 ((PolicySetType) policy).setDescription(policyRawDesc);
169 policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
170 ((PolicyType) policy).setDescription(policyRawDesc);
172 policyAdapter.setPolicyData(policy);
173 policyAdapter.setData(policy);
174 setPreparedToSave(true);
178 // This is the method for preparing the policy for saving. We have broken it out
179 // separately because the fully configured policy is used for multiple things
181 public boolean prepareToSave() throws PAPException {
183 if (isPreparedToSave()) {
184 // we have already done this
189 String policyID = policyAdapter.getPolicyID();
190 version = policyAdapter.getHighestVersion();
192 if ("Raw".equals(policyAdapter.getRuleProvider())) {
196 // Create the Instance for pojo, PolicyType object is used in marshalling.
197 if ("Decision".equals(policyAdapter.getPolicyType())) {
198 PolicyType policyConfig = new PolicyType();
200 policyConfig.setVersion(Integer.toString(version));
201 policyConfig.setPolicyId(policyID);
202 policyConfig.setTarget(new TargetType());
203 policyAdapter.setData(policyConfig);
205 policyName = policyAdapter.getNewFileName();
207 if(policyAdapter.getRuleProvider().equals(GUARD_YAML) ||
208 policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) ||
209 policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){
211 Map<String, String> yamlParams = new HashMap<>();
212 String blackListEntryType = policyAdapter.getBlackListEntryType() != null
213 ? policyAdapter.getBlackListEntryType() : "Use Manual Entry";
214 String description = policyAdapter.getPolicyDescription() != null ? policyAdapter.getPolicyDescription()
215 : "YAML Guard Policy";
216 yamlParams.put(DESCRIPTION, description + "@blEntry@" + blackListEntryType + "@blEntry@");
217 String fileName = policyAdapter.getNewFileName();
218 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
219 if ((name == null) || ("".equals(name))) {
220 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
222 yamlParams.put(POLICY_NAME, name);
223 yamlParams.put(ONAPNAME, policyAdapter.getOnapName());
224 Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes();
225 yamlParams.putAll(params);
226 // Call YAML to XACML
228 PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider());
229 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
230 decisionPolicy.setVersion(Integer.toString(version));
231 policyAdapter.setPolicyData(decisionPolicy);
232 policyAdapter.setData(decisionPolicy);
233 } catch (BuilderException e) {
235 throw new PAPException(e);
237 } else if (policyAdapter.getData() != null) {
238 PolicyType decisionPolicy = (PolicyType) policyAdapter.getData();
240 decisionPolicy.setDescription(policyAdapter.getPolicyDescription());
242 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
243 AllOfType allOfOne = new AllOfType();
244 String fileName = policyAdapter.getNewFileName();
245 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
246 if ((name == null) || ("".equals(name))) {
247 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
249 allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
251 AllOfType allOf = new AllOfType();
254 allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName())));
256 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
257 if (policyAdapter.getRuleProvider() != null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)) {
258 dynamicFieldComponentAttributes = new HashMap<>();
261 // If there is any dynamic field attributes create the matches here
262 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
263 String key = keyField;
264 String value = dynamicFieldComponentAttributes.get(key);
265 MatchType dynamicMatch = createDynamicMatch(key, value);
266 allOf.getMatch().add(dynamicMatch);
269 AnyOfType anyOf = new AnyOfType();
270 anyOf.getAllOf().add(allOfOne);
271 anyOf.getAllOf().add(allOf);
273 TargetType target = new TargetType();
274 target.getAnyOf().add(anyOf);
275 decisionPolicy.setTarget(target);
277 Map<String, String> dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap();
278 if (policyAdapter.getRuleProvider() != null && (policyAdapter.getRuleProvider().equals(AAFPROVIDER)
279 || policyAdapter.getRuleProvider().equals(RAINY_DAY))) {
280 dynamicFieldDecisionSettings = new HashMap<>();
283 // settings are dynamic so check how many rows are added and add all
284 for (String keyField : dynamicFieldDecisionSettings.keySet()) {
285 String key = keyField;
286 String value = dynamicFieldDecisionSettings.get(key);
287 String dataType = getDataType(key);
288 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
289 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
292 Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
293 if (policyAdapter.getRuleProvider().equals(RAINY_DAY)) {
294 for (String keyField : dynamicFieldTreatmentAttributes.keySet()) {
295 String errorcode = keyField;
296 String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
297 createRainydayRule(decisionPolicy, errorcode, treatment, true);
300 createRule(decisionPolicy, true);
301 createRule(decisionPolicy, false);
305 setPreparedToSave(true);
309 public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException {
311 ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
312 MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
313 matchParameters.setControlLoopName(yamlParams.get("clname"));
314 if (yamlParams.containsKey("targets")) {
315 String targetString = yamlParams.get("targets");
316 List<String> targets = null;
317 if (targetString != null && !targetString.isEmpty()) {
318 if (targetString.contains(",")) {
319 targets = Arrays.asList(targetString.split(","));
321 targets = new ArrayList<>();
322 targets.add(targetString);
325 matchParameters.setTargets(targets);
327 GuardPolicy policy1 = new GuardPolicy(
328 (policyAdapter.getUuid() != null ? policyAdapter.getUuid() : UUID.randomUUID().toString()),
329 yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
330 builder = builder.addGuardPolicy(policy1);
331 Map<String, String> activeTimeRange = new HashMap<>();
332 activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
333 activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
334 String blackListString = yamlParams.get("blackList");
335 List<String> blackList = null;
336 if (blackListString != null && !blackListString.trim().isEmpty()) {
337 if (blackListString.contains(",")) {
338 blackList = Arrays.asList(blackListString.split(","));
340 blackList = new ArrayList<>();
341 blackList.add(blackListString);
344 if (yamlParams.containsKey("appendBlackList")) {
345 String appendBlackListString = yamlParams.get("appendBlackList");
346 List<String> appendBlackList = null;
347 if (appendBlackListString != null && !appendBlackListString.trim().isEmpty()) {
348 appendBlackList = Arrays.asList(appendBlackListString.split(","));
349 for (int i = 0; i < appendBlackList.size(); i++) {
350 blackList.remove(appendBlackList.get(i));
355 Path xacmlTemplatePath;
356 ClassLoader classLoader = getClass().getClassLoader();
357 Constraint cons = new Constraint();
358 switch (ruleProvider) {
360 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
361 xacmlTemplatePath = templateFile.toPath();
362 cons.setActive_time_range(activeTimeRange);
363 if (blackList == null || blackList.isEmpty()) {
364 throw new BuilderException("blackList is required");
366 cons.setBlacklist(blackList);
369 templateFile = new File(classLoader.getResource(XACML_GUARD_MIN_MAX_TEMPLATE).getFile());
370 xacmlTemplatePath = templateFile.toPath();
371 cons = new Constraint(Integer.parseInt(yamlParams.get("min")),
372 Integer.parseInt(yamlParams.get("max")), activeTimeRange);
375 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
376 xacmlTemplatePath = templateFile.toPath();
377 Map<String, String> timeWindow = new HashMap<>();
378 if (!PolicyUtils.isInteger(yamlParams.get("timeWindow"))) {
379 throw new BuilderException("time window is not in Integer format.");
381 String timeUnits = yamlParams.get("timeUnits");
382 if (timeUnits == null
383 || !("minute".equalsIgnoreCase(timeUnits) || "hour".equalsIgnoreCase(timeUnits)
384 || "day".equalsIgnoreCase(timeUnits) || "week".equalsIgnoreCase(timeUnits)
385 || "month".equalsIgnoreCase(timeUnits) || "year".equalsIgnoreCase(timeUnits))) {
386 throw new BuilderException("time Units is not in proper format.");
388 timeWindow.put("value", yamlParams.get("timeWindow"));
389 timeWindow.put("units", yamlParams.get("timeUnits"));
390 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), timeWindow, activeTimeRange);
394 builder = builder.addLimitConstraint(policy1.getId(), cons);
395 // Build the specification
396 Results results = builder.buildSpecification();
398 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
399 String xacmlTemplateContent;
401 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
402 HashMap<String, String> yamlSpecs = new HashMap<>();
403 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
404 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
405 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
406 GuardPolicy guard = yamlGuardObject.getGuards().get(0);
408 yamlSpecs.put("actor", guard.getMatch_parameters().getActor());
409 yamlSpecs.put("recipe", guard.getMatch_parameters().getRecipe());
410 yamlSpecs.put("clname", guard.getMatch_parameters().getControlLoopName());
412 Constraint constraints = guard.getLimit_constraints().get(0);
413 if (constraints.getFreq_limit_per_target() != null) {
414 yamlSpecs.put("limit", constraints.getFreq_limit_per_target().toString());
416 if (constraints.getTime_window() != null) {
417 yamlSpecs.put("twValue", constraints.getTime_window().get("value"));
418 yamlSpecs.put("twUnits", constraints.getTime_window().get("units"));
421 if (constraints.getMaxVnfCount() != null) {
422 yamlSpecs.put("max", constraints.getMaxVnfCount().toString());
424 if (constraints.getMinVnfCount() != null) {
425 yamlSpecs.put("min", constraints.getMinVnfCount().toString());
428 yamlSpecs.put("guardActiveStart", constraints.getActive_time_range().get("start"));
429 yamlSpecs.put("guardActiveEnd", constraints.getActive_time_range().get("end"));
430 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs,
431 constraints.getBlacklist(),
432 guard.getMatch_parameters().getTargets());
434 // Convert the Policy into Stream input to Policy Adapter.
435 Object policy = XACMLPolicyScanner
436 .readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
438 return (PolicyType) policy;
439 } catch (IOException e) {
440 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(),
443 } catch (BuilderException e) {
444 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(), e);
450 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
451 return (DecisionSettings) commonClassDao.getEntityItem(DecisionSettings.class, "xacml_id", settingId);
454 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
455 RuleType rule = new RuleType();
457 rule.setRuleId(policyAdapter.getRuleID());
460 rule.setEffect(EffectType.PERMIT);
462 rule.setEffect(EffectType.DENY);
464 rule.setTarget(new TargetType());
466 // Create Target in Rule
467 AllOfType allOfInRule = new AllOfType();
469 // Creating match for ACCESS in rule target
470 MatchType accessMatch = new MatchType();
471 AttributeValueType accessAttributeValue = new AttributeValueType();
472 accessAttributeValue.setDataType(STRING_DATATYPE);
473 accessAttributeValue.getContent().add("DECIDE");
474 accessMatch.setAttributeValue(accessAttributeValue);
475 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
476 URI accessURI = null;
478 accessURI = new URI(ACTION_ID);
479 } catch (URISyntaxException e) {
480 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
482 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
483 accessAttributeDesignator.setDataType(STRING_DATATYPE);
484 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
485 accessMatch.setAttributeDesignator(accessAttributeDesignator);
486 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
488 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
489 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
490 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
491 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
493 if (policyAdapter.getRuleProvider() != null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)) {
494 // Values for AAF Provider are here for XML Creation.
495 ConditionType condition = new ConditionType();
496 ApplyType decisionApply = new ApplyType();
498 AttributeValueType value1 = new AttributeValueType();
499 value1.setDataType(BOOLEAN_DATATYPE);
500 value1.getContent().add("true");
502 AttributeDesignatorType value2 = new AttributeDesignatorType();
503 value2.setAttributeId(AAFEngine.AAF_RESULT);
504 value2.setCategory(CATEGORY_RESOURCE);
505 value2.setDataType(BOOLEAN_DATATYPE);
506 value2.setMustBePresent(false);
508 ApplyType innerDecisionApply = new ApplyType();
509 innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
510 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
512 decisionApply.setFunctionId(XACML3.ID_FUNCTION_BOOLEAN_EQUAL.stringValue());
513 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
514 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
515 condition.setExpression(new ObjectFactory().createApply(decisionApply));
517 ApplyType notOuterApply = new ApplyType();
518 notOuterApply.setFunctionId(FUNCTION_NOT);
519 notOuterApply.getExpression().add(condition.getExpression());
520 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
522 rule.setCondition(condition);
523 allOfInRule.getMatch().add(accessMatch);
525 AnyOfType anyOfInRule = new AnyOfType();
526 anyOfInRule.getAllOf().add(allOfInRule);
528 TargetType targetInRule = new TargetType();
529 targetInRule.getAnyOf().add(anyOfInRule);
531 rule.setTarget(targetInRule);
533 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
534 AdviceExpressionType adviceExpression = new AdviceExpressionType();
535 adviceExpression.setAdviceId(AAFPROVIDER);
536 adviceExpression.setAppliesTo(EffectType.DENY);
537 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
538 assignment.setAttributeId("aaf.response");
539 assignment.setCategory(CATEGORY_RESOURCE);
540 AttributeDesignatorType value = new AttributeDesignatorType();
541 value.setAttributeId(AAFEngine.AAF_RESPONSE);
542 value.setCategory(CATEGORY_RESOURCE);
543 value.setDataType(STRING_DATATYPE);
544 value.setMustBePresent(false);
545 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
546 adviceExpression.getAttributeAssignmentExpression().add(assignment);
547 adviceExpressions.getAdviceExpression().add(adviceExpression);
548 rule.setAdviceExpressions(adviceExpressions);
550 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
551 policyAdapter.setPolicyData(decisionPolicy);
553 } else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
554 boolean isCompound = false;
555 ConditionType condition = new ConditionType();
556 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
558 for (String labelAttr : dynamicLabelRuleAlgorithms) {
559 // if the rule algorithm as a label means it is a compound
560 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
561 ApplyType decisionApply = new ApplyType();
563 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
564 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
565 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
566 decisionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
567 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
568 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
569 condition.setExpression(new ObjectFactory().createApply(decisionApply));
573 // if rule algorithm not a compound
575 condition.setExpression(new ObjectFactory()
576 .createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
580 ApplyType notOuterApply = new ApplyType();
581 notOuterApply.setFunctionId(FUNCTION_NOT);
582 notOuterApply.getExpression().add(condition.getExpression());
583 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
585 rule.setCondition(condition);
586 allOfInRule.getMatch().add(accessMatch);
588 AnyOfType anyOfInRule = new AnyOfType();
589 anyOfInRule.getAllOf().add(allOfInRule);
591 TargetType targetInRule = new TargetType();
592 targetInRule.getAnyOf().add(anyOfInRule);
594 rule.setTarget(targetInRule);
596 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
597 policyAdapter.setPolicyData(decisionPolicy);
600 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."
601 + policyAdapter.getData().getClass().getCanonicalName());
606 private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
607 RuleType rule = new RuleType();
609 rule.setRuleId(UUID.randomUUID().toString());
612 rule.setEffect(EffectType.PERMIT);
614 rule.setEffect(EffectType.DENY);
616 rule.setTarget(new TargetType());
618 // Create Target in Rule
619 AllOfType allOfInRule = new AllOfType();
621 // Creating match for DECIDE in rule target
622 MatchType accessMatch = new MatchType();
623 AttributeValueType accessAttributeValue = new AttributeValueType();
624 accessAttributeValue.setDataType(STRING_DATATYPE);
625 accessAttributeValue.getContent().add("DECIDE");
626 accessMatch.setAttributeValue(accessAttributeValue);
627 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
628 URI accessURI = null;
630 accessURI = new URI(ACTION_ID);
631 } catch (URISyntaxException e) {
632 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
634 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
635 accessAttributeDesignator.setDataType(STRING_DATATYPE);
636 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
637 accessMatch.setAttributeDesignator(accessAttributeDesignator);
638 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
640 allOfInRule.getMatch().add(accessMatch);
642 // Creating match for ErrorCode in rule target
643 MatchType errorcodeMatch = new MatchType();
644 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
645 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
646 errorcodeAttributeValue.getContent().add(errorcode);
647 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
648 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
649 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
650 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
651 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
652 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
653 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
655 allOfInRule.getMatch().add(errorcodeMatch);
657 AnyOfType anyOfInRule = new AnyOfType();
658 anyOfInRule.getAllOf().add(allOfInRule);
660 TargetType targetInRule = new TargetType();
661 targetInRule.getAnyOf().add(anyOfInRule);
663 rule.setTarget(targetInRule);
665 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
666 AdviceExpressionType adviceExpression = new AdviceExpressionType();
667 adviceExpression.setAdviceId(RAINY_DAY);
668 adviceExpression.setAppliesTo(EffectType.PERMIT);
670 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
671 assignment.setAttributeId("treatment");
672 assignment.setCategory(CATEGORY_RESOURCE);
674 AttributeValueType treatmentAttributeValue = new AttributeValueType();
675 treatmentAttributeValue.setDataType(STRING_DATATYPE);
676 treatmentAttributeValue.getContent().add(treatment);
677 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
679 adviceExpression.getAttributeAssignmentExpression().add(assignment);
680 adviceExpressions.getAdviceExpression().add(adviceExpression);
681 rule.setAdviceExpressions(adviceExpressions);
682 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
683 policyAdapter.setPolicyData(decisionPolicy);
687 // if compound setting the inner apply here
688 protected ApplyType getInnerDecisionApply(String value1Label) {
689 ApplyType decisionApply = new ApplyType();
691 // check the index for the label.
692 for (String labelAttr : dynamicLabelRuleAlgorithms) {
693 if (labelAttr.equals(value1Label)) {
694 String attributeId = dynamicFieldOneRuleAlgorithms.get(index);
695 populateDataTypeList(attributeId);
697 // check if the row contains label again
698 for (String labelValue : dynamicLabelRuleAlgorithms) {
699 if (labelValue.equals(attributeId)) {
700 return getCompoundDecisionApply(index);
704 // Getting the values from the form.
705 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
706 String attributeValue = dynamicFieldTwoRuleAlgorithms.get(index);
707 decisionApply.setFunctionId(getFunctionDefinitionId(functionKey));
708 // if two text field are rule attributes.
709 if ((attributeId.contains(RULE_VARIABLE)) && (attributeValue.contains(RULE_VARIABLE))) {
710 applyTwoTextFieldRuleAttribute(decisionApply, attributeId, functionKey);
712 // if either of one text field is rule attribute.
713 if (!attributeId.startsWith("S_")) {
714 ApplyType innerDecisionApply = generateApplyTypeDataType(functionKey);
715 AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey);
716 AttributeValueType decisionConditionAttributeValue = generateAttributeValueTypeDataType(functionKey);
718 if (attributeId != null) {
719 attributeDesignator.setCategory(CATEGORY_RESOURCE);
720 attributeDesignator.setAttributeId(attributeId);
722 decisionConditionAttributeValue.getContent().add(attributeValue);
723 innerDecisionApply.getExpression()
724 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
725 decisionApply.getExpression()
726 .add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
727 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
729 attributeId = attributeId.substring(2, attributeId.length());
730 VariableReferenceType variableReferenceType = new VariableReferenceType();
731 variableReferenceType.setVariableId(attributeId);
733 String dataType = dataTypeList.get(index);
735 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
736 decisionConditionAttributeValue.setDataType(dataType);
737 decisionConditionAttributeValue.getContent().add(attributeValue);
738 decisionApply.getExpression()
739 .add(new ObjectFactory().createVariableReference(variableReferenceType));
740 decisionApply.getExpression()
741 .add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
747 return decisionApply;
750 // if the rule algorithm is multiple compound one setting the apply
751 protected ApplyType getCompoundDecisionApply(int index) {
752 ApplyType decisionApply = new ApplyType();
753 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
754 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
755 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
756 decisionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
757 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
758 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
759 return decisionApply;
762 private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
763 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
764 AttributeValueType dynamicAttributeValue = new AttributeValueType();
766 dynamicAttributeValue.setDataType(dataType);
767 dynamicAttributeValue.getContent().add(value);
769 dynamicVariable.setVariableId(key);
770 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
772 return dynamicVariable;
776 private void populateDataTypeList(String value1) {
777 String dataType = null;
778 if (value1.contains("S_")) {
779 value1 = value1.substring(2, value1.length());
780 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
781 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
782 dataType = STRING_DATATYPE;
783 } else if (decisionSettings != null
784 && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
785 dataType = BOOLEAN_DATATYPE;
787 dataType = INTEGER_DATATYPE;
793 dataTypeList.add(dataType);
797 private String getDataType(String key) {
799 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
800 String dataType = null;
802 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
803 dataType = STRING_DATATYPE;
804 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
805 dataType = BOOLEAN_DATATYPE;
807 dataType = INTEGER_DATATYPE;
814 public Object getCorrectPolicyDataObject() {
815 return policyAdapter.getData();
818 public String getFunctionDefinitionId(String key) {
819 FunctionDefinition object =
820 (FunctionDefinition) commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", key);
821 if (object != null) {
822 return object.getXacmlid();
827 private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) {
828 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
829 switch(functionKey.toLowerCase())
832 attributeDesignator.setDataType(INTEGER_DATATYPE);
835 attributeDesignator.setDataType(STRING_DATATYPE);
837 return attributeDesignator;
840 private ApplyType generateApplyTypeDataType(String functionKey) {
841 ApplyType applyType = new ApplyType();
842 switch(functionKey.toLowerCase())
845 applyType.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
848 applyType.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
853 private AttributeValueType generateAttributeValueTypeDataType(String functionKey) {
854 AttributeValueType applyType = new AttributeValueType();
855 switch(functionKey.toLowerCase())
858 applyType.setDataType(INTEGER_DATATYPE);
861 applyType.setDataType(STRING_DATATYPE);
866 private void applyTwoTextFieldRuleAttribute(ApplyType decisionApply, String value1, String functionKey) {
867 decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
868 decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
871 private ApplyType generateApplyTypeDataType(String value1, String functionKey) {
872 ApplyType innerApply = generateApplyTypeDataType(functionKey);
873 AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey);
875 attributeDesignator.setCategory(CATEGORY_RESOURCE);
876 // Here set actual field values
878 .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
879 innerApply.getExpression()
880 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));