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