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