Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / ActionPolicy.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.BufferedWriter;
24 import java.io.File;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.LinkedList;
32 import java.util.List;
33 import java.util.Map;
34
35 import javax.persistence.EntityManager;
36 import javax.persistence.EntityManagerFactory;
37 import javax.persistence.Query;
38
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
54
55 import org.apache.commons.io.FilenameUtils;
56 import org.apache.commons.logging.Log;
57 import org.apache.commons.logging.LogFactory;
58 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
59 import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
60 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
61 import org.openecomp.policy.rest.jpa.Datatype;
62 import org.openecomp.policy.rest.jpa.FunctionDefinition;
63
64 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
65
66 import org.openecomp.policy.common.logging.eelf.MessageCodes;
67 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
68 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
69 import org.openecomp.policy.common.logging.flexlogger.Logger; 
70
71 public class ActionPolicy extends Policy {
72         
73         /**
74          * Config Fields
75          */
76         private static final Logger logger = FlexLogger.getLogger(ConfigPolicy.class);
77
78         public static final String JSON_CONFIG = "JSON";
79         public static final String XML_CONFIG = "XML";
80         public static final String PROPERTIES_CONFIG = "PROPERTIES";
81         public static final String OTHER_CONFIG = "OTHER";
82         
83         public static final String PDP_ACTION = "PDP";
84         public static final String PEP_ACTION = "PEP";
85         public static final String TYPE_ACTION = "REST";
86
87         public static final String GET_METHOD = "GET";
88         public static final String PUT_METHOD = "PUT";
89         public static final String POST_METHOD = "POST";
90
91         public static final String PERFORMER_ATTRIBUTEID = "performer";
92         public static final String TYPE_ATTRIBUTEID = "type";
93         public static final String METHOD_ATTRIBUTEID = "method";
94         public static final String HEADERS_ATTRIBUTEID = "headers";
95         public static final String URL_ATTRIBUTEID = "url";
96         public static final String BODY_ATTRIBUTEID = "body";
97         
98         List<String> dynamicLabelRuleAlgorithms = new LinkedList<String>();
99         List<String> dynamicFieldFunctionRuleAlgorithms = new LinkedList<String>();
100         List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<String>();
101         List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<String>();
102         
103         protected Map<String, String> dropDownMap = new HashMap<String, String>();
104         
105         public ActionPolicy() {
106                 super();
107         }
108         
109         public ActionPolicy(PolicyRestAdapter policyAdapter){
110                 this.policyAdapter = policyAdapter;
111         }
112         
113         @Override
114         public Map<String, String> savePolicies() throws Exception {
115                 
116                 Map<String, String> successMap = new HashMap<String,String>();
117                 if(isPolicyExists()){
118                         successMap.put("EXISTS", "This Policy already exist on the PAP");
119                         return successMap;
120                 }
121                 
122                 if(!isPreparedToSave()){
123                         //Prep and configure the policy for saving
124                         prepareToSave();
125                 }
126
127                 // Until here we prepared the data and here calling the method to create xml.
128                 Path newPolicyPath = null;
129                 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
130                 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );         
131                 if (successMap.containsKey("success")) {
132                         Path finalPolicyPath = getFinalPolicyPath();
133                         policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
134                 }
135                 return successMap;              
136         }
137         
138         //This is the method for preparing the policy for saving.  We have broken it out
139         //separately because the fully configured policy is used for multiple things
140         @Override
141         public boolean prepareToSave() throws Exception{
142
143                 if(isPreparedToSave()){
144                         //we have already done this
145                         return true;
146                 }
147                 
148                 int version = 0;
149                 String policyID = policyAdapter.getPolicyID();
150                 
151                 if (policyAdapter.isEditPolicy()) {
152                         version = policyAdapter.getHighestVersion() + 1;
153                 } else {
154                         version = 1;
155                 }
156                 
157                 // Create the Instance for pojo, PolicyType object is used in marshalling.
158                 if (policyAdapter.getPolicyType().equals("Action")) {
159                         PolicyType policyConfig = new PolicyType();
160
161                         policyConfig.setVersion(Integer.toString(version));
162                         policyConfig.setPolicyId(policyID);
163                         policyConfig.setTarget(new TargetType());
164                         policyAdapter.setData(policyConfig);
165                 }
166                 
167                 if (policyAdapter.getData() != null) {
168                         
169                         // Save off everything
170                         // making ready all the required elements to generate the action policy xml.
171                         // Get the uniqueness for policy name.
172                         Path newFile = getNextFilename(Paths.get(policyAdapter.getParentPath().toString()), policyAdapter.getPolicyType(), policyAdapter.getPolicyName(), version);
173                         if (newFile == null) {
174                                 //TODO:EELF Cleanup - Remove logger
175                                 //logger.error("Policy already Exists, cannot create the policy.");
176                                 PolicyLogger.error("Policy already Exists, cannot create the policy.");
177                                 setPolicyExists(true);
178                                 return false;
179                         }
180                         policyName = newFile.getFileName().toString();
181                         
182                         // Action body is optional so checking value provided or not
183                         //String actionBodyString = policyAdapter.getActionBody();
184                         String comboDictValue = policyAdapter.getActionAttribute();
185                 String actionBody = getActionPolicyDict(comboDictValue).getBody();
186                         if(!(actionBody==null || "".equals(actionBody))){
187                                 saveActionBody(policyName, actionBody);
188                         }
189                         
190                         // Make sure the filename ends with an extension
191                         if (policyName.endsWith(".xml") == false) {
192                                 policyName = policyName + ".xml";
193                         }
194                         
195                         PolicyType actionPolicy = (PolicyType) policyAdapter.getData();
196                         
197                         actionPolicy.setDescription(policyAdapter.getPolicyDescription());
198                         
199                         actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
200
201                         AllOfType allOf = new AllOfType();
202                         
203                         Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
204                         
205                         // If there is any dynamic field attributes create the matches here
206                         for (String keyField : dynamicFieldComponentAttributes.keySet()) {
207                                 String key = keyField;
208                                 String value = dynamicFieldComponentAttributes.get(key);
209                                 MatchType dynamicMatch = createDynamicMatch(key, value);
210                                 allOf.getMatch().add(dynamicMatch);
211                         }
212
213                         AnyOfType anyOf = new AnyOfType();
214                         anyOf.getAllOf().add(allOf);
215
216                         TargetType target = new TargetType();
217                         target.getAnyOf().add(anyOf);
218                         
219                         // Adding the target to the policy element
220                         actionPolicy.setTarget(target);
221                         
222                         RuleType rule = new RuleType();
223                         rule.setRuleId(policyAdapter.getRuleID());
224
225                         rule.setEffect(EffectType.PERMIT);
226                         rule.setTarget(new TargetType());
227                         
228                         dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
229                         dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
230                         dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
231                         dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
232                         //dropDownMap = policyAdapter.getDropDownMap();
233                         dropDownMap = createDropDownMap();
234                                                 
235                         // Rule attributes are optional and dynamic so check and add them to condition.
236                         if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) {
237                                 boolean isCompound = false;
238                                 ConditionType condition = new ConditionType();
239                                 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
240
241                                 for (String labelAttr : dynamicLabelRuleAlgorithms) {
242                                         // if the rule algorithm as a label means it is a compound
243                                         if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) {
244                                                 ApplyType actionApply = new ApplyType();
245
246                                                 String selectedFunction = (String) dynamicFieldFunctionRuleAlgorithms.get(index).toString();
247                                                 String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
248                                                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
249                                                 actionApply.setFunctionId(dropDownMap.get(selectedFunction));
250                                                 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
251                                                 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
252                                                 condition.setExpression(new ObjectFactory().createApply(actionApply));
253                                                 isCompound = true;
254                                         }
255                                         
256                                 }
257                                 // if rule algorithm not a compound
258                                 if (!isCompound) {
259                                         condition.setExpression(new ObjectFactory().createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index).toString())));
260                                 }
261                                 rule.setCondition(condition);
262                         }
263                         // set the obligations to rule
264                         rule.setObligationExpressions(getObligationExpressions());
265                         actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
266                         policyAdapter.setPolicyData(actionPolicy);
267                 }  else {
268                         //TODO:EELF Cleanup - Remove logger
269                         //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
270                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
271                 }       
272
273                 setPreparedToSave(true);
274                 return true;
275         }
276         
277         // Saving the json Configurations file if exists at server location for action policy.
278         private void saveActionBody(String policyName, String actionBodyData) {
279                 int version = 0;
280                 int highestVersion = 0;
281                 String domain = getParentPathSubScopeDir();
282                 String path = domain.replace('\\', '.');
283                 String removeExtension = policyName.substring(0, policyName.indexOf(".xml"));
284                 String removeVersion = removeExtension.substring(0, removeExtension.indexOf("."));
285                 if (policyAdapter.isEditPolicy()) {
286                         highestVersion = policyAdapter.getHighestVersion();
287                         if(highestVersion != 0){
288                                 version = highestVersion + 1;   
289                         }
290                 } else {
291                         version = 1;
292                 }
293                 if(path.contains("/")){
294                         path = domain.replace('/', '.');
295                         logger.info("print the path:" +path);
296                 }
297                 try {
298
299                         File file = new File(ACTION_HOME + File.separator + path + "." + removeVersion + "." + version + ".json");
300                         
301                         if (logger.isDebugEnabled())
302                                 logger.debug("The action body is at " + file.getAbsolutePath());
303
304                         // if file doesn't exists, then create it
305                         if (!file.exists()) {
306                                 file.createNewFile();
307                         }
308                         File configHomeDir = new File(ACTION_HOME);
309                         File[] listOfFiles = configHomeDir.listFiles();
310                         if (listOfFiles != null){
311                                 for(File eachFile : listOfFiles){
312                                         if(eachFile.isFile()){
313                                                 String fileNameWithoutExtension = FilenameUtils.removeExtension(eachFile.getName());
314                                                 String actionFileNameWithoutExtension = FilenameUtils.removeExtension(path + "." + policyName);
315                                                 if (fileNameWithoutExtension.equals(actionFileNameWithoutExtension)){
316                                                         //delete the file
317                                                         if (logger.isInfoEnabled())
318                                                                 logger.info("Deleting action body is at " + eachFile.getAbsolutePath());
319                                                         eachFile.delete();
320                                                 }
321                                         }
322                                 }
323                         }
324                         FileWriter fw = new FileWriter(file.getAbsoluteFile());
325                         BufferedWriter bw = new BufferedWriter(fw);
326                         bw.write(actionBodyData);
327                         bw.close();
328
329                         if (logger.isInfoEnabled()) {
330                                 logger.info("Action Body is succesfully saved at " + file.getAbsolutePath());
331                         }
332                 } catch (IOException e) {
333                         e.printStackTrace();
334                 }
335
336         }
337         
338         // Data required for obligation part is setting here.
339         private ObligationExpressionsType getObligationExpressions() {
340                 
341                 // TODO: add code to get all these values from dictionary
342                 ObligationExpressionsType obligations = new ObligationExpressionsType();
343
344                 ObligationExpressionType obligation = new ObligationExpressionType();
345         String comboDictValue = policyAdapter.getActionAttribute();
346                 obligation.setObligationId(comboDictValue);
347                 obligation.setFulfillOn(EffectType.PERMIT);
348
349                 // Add Action Assignment:
350                 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
351                 assignment1.setAttributeId(PERFORMER_ATTRIBUTEID);
352                 assignment1.setCategory(CATEGORY_RECIPIENT_SUBJECT);
353
354                 AttributeValueType actionNameAttributeValue = new AttributeValueType();
355                 actionNameAttributeValue.setDataType(STRING_DATATYPE);
356                 actionNameAttributeValue.getContent().add(performer.get(policyAdapter.getActionPerformer()));
357
358                 assignment1.setExpression(new ObjectFactory().createAttributeValue(actionNameAttributeValue));
359                 obligation.getAttributeAssignmentExpression().add(assignment1);
360
361                 // Add Type Assignment:
362                 AttributeAssignmentExpressionType assignmentType = new AttributeAssignmentExpressionType();
363                 assignmentType.setAttributeId(TYPE_ATTRIBUTEID);
364                 assignmentType.setCategory(CATEGORY_RESOURCE);
365
366                 AttributeValueType typeAttributeValue = new AttributeValueType();
367                 typeAttributeValue.setDataType(STRING_DATATYPE);
368                 String actionDictType = getActionPolicyDict(comboDictValue).getType();
369                 typeAttributeValue.getContent().add(actionDictType);
370
371                 assignmentType.setExpression(new ObjectFactory().createAttributeValue(typeAttributeValue));
372                 obligation.getAttributeAssignmentExpression().add(assignmentType);
373
374                 // Add Rest_URL Assignment:
375                 AttributeAssignmentExpressionType assignmentURL = new AttributeAssignmentExpressionType();
376                 assignmentURL.setAttributeId(URL_ATTRIBUTEID);
377                 assignmentURL.setCategory(CATEGORY_RESOURCE);
378
379                 AttributeValueType actionURLAttributeValue = new AttributeValueType();
380                 actionURLAttributeValue.setDataType(URI_DATATYPE);
381                 String actionDictUrl = getActionPolicyDict(comboDictValue).getUrl();
382                 actionURLAttributeValue.getContent().add(actionDictUrl);
383
384                 assignmentURL.setExpression(new ObjectFactory().createAttributeValue(actionURLAttributeValue));
385                 obligation.getAttributeAssignmentExpression().add(assignmentURL);
386
387                 // Add Method Assignment:
388                 AttributeAssignmentExpressionType assignmentMethod = new AttributeAssignmentExpressionType();
389                 assignmentMethod.setAttributeId(METHOD_ATTRIBUTEID);
390                 assignmentMethod.setCategory(CATEGORY_RESOURCE);
391
392                 AttributeValueType methodAttributeValue = new AttributeValueType();
393                 methodAttributeValue.setDataType(STRING_DATATYPE);
394                 String actionDictMethod = getActionPolicyDict(comboDictValue).getMethod();
395                 methodAttributeValue.getContent().add(actionDictMethod);
396
397                 assignmentMethod.setExpression(new ObjectFactory().createAttributeValue(methodAttributeValue));
398                 obligation.getAttributeAssignmentExpression().add(assignmentMethod);
399
400                 // Add JSON_URL Assignment:
401                 String actionBody = getActionPolicyDict(comboDictValue).getBody();
402                 if (!actionBody.equals(null)) {
403                 //if(!(actionBody==null || "".equals(actionBody))){
404                         AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType();
405                         assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID);
406                         assignmentJsonURL.setCategory(CATEGORY_RESOURCE);
407
408                         AttributeValueType jsonURLAttributeValue = new AttributeValueType();
409                         jsonURLAttributeValue.setDataType(URI_DATATYPE);
410                         final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());;
411                         String policyDir = policyAdapter.getParentPath().toString();
412                         int startIndex1 = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
413                         policyDir = policyDir.substring(startIndex1, policyDir.length());
414                         logger.info("print the main domain value"+policyDir);
415                         String path = policyDir.replace('\\', '.');
416                         if(path.contains("/")){
417                                 path = policyDir.replace('/', '.');
418                                 logger.info("print the path:" +path);
419                         }
420                         jsonURLAttributeValue.getContent().add(CONFIG_URL + "/Action/" +  path + "." +FilenameUtils.removeExtension(policyName) + ".json");
421
422                         assignmentJsonURL.setExpression(new ObjectFactory().createAttributeValue(jsonURLAttributeValue));
423                         obligation.getAttributeAssignmentExpression().add(assignmentJsonURL);
424                 }
425
426                 if(!getActionPolicyDict(comboDictValue).getHeader().equals(null)){
427                         String headerVal = getActionPolicyDict(comboDictValue).getHeader();
428                         if(headerVal != null && !headerVal.equals("")){
429                                 // parse it on : to get number of headers
430                                 String[] result = headerVal.split(":");
431                                 System.out.println(Arrays.toString(result));
432                                 for (String eachString : result){
433                                         // parse each value on =
434                                         String[] textFieldVals = eachString.split("=");
435                                         obligation.getAttributeAssignmentExpression().add(addDynamicHeaders(textFieldVals[0], textFieldVals[1]));
436                                 }
437                         }
438
439                 }
440                         
441                 obligations.getObligationExpression().add(obligation);
442                 return obligations;
443         }
444
445         
446         // if compound setting the inner apply here
447         protected ApplyType getInnerActionApply(String value1Label) {
448                 ApplyType actionApply = new ApplyType();
449                 int index = 0;
450                 // check the index for the label.
451                 for (String labelAttr : dynamicLabelRuleAlgorithms) {
452                         if (labelAttr.equals(value1Label)) {
453                                 String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
454                                 // check if the row contains label again
455                                 for (String labelValue : dynamicLabelRuleAlgorithms) {
456                                         if (labelValue.equals(value1)) {
457                                                 return getCompoundApply(index);
458                                         }
459                                 }
460
461                                 // Getting the values from the form.
462                                 String functionKey = dynamicFieldFunctionRuleAlgorithms.get(index).toString();
463                                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
464                                 actionApply.setFunctionId(dropDownMap.get(functionKey));
465                                 // if two text field are rule attributes.
466                                 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
467                                         ApplyType innerActionApply1 = new ApplyType();
468                                         ApplyType innerActionApply2 = new ApplyType();
469                                         AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
470                                         AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
471                                         // If selected function is Integer function set integer functionID
472                                         if (functionKey.toLowerCase().contains("integer")) {
473                                                 innerActionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
474                                                 innerActionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
475                                                 attributeDesignator1.setDataType(INTEGER_DATATYPE);
476                                                 attributeDesignator2.setDataType(INTEGER_DATATYPE);
477                                         } else {
478                                                 // If selected function is not a Integer function
479                                                 // set String functionID
480                                                 innerActionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
481                                                 innerActionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
482                                                 attributeDesignator1.setDataType(STRING_DATATYPE);
483                                                 attributeDesignator2.setDataType(STRING_DATATYPE);
484                                         }
485                                         attributeDesignator1.setCategory(CATEGORY_RESOURCE);
486                                         attributeDesignator2.setCategory(CATEGORY_RESOURCE);
487
488                                         // Here set actual field values
489                                         attributeDesignator1.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));
490                                         attributeDesignator2.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));
491
492                                         innerActionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator1));
493                                         innerActionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator2));
494
495                                         actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1));
496                                         actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2));
497
498                                 } else {// if either of one text field is rule attribute.
499                                         ApplyType innerActionApply = new ApplyType();
500                                         AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
501                                         AttributeValueType actionConditionAttributeValue = new AttributeValueType();
502
503                                         if (functionKey.toLowerCase().contains("integer")) {
504                                                 innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
505                                                 actionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
506                                                 attributeDesignator.setDataType(INTEGER_DATATYPE);
507                                         } else {
508                                                 innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
509                                                 actionConditionAttributeValue.setDataType(STRING_DATATYPE);
510                                                 attributeDesignator.setDataType(STRING_DATATYPE);
511                                         }
512
513                                         String attributeId = null;
514                                         String attributeValue = null;
515
516                                         // Find which textField has rule attribute and set it as
517                                         attributeId = value1;
518                                         attributeValue = value2;
519
520                                         if (attributeId != null) {
521                                                 attributeDesignator.setCategory(CATEGORY_RESOURCE);
522                                                 attributeDesignator.setAttributeId(attributeId);
523                                         }
524                                         actionConditionAttributeValue.getContent().add(attributeValue);
525                                         innerActionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
526                                         // Decide the order of element based the values.
527                                         if (attributeId.equals(value1)) {
528                                                 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
529                                                 actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
530                                         } else {
531                                                 actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
532                                                 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
533                                         }
534                                 }
535                         }
536                         index++;
537                 }
538                 return actionApply;
539         }
540
541         // if the rule algorithm is multiple compound one setting the apply
542         protected ApplyType getCompoundApply(int index) {
543                 ApplyType actionApply = new ApplyType();
544                 String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index).toString();
545                 String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
546                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
547                 actionApply.setFunctionId(dropDownMap.get(selectedFunction));
548                 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
549                 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
550                 return actionApply;
551         }
552                 
553         // Adding the dynamic headers if any
554         private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) {
555                 AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType();
556                 assignmentHeaders.setAttributeId("headers:" + header);
557                 assignmentHeaders.setCategory(CATEGORY_RESOURCE);
558
559                 AttributeValueType headersAttributeValue = new AttributeValueType();
560                 headersAttributeValue.setDataType(STRING_DATATYPE);
561                 headersAttributeValue.getContent().add(value);
562
563                 assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue));
564                 return assignmentHeaders;
565         }
566         
567         private Map<String,String> createDropDownMap(){
568                 JPAUtils jpaUtils = null;
569                 try {
570                         jpaUtils = JPAUtils.getJPAUtilsInstance(policyAdapter.getEntityManagerFactory());
571                 } catch (Exception e) {
572                         // TODO Auto-generated catch block
573                         e.printStackTrace();
574                 }
575                 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
576                 Map<String, String> dropDownMap = new HashMap<String, String>();
577                 for (Datatype id : functionMap.keySet()) {
578                         List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
579                                         .get(id);
580                         for (FunctionDefinition functionDef : functionDefinitions) {
581                                 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
582                         }
583                 }
584                 
585                 return dropDownMap;
586         }
587         
588         private ActionPolicyDict getActionPolicyDict(String attributeName){
589                 ActionPolicyDict retObj = new ActionPolicyDict();
590                 //EntityManagerFactory emf = policyAdapter.getEntityManagerFactory();
591                 //EntityManager em = emf.createEntityManager();
592                 EntityManager em = policyAdapter.getEntityManagerFactory().createEntityManager();
593                 Query getActionPolicyDicts = em.createNamedQuery("ActionPolicyDict.findAll");   
594                 List<?> actionPolicyDicts = getActionPolicyDicts.getResultList();       
595                 
596                 for (Object id : actionPolicyDicts) {
597                         //ActionPolicyDict actionPolicyList = actionPolicyDicts.getItem(id).getEntity();
598                         ActionPolicyDict actionPolicy = (ActionPolicyDict) id;
599                         if(attributeName.equals(actionPolicy.getAttributeName())){
600                                 retObj = actionPolicy;
601                                 break;
602                         }
603                 }
604                 
605                 try{
606                 em.getTransaction().commit();
607                 } catch(Exception e){
608                         try{
609                                 em.getTransaction().rollback();
610                         } catch(Exception e2){
611                                 e2.printStackTrace();
612                         }
613                 }
614                 em.close();
615                 
616                 return retObj;
617         }
618
619         @Override
620         public Object getCorrectPolicyDataObject() {
621                 return policyAdapter.getPolicyData();
622         }
623
624
625
626 }