da5c6aea15d95ba8b3ab69a69138235fc4206d64
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / DecisionPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
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;
27 import java.io.File;
28 import java.io.IOException;
29 import java.net.URI;
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;
40 import java.util.Map;
41 import java.util.UUID;
42
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;
84
85
86 @Component
87 public class DecisionPolicy extends Policy {
88
89     private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class);
90
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";
101
102     private static final String ONAPNAME = "ONAPName";
103     private static final String POLICY_NAME = "PolicyName";
104     private static final String DESCRIPTION = "description";
105
106
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<>();
112
113     private static CommonClassDao commonClassDao;
114
115     public DecisionPolicy() {
116         super();
117     }
118
119     @Autowired
120     public DecisionPolicy(CommonClassDao commonClassDao) {
121         DecisionPolicy.commonClassDao = commonClassDao;
122     }
123
124     public DecisionPolicy(PolicyRestAdapter policyAdapter) {
125         this.policyAdapter = policyAdapter;
126         this.commonClassDao = commonClassDao;
127     }
128
129     @Override
130     public Map<String, String> savePolicies() throws PAPException {
131
132         Map<String, String> successMap = new HashMap<>();
133         if (isPolicyExists()) {
134             successMap.put("EXISTS", "This Policy already exist on the PAP");
135             return successMap;
136         }
137
138         if (!isPreparedToSave()) {
139             // Prep and configure the policy for saving
140             prepareToSave();
141         }
142
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());
146
147         successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
148         return successMap;
149     }
150
151     /**
152      * Scan the Raw Policy data and set to PolicyAdapter.
153      */
154     private void readRawPolicyData() {
155         Object policy;
156         if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) {
157             policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils
158                     .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
159         } else {
160             policy = XACMLPolicyScanner.readPolicy(
161                     new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8)));
162         }
163         String policyRawDesc;
164         if (policy instanceof PolicySetType) {
165             policyRawDesc =
166                     ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
167             ((PolicySetType) policy).setDescription(policyRawDesc);
168         } else {
169             policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
170             ((PolicyType) policy).setDescription(policyRawDesc);
171         }
172         policyAdapter.setPolicyData(policy);
173         policyAdapter.setData(policy);
174         setPreparedToSave(true);
175
176     }
177
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
180     @Override
181     public boolean prepareToSave() throws PAPException {
182
183         if (isPreparedToSave()) {
184             // we have already done this
185             return true;
186         }
187
188         int version = 0;
189         String policyID = policyAdapter.getPolicyID();
190         version = policyAdapter.getHighestVersion();
191
192         if ("Raw".equals(policyAdapter.getRuleProvider())) {
193             readRawPolicyData();
194             return true;
195         }
196         // Create the Instance for pojo, PolicyType object is used in marshalling.
197         if ("Decision".equals(policyAdapter.getPolicyType())) {
198             PolicyType policyConfig = new PolicyType();
199
200             policyConfig.setVersion(Integer.toString(version));
201             policyConfig.setPolicyId(policyID);
202             policyConfig.setTarget(new TargetType());
203             policyAdapter.setData(policyConfig);
204         }
205         policyName = policyAdapter.getNewFileName();
206
207         if(policyAdapter.getRuleProvider().equals(GUARD_YAML) ||
208                 policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) ||
209                 policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){
210
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());
221             }
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
227             try {
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) {
234                 LOGGER.error(e);
235                 throw new PAPException(e);
236             }
237         } else if (policyAdapter.getData() != null) {
238             PolicyType decisionPolicy = (PolicyType) policyAdapter.getData();
239
240             decisionPolicy.setDescription(policyAdapter.getPolicyDescription());
241
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());
248             }
249             allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
250
251             AllOfType allOf = new AllOfType();
252
253             // Match for Onap
254             allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName())));
255
256             Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
257             if (policyAdapter.getRuleProvider() != null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)) {
258                 dynamicFieldComponentAttributes = new HashMap<>();
259             }
260
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);
267             }
268
269             AnyOfType anyOf = new AnyOfType();
270             anyOf.getAllOf().add(allOfOne);
271             anyOf.getAllOf().add(allOf);
272
273             TargetType target = new TargetType();
274             target.getAnyOf().add(anyOf);
275             decisionPolicy.setTarget(target);
276
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<>();
281             }
282
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);
290             }
291
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);
298                 }
299             } else {
300                 createRule(decisionPolicy, true);
301                 createRule(decisionPolicy, false);
302             }
303
304         }
305         setPreparedToSave(true);
306         return true;
307     }
308
309     public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException {
310         try {
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(","));
320                     } else {
321                         targets = new ArrayList<>();
322                         targets.add(targetString);
323                     }
324                 }
325                 matchParameters.setTargets(targets);
326             }
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(","));
339                 } else {
340                     blackList = new ArrayList<>();
341                     blackList.add(blackListString);
342                 }
343             }
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));
351                     }
352                 }
353             }
354             File templateFile;
355             Path xacmlTemplatePath;
356             ClassLoader classLoader = getClass().getClassLoader();
357             Constraint cons = new Constraint();
358             switch (ruleProvider) {
359                 case GUARD_BL_YAML:
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");
365                     }
366                     cons.setBlacklist(blackList);
367                     break;
368                 case GUARD_MIN_MAX:
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);
373                     break;
374                 default:
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.");
380                     }
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.");
387                     }
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);
391                     break;
392             }
393
394             builder = builder.addLimitConstraint(policy1.getId(), cons);
395             // Build the specification
396             Results results = builder.buildSpecification();
397             // YAML TO XACML
398             ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
399             String xacmlTemplateContent;
400             try {
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);
407
408                 yamlSpecs.put("actor", guard.getMatch_parameters().getActor());
409                 yamlSpecs.put("recipe", guard.getMatch_parameters().getRecipe());
410                 yamlSpecs.put("clname", guard.getMatch_parameters().getControlLoopName());
411
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());
415                 }
416                 if (constraints.getTime_window() != null) {
417                     yamlSpecs.put("twValue", constraints.getTime_window().get("value"));
418                     yamlSpecs.put("twUnits", constraints.getTime_window().get("units"));
419                 }
420
421                 if (constraints.getMaxVnfCount() != null) {
422                     yamlSpecs.put("max", constraints.getMaxVnfCount().toString());
423                 }
424                 if (constraints.getMinVnfCount() != null) {
425                     yamlSpecs.put("min", constraints.getMinVnfCount().toString());
426                 }
427
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());
433
434                 // Convert the Policy into Stream input to Policy Adapter.
435                 Object policy = XACMLPolicyScanner
436                         .readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
437
438                 return (PolicyType) policy;
439             } catch (IOException e) {
440                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(),
441                         e);
442             }
443         } catch (BuilderException e) {
444             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage(), e);
445             throw e;
446         }
447         return null;
448     }
449
450     private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
451         return (DecisionSettings) commonClassDao.getEntityItem(DecisionSettings.class, "xacml_id", settingId);
452     }
453
454     private void createRule(PolicyType decisionPolicy, boolean permitRule) {
455         RuleType rule = new RuleType();
456
457         rule.setRuleId(policyAdapter.getRuleID());
458
459         if (permitRule) {
460             rule.setEffect(EffectType.PERMIT);
461         } else {
462             rule.setEffect(EffectType.DENY);
463         }
464         rule.setTarget(new TargetType());
465
466         // Create Target in Rule
467         AllOfType allOfInRule = new AllOfType();
468
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;
477         try {
478             accessURI = new URI(ACTION_ID);
479         } catch (URISyntaxException e) {
480             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
481         }
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);
487
488         dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
489         dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
490         dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
491         dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
492
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();
497
498             AttributeValueType value1 = new AttributeValueType();
499             value1.setDataType(BOOLEAN_DATATYPE);
500             value1.getContent().add("true");
501
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);
507
508             ApplyType innerDecisionApply = new ApplyType();
509             innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
510             innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
511
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));
516             if (!permitRule) {
517                 ApplyType notOuterApply = new ApplyType();
518                 notOuterApply.setFunctionId(FUNCTION_NOT);
519                 notOuterApply.getExpression().add(condition.getExpression());
520                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
521             }
522             rule.setCondition(condition);
523             allOfInRule.getMatch().add(accessMatch);
524
525             AnyOfType anyOfInRule = new AnyOfType();
526             anyOfInRule.getAllOf().add(allOfInRule);
527
528             TargetType targetInRule = new TargetType();
529             targetInRule.getAnyOf().add(anyOfInRule);
530
531             rule.setTarget(targetInRule);
532             if (!permitRule) {
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);
549             }
550             decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
551             policyAdapter.setPolicyData(decisionPolicy);
552
553         } else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
554             boolean isCompound = false;
555             ConditionType condition = new ConditionType();
556             int index = dynamicFieldOneRuleAlgorithms.size() - 1;
557
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();
562
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));
570                     isCompound = true;
571                 }
572
573                 // if rule algorithm not a compound
574                 if (!isCompound) {
575                     condition.setExpression(new ObjectFactory()
576                             .createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
577                 }
578             }
579             if (!permitRule) {
580                 ApplyType notOuterApply = new ApplyType();
581                 notOuterApply.setFunctionId(FUNCTION_NOT);
582                 notOuterApply.getExpression().add(condition.getExpression());
583                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
584             }
585             rule.setCondition(condition);
586             allOfInRule.getMatch().add(accessMatch);
587
588             AnyOfType anyOfInRule = new AnyOfType();
589             anyOfInRule.getAllOf().add(allOfInRule);
590
591             TargetType targetInRule = new TargetType();
592             targetInRule.getAnyOf().add(anyOfInRule);
593
594             rule.setTarget(targetInRule);
595
596             decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
597             policyAdapter.setPolicyData(decisionPolicy);
598
599         } else {
600             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."
601                     + policyAdapter.getData().getClass().getCanonicalName());
602         }
603
604     }
605
606     private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
607         RuleType rule = new RuleType();
608
609         rule.setRuleId(UUID.randomUUID().toString());
610
611         if (permitRule) {
612             rule.setEffect(EffectType.PERMIT);
613         } else {
614             rule.setEffect(EffectType.DENY);
615         }
616         rule.setTarget(new TargetType());
617
618         // Create Target in Rule
619         AllOfType allOfInRule = new AllOfType();
620
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;
629         try {
630             accessURI = new URI(ACTION_ID);
631         } catch (URISyntaxException e) {
632             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
633         }
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);
639
640         allOfInRule.getMatch().add(accessMatch);
641
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);
654
655         allOfInRule.getMatch().add(errorcodeMatch);
656
657         AnyOfType anyOfInRule = new AnyOfType();
658         anyOfInRule.getAllOf().add(allOfInRule);
659
660         TargetType targetInRule = new TargetType();
661         targetInRule.getAnyOf().add(anyOfInRule);
662
663         rule.setTarget(targetInRule);
664
665         AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
666         AdviceExpressionType adviceExpression = new AdviceExpressionType();
667         adviceExpression.setAdviceId(RAINY_DAY);
668         adviceExpression.setAppliesTo(EffectType.PERMIT);
669
670         AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
671         assignment.setAttributeId("treatment");
672         assignment.setCategory(CATEGORY_RESOURCE);
673
674         AttributeValueType treatmentAttributeValue = new AttributeValueType();
675         treatmentAttributeValue.setDataType(STRING_DATATYPE);
676         treatmentAttributeValue.getContent().add(treatment);
677         assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
678
679         adviceExpression.getAttributeAssignmentExpression().add(assignment);
680         adviceExpressions.getAdviceExpression().add(adviceExpression);
681         rule.setAdviceExpressions(adviceExpressions);
682         decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
683         policyAdapter.setPolicyData(decisionPolicy);
684
685     }
686
687     // if compound setting the inner apply here
688     protected ApplyType getInnerDecisionApply(String value1Label) {
689         ApplyType decisionApply = new ApplyType();
690         int index = 0;
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);
696
697                 // check if the row contains label again
698                 for (String labelValue : dynamicLabelRuleAlgorithms) {
699                     if (labelValue.equals(attributeId)) {
700                         return getCompoundDecisionApply(index);
701                     }
702                 }
703
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);
711                 } else {
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);
717
718                         if (attributeId != null) {
719                             attributeDesignator.setCategory(CATEGORY_RESOURCE);
720                             attributeDesignator.setAttributeId(attributeId);
721                         }
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));
728                     } else {
729                         attributeId = attributeId.substring(2, attributeId.length());
730                         VariableReferenceType variableReferenceType = new VariableReferenceType();
731                         variableReferenceType.setVariableId(attributeId);
732
733                         String dataType = dataTypeList.get(index);
734
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));
742                     }
743                 }
744             }
745             index++;
746         }
747         return decisionApply;
748     }
749
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;
760     }
761
762     private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
763         VariableDefinitionType dynamicVariable = new VariableDefinitionType();
764         AttributeValueType dynamicAttributeValue = new AttributeValueType();
765
766         dynamicAttributeValue.setDataType(dataType);
767         dynamicAttributeValue.getContent().add(value);
768
769         dynamicVariable.setVariableId(key);
770         dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
771
772         return dynamicVariable;
773
774     }
775
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;
786             } else {
787                 dataType = INTEGER_DATATYPE;
788             }
789         } else {
790             dataType = "OTHER";
791         }
792
793         dataTypeList.add(dataType);
794     }
795
796
797     private String getDataType(String key) {
798
799         DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
800         String dataType = null;
801
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;
806         } else {
807             dataType = INTEGER_DATATYPE;
808         }
809
810         return dataType;
811     }
812
813     @Override
814     public Object getCorrectPolicyDataObject() {
815         return policyAdapter.getData();
816     }
817
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();
823         }
824         return null;
825     }
826
827     private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) {
828         AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
829         switch(functionKey.toLowerCase())
830         {
831             case "integer":
832                 attributeDesignator.setDataType(INTEGER_DATATYPE);
833                 break;
834             default:
835                 attributeDesignator.setDataType(STRING_DATATYPE);
836         }
837         return attributeDesignator;
838     }
839
840     private ApplyType generateApplyTypeDataType(String functionKey) {
841         ApplyType applyType = new ApplyType();
842         switch(functionKey.toLowerCase())
843         {
844             case "integer":
845                 applyType.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
846                 break;
847             default:
848                 applyType.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
849         }
850         return applyType;
851     }
852
853     private AttributeValueType generateAttributeValueTypeDataType(String functionKey) {
854         AttributeValueType applyType = new AttributeValueType();
855         switch(functionKey.toLowerCase())
856         {
857             case "integer":
858                 applyType.setDataType(INTEGER_DATATYPE);
859                 break;
860             default:
861                 applyType.setDataType(STRING_DATATYPE);
862         }
863         return applyType;
864     }
865
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)));
869     }
870
871     private ApplyType generateApplyTypeDataType(String value1, String functionKey) {
872         ApplyType innerApply = generateApplyTypeDataType(functionKey);
873         AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey);
874
875         attributeDesignator.setCategory(CATEGORY_RESOURCE);
876         // Here set actual field values
877         attributeDesignator
878                 .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
879         innerApply.getExpression()
880                 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
881         return innerApply;
882     }
883
884 }