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