Commit includes ControlLoopPolicy API and bugfixes
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / DecisionPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.pap.xacml.rest.components;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.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<>();
92         List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
93         List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
94         List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
95         List<String> dataTypeList = new LinkedList<>();
96         
97         protected Map<String, String> dropDownMap = new HashMap<>();
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<>();
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<>();
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<>();
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<>();
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<>();
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"));
247                         cons.setTime_in_range(time_in_range);
248                         builder = builder.addLimitConstraint(policy1.getId(), cons);
249                         // Build the specification
250                         Results results = builder.buildSpecification();
251                         // YAML TO XACML 
252                         ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
253                         Path xacmlTemplatePath = Paths.get(XACMLTEMPLATE);
254                 String xacmlTemplateContent;
255                 try {
256                                 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
257                                 HashMap<String, String> yamlSpecs = new HashMap<String, String>();
258                                 yamlSpecs.put("PolicyName", yamlParams.get("PolicyName"));
259                                 yamlSpecs.put("description", yamlParams.get("description"));
260                                 yamlSpecs.put("ECOMPName", yamlParams.get("ECOMPName"));
261                                 yamlSpecs.put("actor", ((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getActor());
262                                 yamlSpecs.put("recipe", ((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getRecipe());
263                                 yamlSpecs.put("limit", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getNum().toString());
264                                 yamlSpecs.put("timeWindow", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getDuration());
265                                 yamlSpecs.put("guardActiveStart", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getTime_in_range().get("arg2"));
266                                 yamlSpecs.put("guardActiveEnd", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getTime_in_range().get("arg3"));
267                         String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs);
268                         // Convert the  Policy into Stream input to Policy Adapter. 
269                         Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
270                                 return (PolicyType) policy;
271                         } catch (IOException e) {
272                                 PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage());
273                         }
274                 } catch (BuilderException e) {
275                         PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage());
276                 }
277                 return null;
278         }
279         
280         private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
281                 DecisionSettings decisionSetting = null;
282                 
283                 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
284                 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
285                 List<?> decisionSettingsList = getDecisionSettings.getResultList();
286                 
287                 for (Object id : decisionSettingsList) {
288                         decisionSetting = (DecisionSettings) id;
289                         if (decisionSetting.getXacmlId().equals(settingId)) {
290                                 break;
291                         }
292                 }
293                 return decisionSetting;
294         }
295         
296         private void createRule(PolicyType decisionPolicy, boolean permitRule) {
297                 RuleType rule = new RuleType();
298                         
299                 rule.setRuleId(policyAdapter.getRuleID());
300                         
301                 if (permitRule) {
302                         rule.setEffect(EffectType.PERMIT);
303                 } else {
304                         rule.setEffect(EffectType.DENY);
305                 }
306                 rule.setTarget(new TargetType());
307
308                 // Create Target in Rule
309                 AllOfType allOfInRule = new AllOfType();
310
311                 // Creating match for ACCESS in rule target
312                 MatchType accessMatch = new MatchType();
313                 AttributeValueType accessAttributeValue = new AttributeValueType();
314                 accessAttributeValue.setDataType(STRING_DATATYPE);
315                 accessAttributeValue.getContent().add("DECIDE");
316                 accessMatch.setAttributeValue(accessAttributeValue);
317                 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
318                 URI accessURI = null;
319                 try {
320                         accessURI = new URI(ACTION_ID);
321                 } catch (URISyntaxException e) {
322                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
323                 }
324                 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
325                 accessAttributeDesignator.setDataType(STRING_DATATYPE);
326                 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
327                 accessMatch.setAttributeDesignator(accessAttributeDesignator);
328                 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
329                 
330                 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
331                 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
332                 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
333                 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
334                 dropDownMap = createDropDownMap();
335                 
336                 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFProvider)){
337                         // Values for AAF Provider are here for XML Creation. 
338                         ConditionType condition = new ConditionType();
339                         ApplyType decisionApply = new ApplyType();
340                         String selectedFunction = "boolean-equal";
341                         
342                         AttributeValueType value1 = new AttributeValueType();
343                         value1.setDataType(BOOLEAN_DATATYPE);
344                         value1.getContent().add("true");
345                         
346                         AttributeDesignatorType value2 = new AttributeDesignatorType();
347                         value2.setAttributeId(AAFEngine.AAF_RESULT);
348                         value2.setCategory(CATEGORY_RESOURCE);
349                         value2.setDataType(BOOLEAN_DATATYPE);
350                         value2.setMustBePresent(false);
351                         
352                         ApplyType innerDecisionApply = new ApplyType();
353                         innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
354                         innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
355                         
356                         decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
357                         decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
358                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
359                         condition.setExpression(new ObjectFactory().createApply(decisionApply));
360                         if (!permitRule) {
361                                 ApplyType notOuterApply = new ApplyType();
362                                 notOuterApply.setFunctionId(FUNCTION_NOT);
363                                 notOuterApply.getExpression().add(condition.getExpression());
364                                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
365                         }
366                         rule.setCondition(condition);
367                         allOfInRule.getMatch().add(accessMatch);
368
369                         AnyOfType anyOfInRule = new AnyOfType();
370                         anyOfInRule.getAllOf().add(allOfInRule);
371
372                         TargetType targetInRule = new TargetType();
373                         targetInRule.getAnyOf().add(anyOfInRule);
374
375                         rule.setTarget(targetInRule);
376                         if(!permitRule){
377                                 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
378                                 AdviceExpressionType adviceExpression = new AdviceExpressionType();
379                                 adviceExpression.setAdviceId(AAFProvider);
380                                 adviceExpression.setAppliesTo(EffectType.DENY);
381                                 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
382                                 assignment.setAttributeId("aaf.response");
383                                 assignment.setCategory(CATEGORY_RESOURCE);
384                                 AttributeDesignatorType value = new AttributeDesignatorType();
385                                 value.setAttributeId(AAFEngine.AAF_RESPONSE);
386                                 value.setCategory(CATEGORY_RESOURCE);
387                                 value.setDataType(STRING_DATATYPE);
388                                 value.setMustBePresent(false);
389                                 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
390                                 adviceExpression.getAttributeAssignmentExpression().add(assignment);
391                                 adviceExpressions.getAdviceExpression().add(adviceExpression);
392                                 rule.setAdviceExpressions(adviceExpressions);
393                         }
394                         decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
395                         policyAdapter.setPolicyData(decisionPolicy);
396                         
397                 }else if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) {
398                         boolean isCompound = false;
399                         ConditionType condition = new ConditionType();
400                         int index = dynamicFieldOneRuleAlgorithms.size() - 1;
401                         
402                         for (String labelAttr : dynamicLabelRuleAlgorithms) {
403                                 // if the rule algorithm as a label means it is a compound
404                                 if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) {
405                                         ApplyType decisionApply = new ApplyType();
406
407                                         String selectedFunction = (String) dynamicFieldComboRuleAlgorithms.get(index).toString();
408                                         String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
409                                         String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
410                                         decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
411                                         decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
412                                         decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
413                                         condition.setExpression(new ObjectFactory().createApply(decisionApply));
414                                         isCompound = true;
415                                 }
416
417                                 // if rule algorithm not a compound
418                                 if (!isCompound) {
419                                         condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index).toString())));
420                                 }
421                         }
422                         if (!permitRule) {
423                                 ApplyType notOuterApply = new ApplyType();
424                                 notOuterApply.setFunctionId(FUNCTION_NOT);
425                                 notOuterApply.getExpression().add(condition.getExpression());
426                                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
427                         }
428                         rule.setCondition(condition);
429                         allOfInRule.getMatch().add(accessMatch);
430
431                         AnyOfType anyOfInRule = new AnyOfType();
432                         anyOfInRule.getAllOf().add(allOfInRule);
433
434                         TargetType targetInRule = new TargetType();
435                         targetInRule.getAnyOf().add(anyOfInRule);
436
437                         rule.setTarget(targetInRule);
438
439                         decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
440                         policyAdapter.setPolicyData(decisionPolicy);
441                         
442                 } else {
443                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
444                 }
445
446         }
447         
448         // if compound setting the inner apply here
449         protected ApplyType getInnerDecisionApply(String value1Label) {
450                 ApplyType decisionApply = new ApplyType();
451                 int index = 0;
452                 // check the index for the label.
453                 for (String labelAttr : dynamicLabelRuleAlgorithms) {
454                         if (labelAttr.equals(value1Label)) {
455                                 String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
456                                 populateDataTypeList(value1);
457
458                                 // check if the row contains label again
459                                 for (String labelValue : dynamicLabelRuleAlgorithms) {
460                                         if (labelValue.equals(value1)) {
461                                                 return getCompoundDecisionApply(index);
462                                         }
463                                 }
464
465                                 // Getting the values from the form.
466                                 String functionKey = (String) dynamicFieldComboRuleAlgorithms.get(index).toString();
467                                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
468                                 decisionApply.setFunctionId(dropDownMap.get(functionKey));
469                                 // if two text field are rule attributes.
470                                 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
471                                         ApplyType innerDecisionApply1 = new ApplyType();
472                                         ApplyType       innerDecisionApply2      = new  ApplyType();                                                      
473                                         AttributeDesignatorType  attributeDesignator1     = new AttributeDesignatorType();                                                               
474                                         AttributeDesignatorType  attributeDesignator2     = new AttributeDesignatorType();                                                                                       
475                                         //If selected function is Integer function set integer functionID
476                                         if(functionKey.toLowerCase().contains("integer")){
477                                                 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
478                                                 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
479                                                 attributeDesignator1.setDataType(INTEGER_DATATYPE);
480                                                 attributeDesignator2.setDataType(INTEGER_DATATYPE);
481                                         } else{
482                                                 //If selected function is not a Integer function set String functionID
483                                                 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
484                                                 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
485                                                 attributeDesignator1.setDataType(STRING_DATATYPE);
486                                                 attributeDesignator2.setDataType(STRING_DATATYPE);
487                                         }
488                                         attributeDesignator1.setCategory(CATEGORY_RESOURCE);
489                                         attributeDesignator2.setCategory(CATEGORY_RESOURCE);
490                                         //Here set actual field values
491                                         attributeDesignator1.setAttributeId(value1.  contains("resource:")?value1.substring( 9):value1.substring(8));
492                                         attributeDesignator2.setAttributeId(value1.  contains("resource:")?value1.substring( 9):value1.substring(8));                                                    
493                                         innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
494                                         innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));                                                    
495                                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
496                                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));                                                          
497                                 } else {
498                                         // if either of one text field is rule attribute.
499                                         if (!value1.startsWith("S_")) {
500                                                 ApplyType innerDecisionApply = new ApplyType();
501                                                 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
502                                                 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
503
504                                                 if (functionKey.toLowerCase().contains("integer")) {
505                                                         innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
506                                                         decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
507                                                         attributeDesignator.setDataType(INTEGER_DATATYPE);
508                                                 } else {
509                                                         innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
510                                                         decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
511                                                         attributeDesignator.setDataType(STRING_DATATYPE);
512                                                 }
513
514                                                 String attributeId = null;
515                                                 String attributeValue = null;
516
517                                                 // Find which textField has rule attribute and set it as
518                                                 // attributeId and the other as attributeValue.
519                                                 attributeId = value1;
520                                                 attributeValue = value2;
521                         
522                                                 if (attributeId != null) {
523                                                         attributeDesignator.setCategory(CATEGORY_RESOURCE);
524                                                         attributeDesignator.setAttributeId(attributeId);
525                                                 }
526                                                 decisionConditionAttributeValue.getContent().add(attributeValue);
527                                                 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
528                                                 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
529                                                 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
530                                         } else {
531                                                 value1 = value1.substring(2, value1.length());
532                                                 VariableReferenceType variableReferenceType = new VariableReferenceType();
533                                                 variableReferenceType.setVariableId(value1);
534                                                 
535                                                 String dataType = dataTypeList.get(index);
536
537                                                 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
538                                                 decisionConditionAttributeValue.setDataType(dataType);
539                                                 decisionConditionAttributeValue.getContent().add(value2);
540                                                 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
541                                                 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
542                                         }
543                                 }
544                         }
545                         index++;
546                 }
547                 return decisionApply;
548         }
549
550         // if the rule algorithm is multiple compound one setting the apply
551         protected ApplyType getCompoundDecisionApply(int index) {
552                 ApplyType decisionApply = new ApplyType();
553                 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index).toString();
554                 String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
555                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
556                 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
557                 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
558                 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
559                 return decisionApply;
560         }
561         
562         private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
563                 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
564                 AttributeValueType dynamicAttributeValue = new AttributeValueType();
565
566                 dynamicAttributeValue.setDataType(dataType);
567                 dynamicAttributeValue.getContent().add(value);
568
569                 dynamicVariable.setVariableId(key);
570                 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
571
572                 return dynamicVariable;
573
574         }       
575         
576         private void populateDataTypeList(String value1) {
577                 
578                 ///String value1 = dynamicFieldDecisionOneRuleAlgorithms.get(index).getValue().toString();
579                 String dataType = null;
580
581                 if(value1.contains("S_")) {
582                         value1 = value1.substring(2, value1.length());
583                         DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1);
584                         if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("string")) {
585                                 dataType = STRING_DATATYPE;
586                         } else if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("boolean")) {
587                                 dataType = BOOLEAN_DATATYPE;
588                         } else {
589                                 dataType = INTEGER_DATATYPE;
590                         }
591                 } else {
592                         dataType = "OTHER";
593                 }
594
595                 dataTypeList.add(dataType);
596         }
597         
598         private Map<String,String> createDropDownMap(){
599                 JPAUtils jpaUtils = null;
600                 try {
601                         jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
602                 } catch (Exception e) {
603                         LOGGER.error("Exception Occured"+e);
604                 }
605                 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
606                 Map<String, String> dropDownMap = new HashMap<String, String>();
607                 for (Datatype id : functionMap.keySet()) {
608                         List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
609                                         .get(id);
610                         for (FunctionDefinition functionDef : functionDefinitions) {
611                                 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
612                         }
613                 }
614                 
615                 return dropDownMap;
616         }
617         
618         private String getDataType(String key) {
619                 
620                 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
621                 String dataType = null;
622                 
623                 if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("string")) {
624                         dataType = STRING_DATATYPE;
625                 } else if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("boolean")) {
626                         dataType = BOOLEAN_DATATYPE;
627                 } else {
628                         dataType = INTEGER_DATATYPE;
629                 }
630                 
631                 return dataType;
632         }
633
634         @Override
635         public Object getCorrectPolicyDataObject() {
636                 return policyAdapter.getData();
637         }
638         
639 }