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