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