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