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