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