Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / ActionPolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
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.controller;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.io.PrintWriter;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.LinkedHashMap;
32 import java.util.LinkedList;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.UUID;
36
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39 import javax.xml.bind.JAXBElement;
40
41 import org.json.JSONObject;
42 import org.openecomp.policy.adapter.PolicyAdapter;
43 import org.openecomp.policy.admin.PolicyNotificationMail;
44 import org.openecomp.policy.admin.RESTfulPAPEngine;
45 import org.openecomp.policy.dao.FunctionDefinitionDao;
46 import org.openecomp.policy.dao.PolicyVersionDao;
47 import org.openecomp.policy.dao.RuleAlgorithmsDao;
48 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
49 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
50 import org.openecomp.policy.rest.dao.ActionPolicyDictDao;
51 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
52 import org.openecomp.policy.rest.jpa.PolicyVersion;
53 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
54 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
55 import org.openecomp.portalsdk.core.web.support.JsonMessage;
56 import org.openecomp.portalsdk.core.web.support.UserUtils;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.http.MediaType;
59 import org.springframework.stereotype.Controller;
60 import org.springframework.web.bind.annotation.RequestMapping;
61 import org.springframework.web.servlet.ModelAndView;
62
63 import com.att.research.xacml.api.XACML3;
64 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
65 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
66 import com.fasterxml.jackson.databind.DeserializationFeature;
67 import com.fasterxml.jackson.databind.JsonNode;
68 import com.fasterxml.jackson.databind.ObjectMapper;
69 import com.google.common.base.Joiner;
70
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
84 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
85 import org.openecomp.policy.common.logging.flexlogger.Logger;
86
87 @Controller
88 @RequestMapping({"/"})
89 public class ActionPolicyController extends RestrictedBaseController{
90         private static final Logger logger = FlexLogger.getLogger(ActionPolicyController.class);
91
92         private static FunctionDefinitionDao functionDefinitionDao;
93         private static RuleAlgorithmsDao ruleAlgorithmsDao;
94         private static ActionPolicyDictDao actionPolciyDictDao;
95         private static PolicyVersionDao policyVersionDao;
96         private static WatchPolicyNotificationDao policyNotificationDao;
97
98         @Autowired 
99         private ActionPolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, ActionPolicyDictDao actionPolciyDictDao,
100                         PolicyVersionDao policyVersionDao, FunctionDefinitionDao functionDefinitionDao, WatchPolicyNotificationDao policyNotificationDao){
101                 ActionPolicyController.ruleAlgorithmsDao =ruleAlgorithmsDao;
102                 ActionPolicyController.actionPolciyDictDao =actionPolciyDictDao;
103                 ActionPolicyController.policyVersionDao =policyVersionDao;
104                 ActionPolicyController.functionDefinitionDao = functionDefinitionDao;
105                 ActionPolicyController.policyNotificationDao = policyNotificationDao;
106         }
107         
108         public ActionPolicyController(){}
109
110         private String ruleID = "";
111         private ArrayList<Object> attributeList;
112         protected  LinkedList<Integer> ruleAlgoirthmTracker;
113         public static final String PERFORMER_ATTRIBUTEID = "performer";
114         protected  Map<String, String> performer = new HashMap<String, String>();
115         private  ArrayList<Object>  ruleAlgorithmList;
116
117         public String newPolicyID() {
118                 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
119                                 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
120         }
121
122
123         @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
124         public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
125                 try{
126                         Map<String, Object> model = new HashMap<String, Object>();
127                         ObjectMapper mapper = new ObjectMapper();
128                         model.put("functionDefinitionDatas", mapper.writeValueAsString(functionDefinitionDao.getFunctionDefinitionByName()));
129                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
130                         JSONObject j = new JSONObject(msg);
131                         response.getWriter().write(j.toString());
132                 }
133                 catch (Exception e){
134                         logger.equals(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
135                 }
136         }
137
138         @RequestMapping(value={"/policyController/save_Actionpolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
139         public ModelAndView saveActionPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
140                 try {
141                         String userId = UserUtils.getUserIdFromCookie(request);
142                         RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
143                         ObjectMapper mapper = new ObjectMapper();
144                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
145                         JsonNode root = mapper.readTree(request.getReader());
146                         PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
147                         if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
148                                 policyData.isEditPolicy = true;
149                         }
150                         if(root.get("policyData").get("model").get("path").size() != 0){
151                                 String dirName = "";
152                                 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
153                                         dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
154                                 }
155                                 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
156                         }else{
157                                 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
158                         }
159                         int version = 0;
160                         int highestVersion = 0;
161                         int descriptionVersion = 0;
162                         //get the highest version of policy from policy version table.
163                         //getting the sub scope domain where the policy is created or updated
164                         String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Action_" + policyData.getPolicyName();
165                         List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
166                         if (versionList.size() > 0) {           
167                                 for(int i = 0;  i < versionList.size(); i++) {
168                                         PolicyVersion entityItem = versionList.get(i);
169                                         if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
170                                                 highestVersion = entityItem.getHigherVersion();
171                                         }
172                                 }
173                         }               
174                         if(highestVersion != 0){
175                                 version = highestVersion;
176                                 descriptionVersion = highestVersion +1;         
177                         }else{
178                                 version = 1;
179                                 descriptionVersion = 1;
180                         }
181
182                         //set policy adapter values for Building JSON object containing policy data
183                         String createdBy = "";
184                         String modifiedBy = userId;
185                         if(descriptionVersion == 1){
186                                 createdBy = userId;
187                         }else{
188                                 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
189                                 File policyPath = new File(policyName);
190                                 try {
191                                         createdBy =     XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
192                                 } catch (IOException e) {
193                                         createdBy = "guest";
194                                 }
195                         }
196
197                         policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
198                         Map<String, String> successMap = new HashMap<String, String>();
199                         Map<String, String> attributeMap = new HashMap<String, String>();
200
201                         List<String> dynamicRuleAlgorithmLabels = new LinkedList<String>();
202                         List<String> dynamicRuleAlgorithmCombo = new LinkedList<String>();
203                         List<String> dynamicRuleAlgorithmField1 = new LinkedList<String>();
204                         List<String> dynamicRuleAlgorithmField2 = new LinkedList<String>();
205
206                         //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
207                         List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms();
208                         for (int i = 0; i < ruleAlgorithmsList.size(); i++) {
209                                 RuleAlgorithms a = ruleAlgorithmsList.get(i);
210                                 if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) {
211                                         policyData.setRuleCombiningAlgId(a.getXacmlId());
212                                         break;
213                                 }
214                         }
215
216                         if(policyData.getAttributes().size() > 0){
217                                 for(Object attribute : policyData.getAttributes()){
218                                         if(attribute instanceof LinkedHashMap<?, ?>){
219                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
220                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
221                                                 attributeMap.put(key, value);   
222                                         }
223                                 }
224                         }
225
226                         if(policyData.getRuleAlgorithmschoices().size() > 0){
227                                 for(Object attribute : policyData.getRuleAlgorithmschoices()){
228                                         if(attribute instanceof LinkedHashMap<?, ?>){
229                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
230                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
231                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
232                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
233                                                 dynamicRuleAlgorithmLabels.add(label);
234                                                 dynamicRuleAlgorithmField1.add(key);
235                                                 dynamicRuleAlgorithmCombo.add(rule);
236                                                 dynamicRuleAlgorithmField2.add(value);
237                                         }
238                                 }
239                         }
240
241                         String actionDictValue = policyData.getActionAttributeValue();
242                         ActionPolicyDict jsonData = ((ActionPolicyDict) actionPolciyDictDao.getActionEntityDatabyId(actionDictValue));
243                         String actionBodyString = jsonData.getBody();
244                         String actionDictHeader = jsonData.getHeader();
245                         String actionDictType = jsonData.getType();
246                         String actionDictUrl = jsonData.getUrl();
247                         String actionDictMethod = jsonData.getMethod();
248                         policyData.setActionDictHeader(actionDictHeader);
249                         policyData.setActionDictType(actionDictType);
250                         policyData.setActionDictUrl(actionDictUrl);
251                         policyData.setActionDictMethod(actionDictMethod);
252                         policyData.setActionAttribute(actionDictValue);
253                         policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
254                         policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
255                         policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
256                         policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
257                         if (actionBodyString != null) {
258                                 policyData.setActionBody(actionBodyString);
259                         }
260                         policyData.setDynamicFieldConfigAttributes(attributeMap);
261
262                         if (policyData.isEditPolicy()){
263                                 //increment the version and set in policyAdapter
264                                 policyData.setVersion(String.valueOf(version));
265                                 policyData.setHighestVersion(version);
266                                 policyData.setPolicyID(this.newPolicyID());
267                                 policyData.setRuleID(ruleID);
268                                 successMap = engine.updatePolicyRequest(policyData);
269                         } else {
270                                 //send it for policy creation   
271                                 policyData.setVersion(String.valueOf(version));
272                                 policyData.setHighestVersion(version);
273                                 successMap = engine.createPolicyRequest(policyData);
274
275                         }
276                         if (successMap.containsKey("success")) {
277                                 // Add it into our tree
278                                 Path finalPolicyPath = null;
279                                 finalPolicyPath = Paths.get(successMap.get("success"));
280                                 PolicyElasticSearchController controller = new PolicyElasticSearchController();
281                                 controller.updateElk(finalPolicyPath.toString());
282                                 File file = finalPolicyPath.toFile();
283                                 if(file != null){
284                                         String policyName = file.toString();
285                                         String removePath = policyName.substring(policyName.indexOf("repository")+11);
286                                         String removeXml = removePath.replace(".xml", "");
287                                         String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
288                                         List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
289                                         if (policyVersionList.size() > 0) {             
290                                                 for(int i = 0;  i < policyVersionList.size(); i++) {
291                                                         PolicyVersion entityItem = policyVersionList.get(i);
292                                                         if(entityItem.getPolicyName().equals(removeExtension)){
293                                                                 version = entityItem.getHigherVersion() +1;
294                                                                 entityItem.setActiveVersion(version);
295                                                                 entityItem.setHigherVersion(version);
296                                                                 entityItem.setModifiedBy(userId);
297                                                                 policyVersionDao.update(entityItem);
298                                                                 if(policyData.isEditPolicy){
299                                                                         PolicyNotificationMail email = new PolicyNotificationMail();
300                                                                         String mode = "EditPolicy";
301                                                                         String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
302                                                                         email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
303                                                                 }
304                                                         }
305                                                 }
306                                         }else{
307                                                 PolicyVersion entityItem = new PolicyVersion();
308                                                 entityItem.setActiveVersion(version);
309                                                 entityItem.setHigherVersion(version);
310                                                 entityItem.setPolicyName(removeExtension);
311                                                 entityItem.setCreatedBy(userId);
312                                                 entityItem.setModifiedBy(userId);
313                                                 policyVersionDao.Save(entityItem);
314                                         }                       
315                                 }
316                         }
317                         response.setCharacterEncoding("UTF-8");
318                         response.setContentType("application / json");
319                         request.setCharacterEncoding("UTF-8");
320
321                         PrintWriter out = response.getWriter();
322                         String responseString = mapper.writeValueAsString(successMap);
323                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
324                         out.write(j.toString());
325                         return null;
326                 }
327                 catch (Exception e){
328                         response.setCharacterEncoding("UTF-8");
329                         request.setCharacterEncoding("UTF-8");
330                         PrintWriter out = response.getWriter();
331                         out.write(e.getMessage());
332                 }
333                 return null;
334         }
335
336         public void PrePopulateActionPolicyData(PolicyAdapter policyAdapter) {
337                 attributeList = new ArrayList<Object>();
338                 ruleAlgorithmList = new ArrayList<Object>();
339                 performer.put("PDP", "PDPAction");
340                 performer.put("PEP", "PEPAction");
341
342                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
343                         Object policyData = policyAdapter.getPolicyData();
344                         PolicyType policy = (PolicyType) policyData;
345                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
346                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1, policyAdapter.getPolicyName().lastIndexOf("."));
347                         policyAdapter.setPolicyName(policyNameValue);
348                         String description = "";
349                         try{
350                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
351                         }catch(Exception e){
352                                 description = policy.getDescription();
353                         }
354                         policyAdapter.setPolicyDescription(description);
355                         // Get the target data under policy for Action.
356                         TargetType target = policy.getTarget();
357                         if (target != null) {
358                                 // under target we have AnyOFType
359                                 List<AnyOfType> anyOfList = target.getAnyOf();
360                                 if (anyOfList != null) {
361                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
362                                         while (iterAnyOf.hasNext()) {
363                                                 AnyOfType anyOf = iterAnyOf.next();
364                                                 // Under AntOfType we have AllOfType
365                                                 List<AllOfType> allOfList = anyOf.getAllOf();
366                                                 if (allOfList != null) {
367                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
368                                                         while (iterAllOf.hasNext()) {
369                                                                 AllOfType allOf = iterAllOf.next();
370                                                                 // Under AllOfType we have Mathch.
371                                                                 List<MatchType> matchList = allOf.getMatch();
372                                                                 if (matchList != null) {
373                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
374                                                                         while (iterMatch.hasNext()) {
375                                                                                 MatchType match = iterMatch.next();
376                                                                                 //
377                                                                                 // Under the match we have attributevalue and
378                                                                                 // attributeDesignator. So,finally down to the actual attribute.
379                                                                                 //
380                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
381                                                                                 String value = (String) attributeValue.getContent().get(0);
382                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
383                                                                                 String attributeId = designator.getAttributeId();
384                                                                                 // Component attributes are saved under Target here we are fetching them back.
385                                                                                 // One row is default so we are not adding dynamic componet at index 0.
386                                                                                 Map<String, String> attribute = new HashMap<String, String>();
387                                                                                 attribute.put("option", attributeId);
388                                                                                 attribute.put("number", value);
389                                                                                 attributeList.add(attribute);   
390                                                                         }
391                                                                 }
392                                                                 policyAdapter.setAttributes(attributeList);
393                                                         }
394                                                 }
395                                         }       
396                                 }
397
398                                 List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
399                                 // Under rule we have Condition and obligation.
400                                 for (Object o : ruleList) {
401                                         if (o instanceof RuleType) {
402                                                 // get the condition data under the rule for rule Algorithms.
403                                                 ruleID = ((RuleType) o).getRuleId();
404                                                 ConditionType condition = ((RuleType) o).getCondition();
405                                                 ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
406                                                 if (condition != null) {
407                                                         int index = 0;
408                                                         ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
409                                                         ruleAlgoirthmTracker = new LinkedList<Integer>();
410                                                         // Populating Rule Algorithms starting from compound.
411                                                         prePopulateCompoundRuleAlgorithm(index, actionApply);
412                                                 }
413                                                 policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
414                                                 // get the Obligation data under the rule for Form elements.
415                                                 if (obligations != null) {
416                                                         // Under the obligationExpressions we have obligationExpression.
417                                                         List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
418                                                         if (obligationList != null) {
419                                                                 Iterator<ObligationExpressionType> iterObligation = obligationList.iterator();
420                                                                 while (iterObligation.hasNext()) {
421                                                                         ObligationExpressionType obligation = iterObligation.next();
422                                                                         policyAdapter.setActionAttributeValue(obligation.getObligationId());
423                                                                         // Under the obligationExpression we have attributeAssignmentExpression.
424                                                                         List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation.getAttributeAssignmentExpression();
425                                                                         if (attributeAssignmentExpressionList != null) {
426                                                                                 Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList.iterator();
427                                                                                 while (iterAttributeAssignmentExpression.hasNext()) {
428                                                                                         AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression.next();
429                                                                                         String attributeID = attributeAssignmentExpression.getAttributeId();
430                                                                                         AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression.getExpression().getValue();
431                                                                                         if (attributeID.equals(PERFORMER_ATTRIBUTEID)) {
432                                                                                                 for (String key : performer.keySet()) {
433                                                                                                         String keyValue = performer.get(key);
434                                                                                                         if (keyValue.equals(attributeValue.getContent().get(0))) {
435                                                                                                                 policyAdapter.setActionPerformer(key);
436                                                                                                         }
437                                                                                                 }
438                                                                                         }
439                                                                                 }
440                                                                         }
441                                                                 }
442                                                         }
443                                                 } 
444                                         }
445                                 }
446                         }
447                 }               
448         }
449
450         private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) {
451                 boolean isCompoundRule = true;
452                 List<JAXBElement<?>> jaxbActionTypes = actionApply.getExpression();
453                 for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
454                         // If There is Attribute Value under Action Type that means we came to the final child
455                         if (logger.isDebugEnabled()) {
456                                 logger.debug("Prepopulating rule algoirthm: " + index);
457                         }
458                         // Check to see if Attribute Value exists, if yes then it is not a compound rule
459                         if (jaxbElement.getValue() instanceof AttributeValueType) {
460                                 prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes);
461                                 ruleAlgoirthmTracker.addLast(index);
462                                 isCompoundRule = false;
463                                 index++;
464                         }
465                 }
466                 if (isCompoundRule) {
467                         // As it's compound rule, Get the Apply types
468                         for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
469                                 ApplyType innerActionApply = (ApplyType) jaxbElement.getValue();
470                                 index = prePopulateCompoundRuleAlgorithm(index, innerActionApply);
471                         }
472                         // Populate combo box
473                         if (logger.isDebugEnabled()) {
474                                 logger.debug("Prepopulating Compound rule algorithm: " + index);
475                         }
476                         Map<String, String> rule = new HashMap<String, String>();
477                         for (String key : PolicyController.getDropDownMap().keySet()) {
478                                 String keyValue = PolicyController.getDropDownMap().get(key);
479                                 if (keyValue.equals(actionApply.getFunctionId())) {
480                                         rule.put("dynamicRuleAlgorithmCombo", key);
481                                 }
482                         }
483                         rule.put("id", "A" + (index +1));
484                         // Populate Key and values for Compound Rule
485                         rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 ));
486                         ruleAlgoirthmTracker.removeLast();
487                         rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
488                         ruleAlgoirthmTracker.removeLast();
489                         ruleAlgoirthmTracker.addLast(index);
490                         ruleAlgorithmList.add(rule);
491                         index++;
492                 }
493                 return index;
494         }
495
496         private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) {
497                 Map<String, String> ruleMap = new HashMap<String, String>();
498                 ruleMap.put("id", "A" + (index +1));
499                 // Populate combo box
500                 Map<String, String> dropDownMap = PolicyController.getDropDownMap();
501                 for (String key : dropDownMap.keySet()) {
502                         String keyValue = dropDownMap.get(key);
503                         if (keyValue.equals(actionApply.getFunctionId())) {
504                                 ruleMap.put("dynamicRuleAlgorithmCombo", key);
505                         }
506                 }
507                 // Populate the key and value fields
508                 // Rule Attribute added as key
509                 if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) {
510                         // Get from Attribute Designator
511                         ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue();
512                         List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
513                         AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
514                         ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
515
516                         // Get from Attribute Value
517                         AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue();
518                         String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
519                         ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
520                 }
521                 // Rule Attribute added as value
522                 else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) {
523                         AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue();
524                         String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
525                         ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
526
527                         ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
528                         List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
529                         AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
530                         ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
531                 }
532                 ruleAlgorithmList.add(ruleMap);
533         }
534
535 }