aboutsummaryrefslogtreecommitdiffstats
path: root/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java
blob: b6e003c91705cd07c02700e482d6025c781865f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/*-
 * ============LICENSE_START=======================================================
 * ECOMP-PAP-REST
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.policy.pap.xacml.rest.components;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
import org.openecomp.policy.rest.jpa.ActionPolicyDict;
import org.openecomp.policy.rest.jpa.Datatype;
import org.openecomp.policy.rest.jpa.FunctionDefinition;

import org.openecomp.policy.xacml.api.XACMLErrorConstants;

import org.openecomp.policy.common.logging.eelf.MessageCodes;
import org.openecomp.policy.common.logging.eelf.PolicyLogger;
import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
import org.openecomp.policy.common.logging.flexlogger.Logger; 

public class ActionPolicy extends Policy {
	
	/**
	 * Config Fields
	 */
	private static final Logger logger = FlexLogger.getLogger(ConfigPolicy.class);

	public static final String JSON_CONFIG = "JSON";
	public static final String XML_CONFIG = "XML";
	public static final String PROPERTIES_CONFIG = "PROPERTIES";
	public static final String OTHER_CONFIG = "OTHER";
	
	public static final String PDP_ACTION = "PDP";
	public static final String PEP_ACTION = "PEP";
	public static final String TYPE_ACTION = "REST";

	public static final String GET_METHOD = "GET";
	public static final String PUT_METHOD = "PUT";
	public static final String POST_METHOD = "POST";

	public static final String PERFORMER_ATTRIBUTEID = "performer";
	public static final String TYPE_ATTRIBUTEID = "type";
	public static final String METHOD_ATTRIBUTEID = "method";
	public static final String HEADERS_ATTRIBUTEID = "headers";
	public static final String URL_ATTRIBUTEID = "url";
	public static final String BODY_ATTRIBUTEID = "body";
	
	List<String> dynamicLabelRuleAlgorithms = new LinkedList<String>();
	List<String> dynamicFieldFunctionRuleAlgorithms = new LinkedList<String>();
	List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<String>();
	List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<String>();
	
	protected Map<String, String> dropDownMap = new HashMap<String, String>();
	
	public ActionPolicy() {
		super();
	}
	
	public ActionPolicy(PolicyRestAdapter policyAdapter){
		this.policyAdapter = policyAdapter;
	}
	
	@Override
	public Map<String, String> savePolicies() throws Exception {
		
		Map<String, String> successMap = new HashMap<String,String>();
		if(isPolicyExists()){
			successMap.put("EXISTS", "This Policy already exist on the PAP");
			return successMap;
		}
		
		if(!isPreparedToSave()){
			//Prep and configure the policy for saving
			prepareToSave();
		}

		// Until here we prepared the data and here calling the method to create xml.
		Path newPolicyPath = null;
		newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
		successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );		
		if (successMap.containsKey("success")) {
			Path finalPolicyPath = getFinalPolicyPath();
			policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
		}
		return successMap;		
	}
	
	//This is the method for preparing the policy for saving.  We have broken it out
	//separately because the fully configured policy is used for multiple things
	@Override
	public boolean prepareToSave() throws Exception{

		if(isPreparedToSave()){
			//we have already done this
			return true;
		}
		
		int version = 0;
		String policyID = policyAdapter.getPolicyID();
		
		if (policyAdapter.isEditPolicy()) {
			version = policyAdapter.getHighestVersion() + 1;
		} else {
			version = 1;
		}
		
		// Create the Instance for pojo, PolicyType object is used in marshalling.
		if (policyAdapter.getPolicyType().equals("Action")) {
			PolicyType policyConfig = new PolicyType();

			policyConfig.setVersion(Integer.toString(version));
			policyConfig.setPolicyId(policyID);
			policyConfig.setTarget(new TargetType());
			policyAdapter.setData(policyConfig);
		}
		
		if (policyAdapter.getData() != null) {
			
			// Save off everything
			// making ready all the required elements to generate the action policy xml.
			// Get the uniqueness for policy name.
			Path newFile = getNextFilename(Paths.get(policyAdapter.getParentPath().toString()), policyAdapter.getPolicyType(), policyAdapter.getPolicyName(), version);
			if (newFile == null) {
				//TODO:EELF Cleanup - Remove logger
				//logger.error("Policy already Exists, cannot create the policy.");
				PolicyLogger.error("Policy already Exists, cannot create the policy.");
				setPolicyExists(true);
				return false;
			}
			policyName = newFile.getFileName().toString();
			
			// Action body is optional so checking value provided or not
			//String actionBodyString = policyAdapter.getActionBody();
			String comboDictValue = policyAdapter.getActionAttribute();
	        String actionBody = getActionPolicyDict(comboDictValue).getBody();
			if(!(actionBody==null || "".equals(actionBody))){
				saveActionBody(policyName, actionBody);
			}
			
			// Make sure the filename ends with an extension
			if (policyName.endsWith(".xml") == false) {
				policyName = policyName + ".xml";
			}
			
			PolicyType actionPolicy = (PolicyType) policyAdapter.getData();
			
			actionPolicy.setDescription(policyAdapter.getPolicyDescription());
			
			actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());

			AllOfType allOf = new AllOfType();
			
			Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
			
			// If there is any dynamic field attributes create the matches here
			for (String keyField : dynamicFieldComponentAttributes.keySet()) {
				String key = keyField;
				String value = dynamicFieldComponentAttributes.get(key);
				MatchType dynamicMatch = createDynamicMatch(key, value);
				allOf.getMatch().add(dynamicMatch);
			}

			AnyOfType anyOf = new AnyOfType();
			anyOf.getAllOf().add(allOf);

			TargetType target = new TargetType();
			target.getAnyOf().add(anyOf);
			
			// Adding the target to the policy element
			actionPolicy.setTarget(target);
			
			RuleType rule = new RuleType();
			rule.setRuleId(policyAdapter.getRuleID());

			rule.setEffect(EffectType.PERMIT);
			rule.setTarget(new TargetType());
			
			dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
			dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
			dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
			dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
			//dropDownMap = policyAdapter.getDropDownMap();
			dropDownMap = createDropDownMap();
						
			// Rule attributes are optional and dynamic so check and add them to condition.
			if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) {
				boolean isCompound = false;
				ConditionType condition = new ConditionType();
				int index = dynamicFieldOneRuleAlgorithms.size() - 1;

				for (String labelAttr : dynamicLabelRuleAlgorithms) {
					// if the rule algorithm as a label means it is a compound
					if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) {
						ApplyType actionApply = new ApplyType();

						String selectedFunction = (String) dynamicFieldFunctionRuleAlgorithms.get(index).toString();
						String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
						String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
						actionApply.setFunctionId(dropDownMap.get(selectedFunction));
						actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
						actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
						condition.setExpression(new ObjectFactory().createApply(actionApply));
						isCompound = true;
					}
					
				}
				// if rule algorithm not a compound
				if (!isCompound) {
					condition.setExpression(new ObjectFactory().createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index).toString())));
				}
				rule.setCondition(condition);
			}
			// set the obligations to rule
			rule.setObligationExpressions(getObligationExpressions());
			actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
			policyAdapter.setPolicyData(actionPolicy);
		}  else {
			//TODO:EELF Cleanup - Remove logger
			//logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
		}	

		setPreparedToSave(true);
		return true;
	}
	
	// Saving the json Configurations file if exists at server location for action policy.
	private void saveActionBody(String policyName, String actionBodyData) {
		int version = 0;
		int highestVersion = 0;
		String domain = getParentPathSubScopeDir();
		String path = domain.replace('\\', '.');
		String removeExtension = policyName.substring(0, policyName.indexOf(".xml"));
		String removeVersion = removeExtension.substring(0, removeExtension.indexOf("."));
		if (policyAdapter.isEditPolicy()) {
			highestVersion = policyAdapter.getHighestVersion();
			if(highestVersion != 0){
				version = highestVersion + 1;	
			}
		} else {
			version = 1;
		}
		if(path.contains("/")){
			path = domain.replace('/', '.');
			logger.info("print the path:" +path);
		}
		try {

			File file = new File(ACTION_HOME + File.separator + path + "." + removeVersion + "." + version + ".json");
			
			if (logger.isDebugEnabled())
				logger.debug("The action body is at " + file.getAbsolutePath());

			// if file doesn't exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
			File configHomeDir = new File(ACTION_HOME);
			File[] listOfFiles = configHomeDir.listFiles();
			if (listOfFiles != null){
				for(File eachFile : listOfFiles){
					if(eachFile.isFile()){
						String fileNameWithoutExtension = FilenameUtils.removeExtension(eachFile.getName());
						String actionFileNameWithoutExtension = FilenameUtils.removeExtension(path + "." + policyName);
						if (fileNameWithoutExtension.equals(actionFileNameWithoutExtension)){
							//delete the file
							if (logger.isInfoEnabled())
								logger.info("Deleting action body is at " + eachFile.getAbsolutePath());
							eachFile.delete();
						}
					}
				}
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(actionBodyData);
			bw.close();

			if (logger.isInfoEnabled()) {
				logger.info("Action Body is succesfully saved at " + file.getAbsolutePath());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	// Data required for obligation part is setting here.
	private ObligationExpressionsType getObligationExpressions() {
		
		// TODO: add code to get all these values from dictionary
		ObligationExpressionsType obligations = new ObligationExpressionsType();

		ObligationExpressionType obligation = new ObligationExpressionType();
        String comboDictValue = policyAdapter.getActionAttribute();
		obligation.setObligationId(comboDictValue);
		obligation.setFulfillOn(EffectType.PERMIT);

		// Add Action Assignment:
		AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
		assignment1.setAttributeId(PERFORMER_ATTRIBUTEID);
		assignment1.setCategory(CATEGORY_RECIPIENT_SUBJECT);

		AttributeValueType actionNameAttributeValue = new AttributeValueType();
		actionNameAttributeValue.setDataType(STRING_DATATYPE);
		actionNameAttributeValue.getContent().add(performer.get(policyAdapter.getActionPerformer()));

		assignment1.setExpression(new ObjectFactory().createAttributeValue(actionNameAttributeValue));
		obligation.getAttributeAssignmentExpression().add(assignment1);

		// Add Type Assignment:
		AttributeAssignmentExpressionType assignmentType = new AttributeAssignmentExpressionType();
		assignmentType.setAttributeId(TYPE_ATTRIBUTEID);
		assignmentType.setCategory(CATEGORY_RESOURCE);

		AttributeValueType typeAttributeValue = new AttributeValueType();
		typeAttributeValue.setDataType(STRING_DATATYPE);
		String actionDictType = getActionPolicyDict(comboDictValue).getType();
		typeAttributeValue.getContent().add(actionDictType);

		assignmentType.setExpression(new ObjectFactory().createAttributeValue(typeAttributeValue));
		obligation.getAttributeAssignmentExpression().add(assignmentType);

		// Add Rest_URL Assignment:
		AttributeAssignmentExpressionType assignmentURL = new AttributeAssignmentExpressionType();
		assignmentURL.setAttributeId(URL_ATTRIBUTEID);
		assignmentURL.setCategory(CATEGORY_RESOURCE);

		AttributeValueType actionURLAttributeValue = new AttributeValueType();
		actionURLAttributeValue.setDataType(URI_DATATYPE);
		String actionDictUrl = getActionPolicyDict(comboDictValue).getUrl();
		actionURLAttributeValue.getContent().add(actionDictUrl);

		assignmentURL.setExpression(new ObjectFactory().createAttributeValue(actionURLAttributeValue));
		obligation.getAttributeAssignmentExpression().add(assignmentURL);

		// Add Method Assignment:
		AttributeAssignmentExpressionType assignmentMethod = new AttributeAssignmentExpressionType();
		assignmentMethod.setAttributeId(METHOD_ATTRIBUTEID);
		assignmentMethod.setCategory(CATEGORY_RESOURCE);

		AttributeValueType methodAttributeValue = new AttributeValueType();
		methodAttributeValue.setDataType(STRING_DATATYPE);
		String actionDictMethod = getActionPolicyDict(comboDictValue).getMethod();
		methodAttributeValue.getContent().add(actionDictMethod);

		assignmentMethod.setExpression(new ObjectFactory().createAttributeValue(methodAttributeValue));
		obligation.getAttributeAssignmentExpression().add(assignmentMethod);

		// Add JSON_URL Assignment:
		String actionBody = getActionPolicyDict(comboDictValue).getBody();
		if (!actionBody.equals(null)) {
		//if(!(actionBody==null || "".equals(actionBody))){
			AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType();
			assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID);
			assignmentJsonURL.setCategory(CATEGORY_RESOURCE);

			AttributeValueType jsonURLAttributeValue = new AttributeValueType();
			jsonURLAttributeValue.setDataType(URI_DATATYPE);
			final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());;
			String policyDir = policyAdapter.getParentPath().toString();
			int startIndex1 = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
			policyDir = policyDir.substring(startIndex1, policyDir.length());
			logger.info("print the main domain value"+policyDir);
			String path = policyDir.replace('\\', '.');
			if(path.contains("/")){
				path = policyDir.replace('/', '.');
				logger.info("print the path:" +path);
			}
			jsonURLAttributeValue.getContent().add(CONFIG_URL + "/Action/" +  path + "." +FilenameUtils.removeExtension(policyName) + ".json");

			assignmentJsonURL.setExpression(new ObjectFactory().createAttributeValue(jsonURLAttributeValue));
			obligation.getAttributeAssignmentExpression().add(assignmentJsonURL);
		}

		if(!getActionPolicyDict(comboDictValue).getHeader().equals(null)){
			String headerVal = getActionPolicyDict(comboDictValue).getHeader();
			if(headerVal != null && !headerVal.equals("")){
				// parse it on : to get number of headers
				String[] result = headerVal.split(":");
				System.out.println(Arrays.toString(result));
				for (String eachString : result){
					// parse each value on =
					String[] textFieldVals = eachString.split("=");
					obligation.getAttributeAssignmentExpression().add(addDynamicHeaders(textFieldVals[0], textFieldVals[1]));
				}
			}

		}
			
		obligations.getObligationExpression().add(obligation);
		return obligations;
	}

	
	// if compound setting the inner apply here
	protected ApplyType getInnerActionApply(String value1Label) {
		ApplyType actionApply = new ApplyType();
		int index = 0;
		// check the index for the label.
		for (String labelAttr : dynamicLabelRuleAlgorithms) {
			if (labelAttr.equals(value1Label)) {
				String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
				// check if the row contains label again
				for (String labelValue : dynamicLabelRuleAlgorithms) {
					if (labelValue.equals(value1)) {
						return getCompoundApply(index);
					}
				}

				// Getting the values from the form.
				String functionKey = dynamicFieldFunctionRuleAlgorithms.get(index).toString();
				String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
				actionApply.setFunctionId(dropDownMap.get(functionKey));
				// if two text field are rule attributes.
				if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
					ApplyType innerActionApply1 = new ApplyType();
					ApplyType innerActionApply2 = new ApplyType();
					AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
					AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
					// If selected function is Integer function set integer functionID
					if (functionKey.toLowerCase().contains("integer")) {
						innerActionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
						innerActionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
						attributeDesignator1.setDataType(INTEGER_DATATYPE);
						attributeDesignator2.setDataType(INTEGER_DATATYPE);
					} else {
						// If selected function is not a Integer function
						// set String functionID
						innerActionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
						innerActionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
						attributeDesignator1.setDataType(STRING_DATATYPE);
						attributeDesignator2.setDataType(STRING_DATATYPE);
					}
					attributeDesignator1.setCategory(CATEGORY_RESOURCE);
					attributeDesignator2.setCategory(CATEGORY_RESOURCE);

					// Here set actual field values
					attributeDesignator1.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));
					attributeDesignator2.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));

					innerActionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator1));
					innerActionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator2));

					actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1));
					actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2));

				} else {// if either of one text field is rule attribute.
					ApplyType innerActionApply = new ApplyType();
					AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
					AttributeValueType actionConditionAttributeValue = new AttributeValueType();

					if (functionKey.toLowerCase().contains("integer")) {
						innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
						actionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
						attributeDesignator.setDataType(INTEGER_DATATYPE);
					} else {
						innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
						actionConditionAttributeValue.setDataType(STRING_DATATYPE);
						attributeDesignator.setDataType(STRING_DATATYPE);
					}

					String attributeId = null;
					String attributeValue = null;

					// Find which textField has rule attribute and set it as
					attributeId = value1;
					attributeValue = value2;

					if (attributeId != null) {
						attributeDesignator.setCategory(CATEGORY_RESOURCE);
						attributeDesignator.setAttributeId(attributeId);
					}
					actionConditionAttributeValue.getContent().add(attributeValue);
					innerActionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
					// Decide the order of element based the values.
					if (attributeId.equals(value1)) {
						actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
						actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
					} else {
						actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
						actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
					}
				}
			}
			index++;
		}
		return actionApply;
	}

	// if the rule algorithm is multiple compound one setting the apply
	protected ApplyType getCompoundApply(int index) {
		ApplyType actionApply = new ApplyType();
		String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index).toString();
		String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
		String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
		actionApply.setFunctionId(dropDownMap.get(selectedFunction));
		actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
		actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
		return actionApply;
	}
		
	// Adding the dynamic headers if any
	private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) {
		AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType();
		assignmentHeaders.setAttributeId("headers:" + header);
		assignmentHeaders.setCategory(CATEGORY_RESOURCE);

		AttributeValueType headersAttributeValue = new AttributeValueType();
		headersAttributeValue.setDataType(STRING_DATATYPE);
		headersAttributeValue.getContent().add(value);

		assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue));
		return assignmentHeaders;
	}
	
	private Map<String,String> createDropDownMap(){
		JPAUtils jpaUtils = null;
		try {
			jpaUtils = JPAUtils.getJPAUtilsInstance(policyAdapter.getEntityManagerFactory());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
		Map<String, String> dropDownMap = new HashMap<String, String>();
		for (Datatype id : functionMap.keySet()) {
			List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
					.get(id);
			for (FunctionDefinition functionDef : functionDefinitions) {
				dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
			}
		}
		
		return dropDownMap;
	}
	
	private ActionPolicyDict getActionPolicyDict(String attributeName){
		ActionPolicyDict retObj = new ActionPolicyDict();
		//EntityManagerFactory emf = policyAdapter.getEntityManagerFactory();
		//EntityManager em = emf.createEntityManager();
		EntityManager em = policyAdapter.getEntityManagerFactory().createEntityManager();
		Query getActionPolicyDicts = em.createNamedQuery("ActionPolicyDict.findAll");	
		List<?> actionPolicyDicts = getActionPolicyDicts.getResultList(); 	
		
		for (Object id : actionPolicyDicts) {
			//ActionPolicyDict actionPolicyList = actionPolicyDicts.getItem(id).getEntity();
			ActionPolicyDict actionPolicy = (ActionPolicyDict) id;
			if(attributeName.equals(actionPolicy.getAttributeName())){
				retObj = actionPolicy;
				break;
			}
		}
		
		try{
		em.getTransaction().commit();
		} catch(Exception e){
			try{
				em.getTransaction().rollback();
			} catch(Exception e2){
				e2.printStackTrace();
			}
		}
		em.close();
		
		return retObj;
	}

	@Override
	public Object getCorrectPolicyDataObject() {
		return policyAdapter.getPolicyData();
	}



}