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