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