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