Consolidate PolicyRestAdapter setup
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / CreateFirewallController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017, 2019 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.onap.policy.controller;
22
23 import com.fasterxml.jackson.core.JsonGenerationException;
24 import com.fasterxml.jackson.databind.DeserializationFeature;
25 import com.fasterxml.jackson.databind.JsonMappingException;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.LinkedHashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
45 import org.apache.commons.lang3.StringUtils;
46 import org.hibernate.SessionFactory;
47 import org.json.JSONObject;
48 import org.onap.policy.common.logging.flexlogger.FlexLogger;
49 import org.onap.policy.common.logging.flexlogger.Logger;
50 import org.onap.policy.rest.adapter.AddressGroupJson;
51 import org.onap.policy.rest.adapter.AddressJson;
52 import org.onap.policy.rest.adapter.AddressMembers;
53 import org.onap.policy.rest.adapter.AddressMembersJson;
54 import org.onap.policy.rest.adapter.DeployNowJson;
55 import org.onap.policy.rest.adapter.IdMap;
56 import org.onap.policy.rest.adapter.PolicyRestAdapter;
57 import org.onap.policy.rest.adapter.PrefixIPList;
58 import org.onap.policy.rest.adapter.ServiceGroupJson;
59 import org.onap.policy.rest.adapter.ServiceListJson;
60 import org.onap.policy.rest.adapter.ServiceMembers;
61 import org.onap.policy.rest.adapter.ServicesJson;
62 import org.onap.policy.rest.adapter.TagDefines;
63 import org.onap.policy.rest.adapter.Tags;
64 import org.onap.policy.rest.adapter.Term;
65 import org.onap.policy.rest.adapter.TermCollector;
66 import org.onap.policy.rest.adapter.VendorSpecificData;
67 import org.onap.policy.rest.dao.CommonClassDao;
68 import org.onap.policy.rest.jpa.AddressGroup;
69 import org.onap.policy.rest.jpa.FWTagPicker;
70 import org.onap.policy.rest.jpa.GroupServiceList;
71 import org.onap.policy.rest.jpa.PolicyEntity;
72 import org.onap.policy.rest.jpa.PrefixList;
73 import org.onap.policy.rest.jpa.SecurityZone;
74 import org.onap.policy.rest.jpa.ServiceList;
75 import org.onap.policy.rest.jpa.TermList;
76 import org.onap.policy.utils.PolicyUtils;
77 import org.onap.policy.xacml.api.XACMLErrorConstants;
78 import org.onap.portalsdk.core.controller.RestrictedBaseController;
79 import org.springframework.beans.factory.annotation.Autowired;
80 import org.springframework.stereotype.Controller;
81 import org.springframework.web.bind.annotation.RequestMapping;
82 import org.springframework.web.servlet.ModelAndView;
83
84 @Controller
85 @RequestMapping("/")
86 public class CreateFirewallController extends RestrictedBaseController {
87     private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class);
88     private static final String ANY = "ANY";
89     private static final String GROUP = "Group_";
90     private static CommonClassDao commonClassDao;
91     private List<String> tagCollectorList;
92     private List<String> termCollectorList;
93
94     List<String> expandablePrefixIpList = new ArrayList<>();
95     List<String> expandableServicesList = new ArrayList<>();
96
97     @Autowired
98     SessionFactory sessionFactory;
99
100     public CreateFirewallController() {
101         // Empty constructor
102     }
103
104     public static CommonClassDao getCommonClassDao() {
105         return commonClassDao;
106     }
107
108     public static void setCommonClassDao(CommonClassDao commonClassDao) {
109         CreateFirewallController.commonClassDao = commonClassDao;
110     }
111
112     @Autowired
113     private CreateFirewallController(CommonClassDao commonClassDao) {
114         CreateFirewallController.commonClassDao = commonClassDao;
115     }
116
117     /**
118      * setDataToPolicyRestAdapter.
119      *
120      * @param policyData PolicyRestAdapter
121      * @return PolicyRestAdapter
122      */
123     public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData) {
124         termCollectorList = new ArrayList<>();
125         tagCollectorList = new ArrayList<>();
126         if (!policyData.getAttributes().isEmpty()) {
127             for (Object attribute : policyData.getAttributes()) {
128                 if (attribute instanceof LinkedHashMap<?, ?>) {
129                     String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
130                     termCollectorList.add(key);
131
132                     String tag = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
133                     tagCollectorList.add(tag);
134                 }
135             }
136         }
137         String jsonBody = constructJson(policyData);
138         if (StringUtils.isBlank(jsonBody)) {
139             policyData.setJsonBody(jsonBody);
140         } else {
141             policyData.setJsonBody("{}");
142         }
143         //
144         // Hmmm - seems to be overriding the previous if statement
145         //
146         policyData.setJsonBody(jsonBody);
147
148         return policyData;
149     }
150
151     private List<String> mapping(String expandableList) {
152         String value;
153         String desc;
154         List<String> valueDesc = new ArrayList<>();
155         List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
156         for (int i = 0; i < prefixListData.size(); i++) {
157             PrefixList prefixList = (PrefixList) prefixListData.get(i);
158             if (prefixList.getPrefixListName().equals(expandableList)) {
159                 value = prefixList.getPrefixListValue();
160                 valueDesc.add(value);
161                 desc = prefixList.getDescription();
162                 valueDesc.add(desc);
163                 break;
164             }
165         }
166         return valueDesc;
167     }
168
169     private ServiceList mappingServiceList(String expandableList) {
170         ServiceList serviceList = null;
171         List<Object> serviceListData = commonClassDao.getData(ServiceList.class);
172         for (int i = 0; i < serviceListData.size(); i++) {
173             serviceList = (ServiceList) serviceListData.get(i);
174             if (serviceList.getServiceName().equals(expandableList)) {
175                 break;
176             }
177         }
178         return serviceList;
179     }
180
181     private GroupServiceList mappingServiceGroup(String expandableList) {
182
183         GroupServiceList serviceGroup = null;
184         List<Object> serviceGroupData = commonClassDao.getData(GroupServiceList.class);
185         for (int i = 0; i < serviceGroupData.size(); i++) {
186             serviceGroup = (GroupServiceList) serviceGroupData.get(i);
187             if (serviceGroup.getGroupName().equals(expandableList)) {
188                 break;
189             }
190         }
191         return serviceGroup;
192     }
193
194     private AddressGroup mappingAddressGroup(String expandableList) {
195
196         AddressGroup addressGroup = null;
197         List<Object> addressGroupData = commonClassDao.getData(AddressGroup.class);
198         for (int i = 0; i < addressGroupData.size(); i++) {
199             addressGroup = (AddressGroup) addressGroupData.get(i);
200             if (addressGroup.getGroupName().equals(expandableList)) {
201                 break;
202             }
203         }
204         return addressGroup;
205     }
206
207     public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
208         ArrayList<Object> attributeList;
209         attributeList = new ArrayList<>();
210         if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
211             return;
212         }
213         Object policyData = policyAdapter.getPolicyData();
214         PolicyType policy = (PolicyType) policyData;
215         // policy name value is the policy name without any prefix and Extensions.
216         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
217         String policyNameValue =
218                 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") + 3);
219         if (policyLogger.isDebugEnabled()) {
220             policyLogger
221                     .debug("Prepopulating form data for Config Policy selected:" + policyAdapter.getPolicyName());
222         }
223         policyAdapter.setPolicyName(policyNameValue);
224         String description = "";
225         try {
226             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
227         } catch (Exception e) {
228             policyLogger.info("General error", e);
229             description = policy.getDescription();
230         }
231         policyAdapter.setPolicyDescription(description);
232
233         ObjectMapper mapper = new ObjectMapper();
234
235         TermCollector tc1 = null;
236         try {
237             // Json conversion.
238             String data;
239             SecurityZone jpaSecurityZone;
240             data = entity.getConfigurationData().getConfigBody();
241             tc1 = mapper.readValue(data, TermCollector.class);
242             List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
243             for (int i = 0; i < securityZoneData.size(); i++) {
244                 jpaSecurityZone = (SecurityZone) securityZoneData.get(i);
245                 if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())) {
246                     policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName());
247                     break;
248                 }
249             }
250         } catch (Exception e) {
251             policyLogger.error("Exception Caused while Retriving the JSON body data" + e);
252         }
253
254         Map<String, String> termTagMap;
255         if (tc1 != null) {
256             for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) {
257                 termTagMap = new HashMap<>();
258                 String ruleName = tc1.getFirewallRuleList().get(i).getRuleName();
259                 String tagPickerName = tc1.getRuleToTag().get(i).getTagPickerName();
260                 termTagMap.put("key", ruleName);
261                 termTagMap.put("value", tagPickerName);
262                 attributeList.add(termTagMap);
263             }
264         }
265         policyAdapter.setAttributes(attributeList);
266         // Get the target data under policy.
267         TargetType target = policy.getTarget();
268         if (target == null) {
269             return;
270         }
271         // Under target we have AnyOFType
272         // NOTE: target.getAnyOf() will never be null
273         for (AnyOfType anyOf : target.getAnyOf()) {
274             for (AllOfType allOf : anyOf.getAllOf()) {
275                 for (MatchType match : allOf.getMatch()) {
276                     //
277                     // Under the match we have attribute value and
278                     // attributeDesignator. So,finally down to the actual attribute.
279                     //
280                     policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
281                             (String) match.getAttributeValue().getContent().get(0));
282                 }
283             }
284         }
285     }
286
287     /**
288      * setFWViewRule.
289      *
290      * @param request HttpServletRequest
291      * @param response HttpServletResponse
292      * @return ModelAndView
293      */
294     @RequestMapping(
295             value = {"/policyController/ViewFWPolicyRule.htm"},
296             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
297     public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response) {
298         try {
299             termCollectorList = new ArrayList<>();
300             ObjectMapper mapper = new ObjectMapper();
301             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
302             JsonNode root = mapper.readTree(request.getReader());
303             PolicyRestAdapter policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
304             if (!policyData.getAttributes().isEmpty()) {
305                 for (Object attribute : policyData.getAttributes()) {
306                     if (attribute instanceof LinkedHashMap<?, ?>) {
307                         String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
308                         termCollectorList.add(key);
309                     }
310                 }
311             }
312             TermList jpaTermList;
313             String ruleSrcList;
314             String ruleDestList;
315             String ruleSrcPort;
316             String ruleDestPort;
317             String ruleAction;
318             List<String> valueDesc;
319             StringBuilder displayString = new StringBuilder();
320             for (String id : termCollectorList) {
321                 List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
322                 jpaTermList = (TermList) tmList.get(0);
323                 if (jpaTermList != null) {
324                     ruleSrcList = jpaTermList.getSrcIPList();
325                     if ((ruleSrcList != null) && (!ruleSrcList.isEmpty()) && !"null".equals(ruleSrcList)) {
326                         displayString.append("Source IP List: " + jpaTermList.getSrcIPList());
327                         displayString.append(" ; \t\n");
328                         for (String srcList : ruleSrcList.split(",")) {
329                             if (srcList.startsWith(GROUP)) {
330                                 AddressGroup ag;
331                                 ag = mappingAddressGroup(srcList);
332                                 displayString.append(
333                                         "\n\t" + "Group has  :" + (ag != null ? ag.getPrefixList() : "") + "\n");
334                                 if (ag != null) {
335                                     for (String groupItems : ag.getPrefixList().split(",")) {
336                                         valueDesc = mapping(groupItems);
337                                         displayString.append("\n\t" + "Name: " + groupItems);
338                                         if (!valueDesc.isEmpty()) {
339                                             displayString.append("\n\t" + "Description: " + valueDesc.get(1));
340                                             displayString.append("\n\t" + "Value: " + valueDesc.get(0));
341                                         }
342                                         displayString.append("\n");
343                                     }
344                                 }
345                             } else {
346                                 if (!srcList.equals(ANY)) {
347                                     valueDesc = mapping(srcList);
348                                     displayString.append("\n\t" + "Name: " + srcList);
349                                     displayString.append("\n\t" + "Description: " + valueDesc.get(1));
350                                     displayString.append("\n\t" + "Value: " + valueDesc.get(0));
351                                     displayString.append("\n");
352                                 }
353                             }
354                         }
355                         displayString.append("\n");
356                     }
357                     ruleDestList = jpaTermList.getDestIPList();
358                     if (ruleDestList != null && (!ruleDestList.isEmpty()) && !"null".equals(ruleDestList)) {
359                         displayString.append("Destination IP List: " + jpaTermList.getDestIPList());
360                         displayString.append(" ; \t\n");
361                         for (String destList : ruleDestList.split(",")) {
362                             if (destList.startsWith(GROUP)) {
363                                 AddressGroup ag;
364                                 ag = mappingAddressGroup(destList);
365                                 displayString.append(
366                                         "\n\t" + "Group has  :" + (ag != null ? ag.getPrefixList() : "") + "\n");
367                                 if (ag != null) {
368                                     for (String groupItems : ag.getPrefixList().split(",")) {
369                                         valueDesc = mapping(groupItems);
370                                         displayString.append("\n\t" + "Name: " + groupItems);
371                                         displayString.append("\n\t" + "Description: " + valueDesc.get(1));
372                                         displayString.append("\n\t" + "Value: " + valueDesc.get(0));
373                                         displayString.append("\n\t");
374                                     }
375                                 }
376                             } else {
377                                 if (!destList.equals(ANY)) {
378                                     valueDesc = mapping(destList);
379                                     displayString.append("\n\t" + "Name: " + destList);
380                                     displayString.append("\n\t" + "Description: " + valueDesc.get(1));
381                                     displayString.append("\n\t" + "Value: " + valueDesc.get(0));
382                                     displayString.append("\n\t");
383                                 }
384                             }
385                         }
386                         displayString.append("\n");
387                     }
388
389                     ruleSrcPort = jpaTermList.getSrcPortList();
390                     if (ruleSrcPort != null && (!ruleSrcPort.isEmpty()) && !"null".equals(ruleSrcPort)) {
391                         displayString.append("\n" + "Source Port List:" + ruleSrcPort);
392                         displayString.append(" ; \t\n");
393                     }
394
395                     ruleDestPort = jpaTermList.getDestPortList();
396                     if (ruleDestPort != null && (!ruleDestPort.isEmpty()) && !"null".equals(ruleDestPort)) {
397                         displayString.append("\n" + "Destination Port List:" + ruleDestPort);
398                         displayString.append(" ; \t\n");
399                         for (String destServices : ruleDestPort.split(",")) {
400                             if (destServices.startsWith(GROUP)) {
401                                 GroupServiceList sg;
402                                 sg = mappingServiceGroup(destServices);
403                                 displayString.append("\n\t" + "Service Group has  :"
404                                         + (sg != null ? sg.getServiceList() : "") + "\n");
405                                 if (sg != null) {
406                                     for (String groupItems : sg.getServiceList().split(",")) {
407                                         ServiceList sl;
408                                         sl = mappingServiceList(groupItems);
409                                         displayString.append("\n\t" + "Name:  " + sl.getServiceName());
410                                         displayString.append("\n\t" + "Description:  " + sl.getServiceDescription());
411                                         displayString.append(
412                                                 "\n\t" + "Transport-Protocol:  " + sl.getServiceTransProtocol());
413                                         displayString.append("\n\t" + "Ports:  " + sl.getServicePorts());
414                                         displayString.append("\n");
415                                     }
416                                 }
417                             } else {
418                                 if (!destServices.equals(ANY)) {
419                                     ServiceList sl;
420                                     sl = mappingServiceList(destServices);
421                                     displayString.append("\n\t" + "Name:  " + sl.getServiceName());
422                                     displayString.append("\n\t" + "Description:  " + sl.getServiceDescription());
423                                     displayString
424                                             .append("\n\t" + "Transport-Protocol:  " + sl.getServiceTransProtocol());
425                                     displayString.append("\n\t" + "Ports:  " + sl.getServicePorts());
426                                     displayString.append("\n");
427                                 }
428                             }
429                         }
430                         displayString.append("\n");
431                     }
432
433                     ruleAction = (jpaTermList).getAction();
434                     if (ruleAction != null && (!ruleAction.isEmpty())) {
435                         displayString.append("\n" + "Action List:" + ruleAction);
436                         displayString.append(" ; \t\n");
437                     }
438                 }
439             }
440             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
441             response.setContentType(PolicyUtils.APPLICATION_JSON);
442             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
443
444             String responseString = mapper.writeValueAsString(displayString);
445             response.getWriter().write(new JSONObject("{policyData: " + responseString + "}").toString());
446             return null;
447         } catch (Exception e) {
448             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
449         }
450         return null;
451     }
452
453     private String constructJson(PolicyRestAdapter policyData) {
454         int ruleCount = 1;
455         // Maps to assosciate the values read from the TermList dictionary
456         Map<Integer, String> mapSrcIp = null;
457         Map<Integer, String> mapDestIP = null;
458         Map<Integer, String> mapSrcPort = null;
459         Map<Integer, String> mapDestPort = null;
460         Map<Integer, String> mapAction = null;
461         Map<Integer, String> mapFromZone = null;
462         Map<Integer, String> mapToZone = null;
463
464         String ruleDesc = null;
465         String ruleFromZone = null;
466         String ruleToZone = null;
467         String ruleSrcPrefixList = null;
468         String ruleDestPrefixList = null;
469         String ruleSrcPort = null;
470         String ruleDestPort = null;
471         String ruleAction = null;
472
473         String json = null;
474
475         List<String> expandableList = new ArrayList<>();
476         TermList jpaTermList;
477         TermCollector tc = new TermCollector();
478         SecurityZone jpaSecurityZone;
479         List<Term> termList = new ArrayList<>();
480
481         Tags tags = null;
482         List<Tags> tagsList = new ArrayList<>();
483
484         TagDefines tagDefine = new TagDefines();
485         List<TagDefines> tagList = null;
486         ServiceListJson targetSl = null;
487         AddressMembers addressMembersJson = null;
488         int intCounter = 0;
489         try {
490             String networkRole = "";
491             for (String tag : tagCollectorList) {
492                 tags = new Tags();
493                 List<Object> tagListData = commonClassDao.getData(FWTagPicker.class);
494                 for (int tagCounter = 0; tagCounter < tagListData.size(); tagCounter++) {
495                     FWTagPicker jpaTagPickerList = (FWTagPicker) tagListData.get(tagCounter);
496                     if (jpaTagPickerList.getTagPickerName().equals(tag)) {
497                         String tagValues = jpaTagPickerList.getTagValues();
498                         tagList = new ArrayList<>();
499                         for (String val : tagValues.split("#")) {
500                             int index = val.indexOf(':');
501                             String keyToStore = val.substring(0, index);
502                             String valueToStore = val.substring(index + 1, val.length());
503
504                             tagDefine = new TagDefines();
505                             tagDefine.setKey(keyToStore);
506                             tagDefine.setValue(valueToStore);
507                             // Add to the collection.
508                             tagList.add(tagDefine);
509
510                         }
511                         networkRole = jpaTagPickerList.getNetworkRole();
512                         break;
513                     }
514                 }
515                 tags.setTags(tagList);
516                 tags.setTagPickerName(tag);
517                 tags.setRuleName(termCollectorList.get(intCounter));
518                 tags.setNetworkRole(networkRole);
519                 tagsList.add(tags);
520                 intCounter++;
521             }
522             tc.setRuleToTag(tagsList);
523
524             for (int tl = 0; tl < termCollectorList.size(); tl++) {
525                 expandableList.add(termCollectorList.get(tl));
526                 Term targetTerm = new Term();
527                 targetTerm.setRuleName(termCollectorList.get(tl));
528                 List<Object> termListData = commonClassDao.getData(TermList.class);
529                 for (int j = 0; j < termListData.size(); j++) {
530                     jpaTermList = (TermList) termListData.get(j);
531                     if (jpaTermList.getTermName().equals(termCollectorList.get(tl))) {
532                         ruleDesc = jpaTermList.getTermDescription();
533                         if ((ruleDesc != null) && (!ruleDesc.isEmpty())) {
534                             targetTerm.setDescription(ruleDesc);
535                         }
536                         ruleFromZone = jpaTermList.getFromZone();
537
538                         if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())) {
539                             mapFromZone = new HashMap<>();
540                             mapFromZone.put(tl, ruleFromZone);
541                         }
542                         ruleToZone = jpaTermList.getToZone();
543
544                         if ((ruleToZone != null) && (!ruleToZone.isEmpty())) {
545                             mapToZone = new HashMap<>();
546                             mapToZone.put(tl, ruleToZone);
547                         }
548                         ruleSrcPrefixList = jpaTermList.getSrcIPList();
549
550                         if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())) {
551                             mapSrcIp = new HashMap<>();
552                             mapSrcIp.put(tl, ruleSrcPrefixList);
553                         }
554
555                         ruleDestPrefixList = jpaTermList.getDestIPList();
556                         if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())) {
557                             mapDestIP = new HashMap<>();
558                             mapDestIP.put(tl, ruleDestPrefixList);
559                         }
560
561                         ruleSrcPort = jpaTermList.getSrcPortList();
562
563                         if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())) {
564                             mapSrcPort = new HashMap<>();
565                             mapSrcPort.put(tl, ruleSrcPort);
566                         }
567
568                         ruleDestPort = jpaTermList.getDestPortList();
569
570                         if (ruleDestPort != null && (!jpaTermList.getDestPortList().isEmpty())) {
571                             mapDestPort = new HashMap<>();
572                             mapDestPort.put(tl, ruleDestPort);
573                         }
574
575                         ruleAction = jpaTermList.getAction();
576
577                         if ((ruleAction != null) && (!ruleAction.isEmpty())) {
578                             mapAction = new HashMap<>();
579                             mapAction.put(tl, ruleAction);
580                         }
581                     }
582                 }
583                 targetTerm.setEnabled(true);
584                 targetTerm.setLog(true);
585                 targetTerm.setNegateSource(false);
586                 targetTerm.setNegateDestination(false);
587
588                 if (mapAction != null) {
589                     targetTerm.setAction(mapAction.get(tl));
590                 }
591
592                 // FromZone arrays
593                 if (mapFromZone != null) {
594                     List<String> fromZone = new ArrayList<>();
595                     for (String fromZoneStr : mapFromZone.get(tl).split(",")) {
596                         fromZone.add(fromZoneStr);
597                     }
598                     targetTerm.setFromZones(fromZone);
599                 }
600
601                 // ToZone arrays
602                 if (mapToZone != null) {
603                     List<String> toZone = new ArrayList<>();
604                     for (String toZoneStr : mapToZone.get(tl).split(",")) {
605                         toZone.add(toZoneStr);
606                     }
607                     targetTerm.setToZones(toZone);
608                 }
609
610                 // Destination Services.
611                 if (mapDestPort != null) {
612                     Set<ServicesJson> destServicesJsonList = new HashSet<>();
613                     for (String destServices : mapDestPort.get(tl).split(",")) {
614                         ServicesJson destServicesJson = new ServicesJson();
615                         destServicesJson.setType("REFERENCE");
616                         if (destServices.equals(ANY)) {
617                             destServicesJson.setName("any");
618                             destServicesJsonList.add(destServicesJson);
619                             break;
620                         } else {
621                             if (destServices.startsWith(GROUP)) {
622                                 destServicesJson.setName(destServices.substring(6, destServices.length()));
623                             } else {
624                                 destServicesJson.setName(destServices);
625                             }
626                             destServicesJsonList.add(destServicesJson);
627                         }
628                     }
629                     targetTerm.setDestServices(destServicesJsonList);
630                 }
631                 // ExpandableServicesList
632                 if ((mapSrcPort != null) && (mapDestPort != null)) {
633                     String servicesCollateString = mapSrcPort.get(tl) + "," + mapDestPort.get(tl);
634                     expandableServicesList.add(servicesCollateString);
635                 } else if (mapSrcPort != null) {
636                     expandableServicesList.add(mapSrcPort.get(tl));
637                 } else if (mapDestPort != null) {
638                     expandableServicesList.add(mapDestPort.get(tl));
639                 }
640
641                 if (mapSrcIp != null) {
642                     // Source List
643                     List<AddressJson> sourceListArrayJson = new ArrayList<>();
644                     for (String srcList : mapSrcIp.get(tl).split(",")) {
645                         AddressJson srcListJson = new AddressJson();
646                         if (srcList.equals(ANY)) {
647                             srcListJson.setType("any");
648                             sourceListArrayJson.add(srcListJson);
649                             break;
650                         } else {
651                             srcListJson.setType("REFERENCE");
652                             if (srcList.startsWith(GROUP)) {
653                                 srcListJson.setName(srcList.substring(6, srcList.length()));
654                             } else {
655                                 srcListJson.setName(srcList);
656                             }
657                             sourceListArrayJson.add(srcListJson);
658                         }
659                     }
660                     targetTerm.setSourceList(sourceListArrayJson);
661                 }
662                 if (mapDestIP != null) {
663                     // Destination List
664                     List<AddressJson> destListArrayJson = new ArrayList<>();
665                     for (String destList : mapDestIP.get(tl).split(",")) {
666                         AddressJson destListJson = new AddressJson();
667                         if (destList.equals(ANY)) {
668                             destListJson.setType("any");
669                             destListArrayJson.add(destListJson);
670                             break;
671                         } else {
672                             destListJson.setType("REFERENCE");
673                             if (destList.startsWith(GROUP)) {
674                                 destListJson.setName(destList.substring(6, destList.length()));
675                             } else {
676                                 destListJson.setName(destList);
677                             }
678                             destListArrayJson.add(destListJson);
679                         }
680                     }
681                     targetTerm.setDestinationList(destListArrayJson);
682                 }
683                 // ExpandablePrefixIPList
684                 if ((mapSrcIp != null) && (mapDestIP != null)) {
685                     String collateString = mapSrcIp.get(tl) + "," + mapDestIP.get(tl);
686                     expandablePrefixIpList.add(collateString);
687                 } else if (mapSrcIp != null) {
688                     expandablePrefixIpList.add(mapSrcIp.get(tl));
689                 } else if (mapDestIP != null) {
690                     expandablePrefixIpList.add(mapDestIP.get(tl));
691                 }
692                 termList.add(targetTerm);
693                 targetTerm.setPosition(Integer.toString(ruleCount++));
694             }
695
696             List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
697             for (int j = 0; j < securityZoneData.size(); j++) {
698                 jpaSecurityZone = (SecurityZone) securityZoneData.get(j);
699                 if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())) {
700                     tc.setSecurityZoneId(jpaSecurityZone.getZoneValue());
701                     IdMap idMapInstance = new IdMap();
702                     idMapInstance.setAstraId(jpaSecurityZone.getZoneValue());
703                     idMapInstance.setVendorId("deviceGroup:dev");
704
705                     List<IdMap> idMap = new ArrayList<>();
706                     idMap.add(idMapInstance);
707
708                     VendorSpecificData vendorStructure = new VendorSpecificData();
709                     vendorStructure.setIdMap(idMap);
710                     tc.setVendorSpecificData(vendorStructure);
711                     break;
712                 }
713             }
714
715             tc.setServiceTypeId("/v0/firewall/pan");
716             tc.setConfigName(policyData.getConfigName());
717             tc.setVendorServiceId("vipr");
718
719             DeployNowJson deployNow = new DeployNowJson();
720             deployNow.setDeployNow(false);
721
722             tc.setDeploymentOption(deployNow);
723
724             Set<ServiceListJson> servListArray = new HashSet<>();
725             Set<ServiceGroupJson> servGroupArray = new HashSet<>();
726             Set<AddressGroupJson> addrGroupArray = new HashSet<>();
727             Set<AddressMembers> addrArray = new HashSet<>();
728
729             ServiceGroupJson targetSg;
730             AddressGroupJson addressSg;
731             ServiceListJson targetAny;
732             ServiceListJson targetAnyTcp;
733             ServiceListJson targetAnyUdp;
734
735             for (String serviceList : expandableServicesList) {
736                 for (String t : serviceList.split(",")) {
737                     if (!t.startsWith(GROUP)) {
738                         if (!t.equals(ANY)) {
739                             ServiceList sl;
740                             targetSl = new ServiceListJson();
741                             sl = mappingServiceList(t);
742                             targetSl.setName(sl.getServiceName());
743                             targetSl.setDescription(sl.getServiceDescription());
744                             targetSl.setTransportProtocol(sl.getServiceTransProtocol());
745                             targetSl.setType(sl.getServiceType());
746                             targetSl.setPorts(sl.getServicePorts());
747                             servListArray.add(targetSl);
748                         } else {
749                             // Any for destinationServices.
750                             // Add names any, any-tcp, any-udp to the serviceGroup object.
751                             targetAny = new ServiceListJson();
752                             targetAny.setName("any");
753                             targetAny.setType("SERVICE");
754                             targetAny.setTransportProtocol("any");
755                             targetAny.setPorts("any");
756
757                             servListArray.add(targetAny);
758
759                             targetAnyTcp = new ServiceListJson();
760                             targetAnyTcp.setName("any-tcp");
761                             targetAnyTcp.setType("SERVICE");
762                             targetAnyTcp.setTransportProtocol("tcp");
763                             targetAnyTcp.setPorts("any");
764
765                             servListArray.add(targetAnyTcp);
766
767                             targetAnyUdp = new ServiceListJson();
768                             targetAnyUdp.setName("any-udp");
769                             targetAnyUdp.setType("SERVICE");
770                             targetAnyUdp.setTransportProtocol("udp");
771                             targetAnyUdp.setPorts("any");
772
773                             servListArray.add(targetAnyUdp);
774                         }
775                     } else { // This is a group
776                         GroupServiceList sg;
777                         targetSg = new ServiceGroupJson();
778                         sg = mappingServiceGroup(t);
779
780                         String name = sg.getGroupName();
781                         // Removing the "Group_" prepending string before packing the JSON
782                         targetSg.setName(name.substring(6, name.length()));
783                         List<ServiceMembers> servMembersList = new ArrayList<>();
784
785                         for (String groupString : sg.getServiceList().split(",")) {
786                             ServiceMembers serviceMembers = new ServiceMembers();
787                             serviceMembers.setType("REFERENCE");
788                             serviceMembers.setName(groupString);
789                             servMembersList.add(serviceMembers);
790                             // Expand the group Name
791                             ServiceList expandGroupSl;
792                             targetSl = new ServiceListJson();
793                             expandGroupSl = mappingServiceList(groupString);
794
795                             targetSl.setName(expandGroupSl.getServiceName());
796                             targetSl.setDescription(expandGroupSl.getServiceDescription());
797                             targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol());
798                             targetSl.setType(expandGroupSl.getServiceType());
799                             targetSl.setPorts(expandGroupSl.getServicePorts());
800                             servListArray.add(targetSl);
801                         }
802
803                         targetSg.setMembers(servMembersList);
804                         servGroupArray.add(targetSg);
805
806                     }
807                 }
808             }
809
810             Set<PrefixIPList> prefixIpList = new HashSet<>();
811             for (String prefixList : expandablePrefixIpList) {
812                 for (String prefixIP : prefixList.split(",")) {
813                     if (!prefixIP.startsWith(GROUP)) {
814                         if (!prefixIP.equals(ANY)) {
815                             List<String> valueDesc;
816                             PrefixIPList targetAddressList = new PrefixIPList();
817                             targetAddressList.setName(prefixIP);
818                             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:" + prefixIP);
819                             valueDesc = mapping(prefixIP);
820                             if (!valueDesc.isEmpty()) {
821                                 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"
822                                         + valueDesc.get(1));
823                                 targetAddressList.setDescription(valueDesc.get(1));
824                             }
825                             AddressMembers addressMembers = new AddressMembers();
826                             addressMembers.setType("SUBNET");
827                             if (!valueDesc.isEmpty()) {
828                                 addressMembers.setValue(valueDesc.get(0));
829                             }
830                             List<AddressMembers> addMembersList = new ArrayList<>();
831                             addMembersList.add(addressMembers);
832
833                             targetAddressList.setMembers(addMembersList);
834                             prefixIpList.add(targetAddressList);
835                         }
836                     } else { // This is a group
837                         AddressGroup ag;
838                         addressSg = new AddressGroupJson();
839                         ag = mappingAddressGroup(prefixIP);
840
841                         String name = ag.getGroupName();
842                         // Removing the "Group_" prepending string before packing the JSON
843                         addressSg.setName(name.substring(6, name.length()));
844
845                         List<AddressMembersJson> addrMembersList = new ArrayList<>();
846                         for (String groupString : ag.getPrefixList().split(",")) {
847                             AddressMembersJson addressMembers = new AddressMembersJson();
848                             addressMembers.setType("REFERENCES");
849                             addressMembers.setName(groupString);
850                             addrMembersList.add(addressMembers);
851                             // Expand the group Name
852                             addressMembersJson = new AddressMembers();
853                             List<String> valueDesc = mapping(groupString);
854
855                             addressMembersJson.setName(groupString);
856                             addressMembersJson.setType("SUBNET");
857                             addressMembersJson.setValue(valueDesc.get(0));
858
859                             addrArray.add(addressMembersJson);
860
861                         }
862                         addressSg.setMembers(addrMembersList);
863                         addrGroupArray.add(addressSg);
864                     }
865
866                 }
867             }
868
869             Set<Object> serviceGroup = new HashSet<>();
870
871             for (Object obj1 : servGroupArray) {
872                 serviceGroup.add(obj1);
873             }
874
875             for (Object obj : servListArray) {
876                 serviceGroup.add(obj);
877             }
878
879             Set<Object> addressGroup = new HashSet<>();
880
881             for (Object addObj : prefixIpList) {
882                 addressGroup.add(addObj);
883             }
884
885             for (Object addObj1 : addrGroupArray) {
886                 addressGroup.add(addObj1);
887             }
888
889             for (Object addObj2 : addrArray) {
890                 addressGroup.add(addObj2);
891             }
892
893             tc.setServiceGroups(serviceGroup);
894             tc.setAddressGroups(addressGroup);
895             tc.setFirewallRuleList(termList);
896
897             try {
898                 json = new ObjectMapper().writer().writeValueAsString(tc);
899             } catch (JsonGenerationException e) {
900                 policyLogger.error("JsonGenerationException Ocured", e);
901             } catch (JsonMappingException e) {
902                 policyLogger.error("IOException Occured", e);
903             }
904
905         } catch (Exception e) {
906             policyLogger.error("Exception Occured" + e);
907         }
908
909         return json;
910     }
911
912 }