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