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.openecomp.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.openecomp.policy.common.logging.eelf.MessageCodes;
44 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
45 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
46 import org.openecomp.policy.common.logging.flexlogger.Logger;
47 import org.openecomp.policy.controlloop.policy.builder.BuilderException;
48 import org.openecomp.policy.controlloop.policy.builder.Results;
49 import org.openecomp.policy.controlloop.policy.guard.Constraint;
50 import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard;
51 import org.openecomp.policy.controlloop.policy.guard.Guard;
52 import org.openecomp.policy.controlloop.policy.guard.GuardPolicy;
53 import org.openecomp.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder;
54 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
55 import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
56 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
57 import org.openecomp.policy.rest.jpa.Datatype;
58 import org.openecomp.policy.rest.jpa.DecisionSettings;
59 import org.openecomp.policy.rest.jpa.FunctionDefinition;
60 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
61 import org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine;
62 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
64 import com.att.research.xacml.std.IdentifierImpl;
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.PolicyType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
84 public class DecisionPolicy extends Policy {
86 private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class);
88 public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
89 private static final String AAFProvider = "AAF";
90 public static final String GUARD_YAML = "GUARD_YAML";
91 public static final String GUARD_BL_YAML = "GUARD_BL_YAML";
92 public static final String RAINY_DAY = "Rainy_Day";
93 private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml";
94 private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml";
96 private static final String ECOMPNAME = "ECOMPName";
97 private static final String POLICY_NAME = "PolicyName";
98 private static final String DESCRIPTION = "description";
101 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
102 List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
103 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
104 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
105 List<String> dataTypeList = new LinkedList<>();
107 protected Map<String, String> dropDownMap = new HashMap<>();
110 public DecisionPolicy() {
114 public DecisionPolicy(PolicyRestAdapter policyAdapter){
115 this.policyAdapter = policyAdapter;
119 public Map<String, String> savePolicies() throws Exception {
121 Map<String, String> successMap = new HashMap<>();
122 if(isPolicyExists()){
123 successMap.put("EXISTS", "This Policy already exist on the PAP");
127 if(!isPreparedToSave()){
128 //Prep and configure the policy for saving
132 // Until here we prepared the data and here calling the method to create xml.
133 Path newPolicyPath = null;
134 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
136 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
140 //This is the method for preparing the policy for saving. We have broken it out
141 //separately because the fully configured policy is used for multiple things
143 public boolean prepareToSave() throws Exception{
145 if(isPreparedToSave()){
146 //we have already done this
151 String policyID = policyAdapter.getPolicyID();
152 version = policyAdapter.getHighestVersion();
154 // Create the Instance for pojo, PolicyType object is used in marshalling.
155 if ("Decision".equals(policyAdapter.getPolicyType())) {
156 PolicyType policyConfig = new PolicyType();
158 policyConfig.setVersion(Integer.toString(version));
159 policyConfig.setPolicyId(policyID);
160 policyConfig.setTarget(new TargetType());
161 policyAdapter.setData(policyConfig);
163 policyName = policyAdapter.getNewFileName();
165 if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){
166 Map<String, String> yamlParams = new HashMap<>();
167 yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy");
168 String fileName = policyAdapter.getNewFileName();
169 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
170 if ((name == null) || ("".equals(name))) {
171 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
173 yamlParams.put(POLICY_NAME, name);
174 yamlParams.put(ECOMPNAME, policyAdapter.getEcompName());
175 Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes();
176 yamlParams.putAll(params);
177 // Call YAML to XACML
178 PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider());
179 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
180 decisionPolicy.setVersion(Integer.toString(version));
181 policyAdapter.setPolicyData(decisionPolicy);
182 policyAdapter.setData(decisionPolicy);
183 }else if (policyAdapter.getData() != null) {
184 PolicyType decisionPolicy = (PolicyType) policyAdapter.getData();
186 decisionPolicy.setDescription(policyAdapter.getPolicyDescription());
188 decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
189 AllOfType allOfOne = new AllOfType();
190 String fileName = policyAdapter.getNewFileName();
191 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
192 if ((name == null) || ("".equals(name))) {
193 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
195 allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
197 AllOfType allOf = new AllOfType();
200 allOf.getMatch().add(createMatch(ECOMPNAME, (policyAdapter.getEcompName())));
202 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
203 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFProvider)){
204 dynamicFieldComponentAttributes = new HashMap<>();
207 // If there is any dynamic field attributes create the matches here
208 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
209 String key = keyField;
210 String value = dynamicFieldComponentAttributes.get(key);
211 MatchType dynamicMatch = createDynamicMatch(key, value);
212 allOf.getMatch().add(dynamicMatch);
215 AnyOfType anyOf = new AnyOfType();
216 anyOf.getAllOf().add(allOfOne);
217 anyOf.getAllOf().add(allOf);
219 TargetType target = new TargetType();
220 target.getAnyOf().add(anyOf);
221 decisionPolicy.setTarget(target);
223 Map<String, String> dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap();
225 //dynamicVariableList = policyAdapter.getDynamicVariableList();
226 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFProvider)){
227 dynamicFieldDecisionSettings = new HashMap<>();
230 // settings are dynamic so check how many rows are added and add all
231 for (String keyField : dynamicFieldDecisionSettings.keySet()) {
232 String key = keyField;
233 String value = dynamicFieldDecisionSettings.get(key);
234 //String dataType = (String) dynamicVariableList.get(counter);
235 String dataType = getDataType(key);
236 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
237 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
241 Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
243 if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){
244 for(String keyField : dynamicFieldTreatmentAttributes.keySet()) {
245 String errorcode = keyField;
246 String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
247 createRainydayRule(decisionPolicy, errorcode, treatment, true);
250 createRule(decisionPolicy, true);
251 createRule(decisionPolicy, false);
256 setPreparedToSave(true);
260 public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) {
262 ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
263 GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), yamlParams.get("actor"), yamlParams.get("recipe"));
264 builder = builder.addGuardPolicy(policy1);
265 Map<String, String> time_in_range = new HashMap<>();
266 time_in_range.put("arg2", yamlParams.get("guardActiveStart"));
267 time_in_range.put("arg3", yamlParams.get("guardActiveEnd"));
268 String blackListString = yamlParams.get("blackList");
269 List<String> blackList = null;
270 if(blackListString!=null){
271 if (blackListString.contains(",")){
272 blackList = Arrays.asList(blackListString.split(","));
275 blackList = new ArrayList<>();
276 blackList.add(blackListString);
280 Path xacmlTemplatePath;
282 ClassLoader classLoader = getClass().getClassLoader();
283 switch (ruleProvider){
285 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
286 xacmlTemplatePath = templateFile.toPath();
287 cons = new Constraint(time_in_range,blackList);
290 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
291 xacmlTemplatePath = templateFile.toPath();
292 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), yamlParams.get("timeWindow"), time_in_range);
295 builder = builder.addLimitConstraint(policy1.getId(), cons);
296 // Build the specification
297 Results results = builder.buildSpecification();
299 ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
301 String xacmlTemplateContent;
303 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
304 HashMap<String, String> yamlSpecs = new HashMap<>();
305 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
306 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
307 yamlSpecs.put(ECOMPNAME, yamlParams.get(ECOMPNAME));
308 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getActor());
309 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getRecipe());
310 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getNum()!=null){
311 yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getNum().toString());
313 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getDuration()!=null){
314 yamlSpecs.put("timeWindow", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getDuration());
316 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_in_range().get("arg2"));
317 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_in_range().get("arg3"));
318 String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist());
319 // Convert the Policy into Stream input to Policy Adapter.
320 Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
321 return (PolicyType) policy;
322 } catch (IOException e) {
323 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() + e);
325 } catch (BuilderException e) {
326 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() +e);
331 private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
332 DecisionSettings decisionSetting = null;
334 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
335 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
336 List<?> decisionSettingsList = getDecisionSettings.getResultList();
338 for (Object id : decisionSettingsList) {
339 decisionSetting = (DecisionSettings) id;
340 if (decisionSetting.getXacmlId().equals(settingId)) {
344 return decisionSetting;
347 private void createRule(PolicyType decisionPolicy, boolean permitRule) {
348 RuleType rule = new RuleType();
350 rule.setRuleId(policyAdapter.getRuleID());
353 rule.setEffect(EffectType.PERMIT);
355 rule.setEffect(EffectType.DENY);
357 rule.setTarget(new TargetType());
359 // Create Target in Rule
360 AllOfType allOfInRule = new AllOfType();
362 // Creating match for ACCESS in rule target
363 MatchType accessMatch = new MatchType();
364 AttributeValueType accessAttributeValue = new AttributeValueType();
365 accessAttributeValue.setDataType(STRING_DATATYPE);
366 accessAttributeValue.getContent().add("DECIDE");
367 accessMatch.setAttributeValue(accessAttributeValue);
368 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
369 URI accessURI = null;
371 accessURI = new URI(ACTION_ID);
372 } catch (URISyntaxException e) {
373 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
375 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
376 accessAttributeDesignator.setDataType(STRING_DATATYPE);
377 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
378 accessMatch.setAttributeDesignator(accessAttributeDesignator);
379 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
381 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
382 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
383 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
384 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
385 dropDownMap = createDropDownMap();
387 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFProvider)){
388 // Values for AAF Provider are here for XML Creation.
389 ConditionType condition = new ConditionType();
390 ApplyType decisionApply = new ApplyType();
391 String selectedFunction = "boolean-equal";
393 AttributeValueType value1 = new AttributeValueType();
394 value1.setDataType(BOOLEAN_DATATYPE);
395 value1.getContent().add("true");
397 AttributeDesignatorType value2 = new AttributeDesignatorType();
398 value2.setAttributeId(AAFEngine.AAF_RESULT);
399 value2.setCategory(CATEGORY_RESOURCE);
400 value2.setDataType(BOOLEAN_DATATYPE);
401 value2.setMustBePresent(false);
403 ApplyType innerDecisionApply = new ApplyType();
404 innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
405 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
407 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
408 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
409 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
410 condition.setExpression(new ObjectFactory().createApply(decisionApply));
412 ApplyType notOuterApply = new ApplyType();
413 notOuterApply.setFunctionId(FUNCTION_NOT);
414 notOuterApply.getExpression().add(condition.getExpression());
415 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
417 rule.setCondition(condition);
418 allOfInRule.getMatch().add(accessMatch);
420 AnyOfType anyOfInRule = new AnyOfType();
421 anyOfInRule.getAllOf().add(allOfInRule);
423 TargetType targetInRule = new TargetType();
424 targetInRule.getAnyOf().add(anyOfInRule);
426 rule.setTarget(targetInRule);
428 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
429 AdviceExpressionType adviceExpression = new AdviceExpressionType();
430 adviceExpression.setAdviceId(AAFProvider);
431 adviceExpression.setAppliesTo(EffectType.DENY);
432 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
433 assignment.setAttributeId("aaf.response");
434 assignment.setCategory(CATEGORY_RESOURCE);
435 AttributeDesignatorType value = new AttributeDesignatorType();
436 value.setAttributeId(AAFEngine.AAF_RESPONSE);
437 value.setCategory(CATEGORY_RESOURCE);
438 value.setDataType(STRING_DATATYPE);
439 value.setMustBePresent(false);
440 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
441 adviceExpression.getAttributeAssignmentExpression().add(assignment);
442 adviceExpressions.getAdviceExpression().add(adviceExpression);
443 rule.setAdviceExpressions(adviceExpressions);
445 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
446 policyAdapter.setPolicyData(decisionPolicy);
448 }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
449 boolean isCompound = false;
450 ConditionType condition = new ConditionType();
451 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
453 for (String labelAttr : dynamicLabelRuleAlgorithms) {
454 // if the rule algorithm as a label means it is a compound
455 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
456 ApplyType decisionApply = new ApplyType();
458 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
459 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
460 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
461 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
462 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
463 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
464 condition.setExpression(new ObjectFactory().createApply(decisionApply));
468 // if rule algorithm not a compound
470 condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
474 ApplyType notOuterApply = new ApplyType();
475 notOuterApply.setFunctionId(FUNCTION_NOT);
476 notOuterApply.getExpression().add(condition.getExpression());
477 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
479 rule.setCondition(condition);
480 allOfInRule.getMatch().add(accessMatch);
482 AnyOfType anyOfInRule = new AnyOfType();
483 anyOfInRule.getAllOf().add(allOfInRule);
485 TargetType targetInRule = new TargetType();
486 targetInRule.getAnyOf().add(anyOfInRule);
488 rule.setTarget(targetInRule);
490 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
491 policyAdapter.setPolicyData(decisionPolicy);
494 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
499 private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
500 RuleType rule = new RuleType();
502 rule.setRuleId(UUID.randomUUID().toString());
505 rule.setEffect(EffectType.PERMIT);
507 rule.setEffect(EffectType.DENY);
509 rule.setTarget(new TargetType());
511 // Create Target in Rule
512 AllOfType allOfInRule = new AllOfType();
514 // Creating match for ACCESS in rule target
515 MatchType accessMatch = new MatchType();
516 AttributeValueType accessAttributeValue = new AttributeValueType();
517 accessAttributeValue.setDataType(STRING_DATATYPE);
518 accessAttributeValue.getContent().add("DECIDE");
519 accessMatch.setAttributeValue(accessAttributeValue);
520 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
521 URI accessURI = null;
523 accessURI = new URI(ACTION_ID);
524 } catch (URISyntaxException e) {
525 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
527 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
528 accessAttributeDesignator.setDataType(STRING_DATATYPE);
529 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
530 accessMatch.setAttributeDesignator(accessAttributeDesignator);
531 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
533 allOfInRule.getMatch().add(accessMatch);
535 // Creating match for ErrorCode in rule target
536 MatchType errorcodeMatch = new MatchType();
537 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
538 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
539 errorcodeAttributeValue.getContent().add(errorcode);
540 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
541 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
542 errorcodeAttributeDesignator.setCategory(CATEGORY_ACTION);
543 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
544 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
545 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
546 errorcodeMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
548 allOfInRule.getMatch().add(errorcodeMatch);
550 AnyOfType anyOfInRule = new AnyOfType();
551 anyOfInRule.getAllOf().add(allOfInRule);
553 TargetType targetInRule = new TargetType();
554 targetInRule.getAnyOf().add(anyOfInRule);
556 rule.setTarget(targetInRule);
558 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
559 AdviceExpressionType adviceExpression = new AdviceExpressionType();
560 adviceExpression.setAdviceId(RAINY_DAY);
561 adviceExpression.setAppliesTo(EffectType.PERMIT);
563 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
564 assignment.setAttributeId("treatment");
565 assignment.setCategory(CATEGORY_RESOURCE);
567 AttributeValueType treatmentAttributeValue = new AttributeValueType();
568 treatmentAttributeValue.setDataType(STRING_DATATYPE);
569 treatmentAttributeValue.getContent().add(treatment);
570 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
572 adviceExpression.getAttributeAssignmentExpression().add(assignment);
573 adviceExpressions.getAdviceExpression().add(adviceExpression);
574 rule.setAdviceExpressions(adviceExpressions);
575 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
576 policyAdapter.setPolicyData(decisionPolicy);
580 // if compound setting the inner apply here
581 protected ApplyType getInnerDecisionApply(String value1Label) {
582 ApplyType decisionApply = new ApplyType();
584 // check the index for the label.
585 for (String labelAttr : dynamicLabelRuleAlgorithms) {
586 if (labelAttr.equals(value1Label)) {
587 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
588 populateDataTypeList(value1);
590 // check if the row contains label again
591 for (String labelValue : dynamicLabelRuleAlgorithms) {
592 if (labelValue.equals(value1)) {
593 return getCompoundDecisionApply(index);
597 // Getting the values from the form.
598 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
599 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
600 decisionApply.setFunctionId(dropDownMap.get(functionKey));
601 // if two text field are rule attributes.
602 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
603 ApplyType innerDecisionApply1 = new ApplyType();
604 ApplyType innerDecisionApply2 = new ApplyType();
605 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
606 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
607 //If selected function is Integer function set integer functionID
608 if(functionKey.toLowerCase().contains("integer")){
609 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
610 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
611 attributeDesignator1.setDataType(INTEGER_DATATYPE);
612 attributeDesignator2.setDataType(INTEGER_DATATYPE);
614 //If selected function is not a Integer function set String functionID
615 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
616 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
617 attributeDesignator1.setDataType(STRING_DATATYPE);
618 attributeDesignator2.setDataType(STRING_DATATYPE);
620 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
621 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
622 //Here set actual field values
623 attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
624 attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8));
625 innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
626 innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));
627 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
628 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));
630 // if either of one text field is rule attribute.
631 if (!value1.startsWith("S_")) {
632 ApplyType innerDecisionApply = new ApplyType();
633 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
634 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
636 if (functionKey.toLowerCase().contains("integer")) {
637 innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
638 decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
639 attributeDesignator.setDataType(INTEGER_DATATYPE);
641 innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
642 decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
643 attributeDesignator.setDataType(STRING_DATATYPE);
646 String attributeId = null;
647 String attributeValue = null;
649 // Find which textField has rule attribute and set it as
650 // attributeId and the other as attributeValue.
651 attributeId = value1;
652 attributeValue = value2;
654 if (attributeId != null) {
655 attributeDesignator.setCategory(CATEGORY_RESOURCE);
656 attributeDesignator.setAttributeId(attributeId);
658 decisionConditionAttributeValue.getContent().add(attributeValue);
659 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
660 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
661 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
663 value1 = value1.substring(2, value1.length());
664 VariableReferenceType variableReferenceType = new VariableReferenceType();
665 variableReferenceType.setVariableId(value1);
667 String dataType = dataTypeList.get(index);
669 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
670 decisionConditionAttributeValue.setDataType(dataType);
671 decisionConditionAttributeValue.getContent().add(value2);
672 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
673 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
679 return decisionApply;
682 // if the rule algorithm is multiple compound one setting the apply
683 protected ApplyType getCompoundDecisionApply(int index) {
684 ApplyType decisionApply = new ApplyType();
685 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
686 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
687 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
688 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
689 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
690 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
691 return decisionApply;
694 private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
695 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
696 AttributeValueType dynamicAttributeValue = new AttributeValueType();
698 dynamicAttributeValue.setDataType(dataType);
699 dynamicAttributeValue.getContent().add(value);
701 dynamicVariable.setVariableId(key);
702 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
704 return dynamicVariable;
708 private void populateDataTypeList(String value1) {
709 String dataType = null;
711 if(value1.contains("S_")) {
712 value1 = value1.substring(2, value1.length());
713 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
714 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
715 dataType = STRING_DATATYPE;
716 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
717 dataType = BOOLEAN_DATATYPE;
719 dataType = INTEGER_DATATYPE;
725 dataTypeList.add(dataType);
728 private Map<String,String> createDropDownMap(){
729 JPAUtils jpaUtils = null;
731 jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
732 } catch (Exception e) {
733 LOGGER.error("Exception Occured"+e);
735 Map<String, String> dropDownMap = new HashMap<>();
737 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
738 for (Map.Entry<Datatype,List<FunctionDefinition>> map: functionMap.entrySet()) {
739 for (FunctionDefinition functionDef : map.getValue()) {
740 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
748 private String getDataType(String key) {
750 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
751 String dataType = null;
753 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
754 dataType = STRING_DATATYPE;
755 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
756 dataType = BOOLEAN_DATATYPE;
758 dataType = INTEGER_DATATYPE;
765 public Object getCorrectPolicyDataObject() {
766 return policyAdapter.getData();