Policy 1707 commit to LF
[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
23
24 import java.io.IOException;
25 import java.io.PrintWriter;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
37
38 import org.hibernate.SessionFactory;
39 import org.json.JSONObject;
40 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
41 import org.openecomp.policy.common.logging.flexlogger.Logger;
42 import org.openecomp.policy.rest.adapter.AddressGroupJson;
43 import org.openecomp.policy.rest.adapter.AddressJson;
44 import org.openecomp.policy.rest.adapter.AddressMembers;
45 import org.openecomp.policy.rest.adapter.DeployNowJson;
46 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
47 import org.openecomp.policy.rest.adapter.PrefixIPList;
48 import org.openecomp.policy.rest.adapter.ServiceGroupJson;
49 import org.openecomp.policy.rest.adapter.ServiceListJson;
50 import org.openecomp.policy.rest.adapter.ServiceMembers;
51 import org.openecomp.policy.rest.adapter.ServicesJson;
52 import org.openecomp.policy.rest.adapter.TagDefines;
53 import org.openecomp.policy.rest.adapter.Tags;
54 import org.openecomp.policy.rest.adapter.Term;
55 import org.openecomp.policy.rest.adapter.TermCollector;
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.AttributeValueType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
85
86 @Controller
87 @RequestMapping("/")
88 public class CreateFirewallController extends RestrictedBaseController {
89         private static Logger logger    = FlexLogger.getLogger(CreateFirewallController.class);
90
91         @Autowired
92         SessionFactory sessionFactory;
93         
94         private static CommonClassDao commonClassDao;
95
96         private List<String> tagCollectorList;
97         private String jsonBody;
98         List<String> expandablePrefixIPList = new ArrayList<String>();
99         List<String> expandableServicesList= new ArrayList<String>();
100         @Autowired
101         private CreateFirewallController(CommonClassDao commonClassDao){
102                 CreateFirewallController.commonClassDao = commonClassDao;
103         }
104
105         public CreateFirewallController(){}
106         private List<String> termCollectorList;
107         private ArrayList<Object> attributeList;
108
109
110         public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){
111                 
112                 termCollectorList = new ArrayList<String>();
113                 tagCollectorList = new ArrayList<String>();
114                 if(policyData.getAttributes().size() > 0){
115                         for(Object attribute : policyData.getAttributes()){
116                                 if(attribute instanceof LinkedHashMap<?, ?>){
117                                         String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
118                                         termCollectorList.add(key);
119                                         
120                                         String tag = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
121                                         tagCollectorList.add(tag);
122                                 }
123                         }
124                 }
125                 jsonBody = constructJson(policyData);   
126                 if (jsonBody != null || jsonBody.equalsIgnoreCase("")) {
127                         policyData.setJsonBody(jsonBody);
128
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<String>();
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<Object>();
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
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                         policyAdapter.setAttributes(attributeList);
246                         // Get the target data under policy.
247                         TargetType target = policy.getTarget();
248                         if (target != null) {
249                                 // Under target we have AnyOFType
250                                 List<AnyOfType> anyOfList = target.getAnyOf();
251                                 if (anyOfList != null) {
252                                         int index = 0;
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                                                                                 if (index == 1) {
276                                                                                         policyAdapter.setConfigName(value);
277                                                                                 }
278                                                                                 if (index ==  2){
279                                                                                         policyAdapter.setRiskType(value);
280                                                                                 }
281         
282                                                                                 if (index ==  3){
283                                                                                         policyAdapter.setRiskLevel(value);
284                                                                                 }
285                                                                                 
286                                                                                 if (index ==  4){
287                                                                                         policyAdapter.setGuard(value);
288                                                                                 }
289                                                                                 if (index == 5 && !value.contains("NA")){
290                                                                                         String newDate = convertDate(value, true);
291                                                                                         policyAdapter.setTtlDate(newDate);
292                                                                                 }
293                                                                                 index++;
294                                                                         }
295                                                                 }
296                                                         }
297                                                 }
298                                         }
299                                 }
300                         }
301                 }
302         }
303         
304         private String convertDate(String dateTTL, boolean portalType) {
305                 String formateDate = null;
306                 String[] date;
307                 String[] parts;
308                 
309                 if (portalType){
310                         parts = dateTTL.split("-");
311                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
312                 } else {
313                         date  = dateTTL.split("T");
314                         parts = date[0].split("-");
315                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
316                 }
317                 return formateDate;
318         }
319         
320         @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
321         public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
322                 try {
323                         termCollectorList = new ArrayList<String>();
324                         ObjectMapper mapper = new ObjectMapper();
325                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
326                         JsonNode root = mapper.readTree(request.getReader());
327                         PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
328                         if(policyData.getAttributes().size() > 0){
329                                 for(Object attribute : policyData.getAttributes()){
330                                         if(attribute instanceof LinkedHashMap<?, ?>){
331                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
332                                                 termCollectorList.add(key);
333                                         }
334                                 }
335                         }
336                         TermList jpaTermList;
337                         String ruleSrcList=null;
338                         String ruleDestList=null;
339                         String ruleSrcPort=null;
340                         String ruleDestPort=null;
341                         String ruleAction=null;
342                         List <String> valueDesc= new ArrayList<String>();
343                         StringBuffer displayString = new StringBuffer();
344                         for (String id : termCollectorList) {
345                                 List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
346                                 jpaTermList = (TermList) tmList.get(0);
347                                 if (jpaTermList != null){                               
348                                         ruleSrcList= ((TermList) jpaTermList).getSrcIPList();   
349                                         if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !ruleSrcList.equals("null")){
350                                                 displayString.append("Source IP List: " + ((TermList) jpaTermList).getSrcIPList());
351                                                 displayString.append(" ; \t\n");
352                                                 for(String srcList:ruleSrcList.split(",")){     
353                                                         if(srcList.startsWith("Group_")){
354                                                                 AddressGroup ag= new AddressGroup();
355                                                                 ag= mappingAddressGroup(srcList);
356                                                                 displayString.append("\n\t"+"Group has  :"+ag.getPrefixList()+"\n");
357                                                                 for(String groupItems:ag.getPrefixList().split(",")){
358                                                                         valueDesc=mapping(groupItems);
359                                                                         displayString.append("\n\t"+"Name: "+groupItems);
360                                                                         if(!valueDesc.isEmpty()){
361                                                                                 displayString.append("\n\t"+"Description: "+valueDesc.get(1));
362                                                                                 displayString.append("\n\t"+"Value: "+valueDesc.get(0));
363                                                                         }
364                                                                         displayString.append("\n");
365                                                                 }
366                                                         }else{
367                                                                 if(!srcList.equals("ANY")){
368                                                                         valueDesc=mapping(srcList);
369                                                                         displayString.append("\n\t"+"Name: "+srcList);
370                                                                         displayString.append("\n\t"+"Description: "+valueDesc.get(1));
371                                                                         displayString.append("\n\t"+"Value: "+valueDesc.get(0));
372                                                                         displayString.append("\n");
373                                                                 }
374                                                         }
375                                                 }
376                                                 displayString.append("\n");
377                                         } 
378                                         ruleDestList= ((TermList) jpaTermList).getDestIPList();
379                                         if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){
380                                                 displayString.append("Destination IP List: " + ((TermList) jpaTermList).getDestIPList());
381                                                 displayString.append(" ; \t\n");
382                                                 for(String destList:ruleDestList.split(",")){   
383                                                         if(destList.startsWith("Group_")){
384                                                                 AddressGroup ag= new AddressGroup();
385                                                                 ag= mappingAddressGroup(destList);
386                                                                 displayString.append("\n\t"+"Group has  :"+ag.getPrefixList()+"\n");
387                                                                 for(String groupItems:ag.getPrefixList().split(",")){
388                                                                         valueDesc=mapping(groupItems);
389                                                                         displayString.append("\n\t"+"Name: "+groupItems);
390                                                                         displayString.append("\n\t"+"Description: "+valueDesc.get(1));
391                                                                         displayString.append("\n\t"+"Value: "+valueDesc.get(0));
392                                                                         displayString.append("\n\t");
393                                                                 }
394                                                         }else{
395                                                                 if(!destList.equals("ANY")){
396                                                                         valueDesc=mapping(destList);
397                                                                         displayString.append("\n\t"+"Name: "+destList);
398                                                                         displayString.append("\n\t"+"Description: "+valueDesc.get(1));
399                                                                         displayString.append("\n\t"+"Value: "+valueDesc.get(0));
400                                                                         displayString.append("\n\t");
401                                                                 }
402                                                         }
403                                                 }
404                                                 displayString.append("\n");
405                                         } 
406
407                                         ruleSrcPort=((TermList) jpaTermList).getSrcPortList();
408                                         if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) {
409                                                 displayString.append("\n"+"Source Port List:"
410                                                                 + ruleSrcPort);
411                                                 displayString.append(" ; \t\n");
412                                         } 
413
414                                         ruleDestPort= ((TermList) jpaTermList).getDestPortList();
415                                         if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) {
416                                                 displayString.append("\n"+"Destination Port List:"
417                                                                 + ruleDestPort);
418                                                 displayString.append(" ; \t\n");
419                                                 for(String destServices:ruleDestPort.split(",")){       
420                                                         if(destServices.startsWith("Group_")){
421                                                                 GroupServiceList sg= new GroupServiceList();
422                                                                 sg= mappingServiceGroup(destServices);
423                                                                 displayString.append("\n\t"+"Service Group has  :"+sg.getServiceList()+"\n");
424                                                                 for(String groupItems:sg.getServiceList().split(",")){
425                                                                         ServiceList sl= new ServiceList();
426                                                                         sl= mappingServiceList(groupItems);
427                                                                         displayString.append("\n\t"+"Name:  "+
428                                                                                         sl.getServiceName());
429                                                                         displayString.append("\n\t"+"Description:  "+
430                                                                                         sl.getServiceDescription());    
431                                                                         displayString.append("\n\t"+"Transport-Protocol:  "+
432                                                                                         sl.getServiceTransProtocol());
433                                                                         displayString.append("\n\t"+"Ports:  "+
434                                                                                         sl.getServicePorts());
435                                                                         displayString.append("\n");
436                                                                 }
437                                                         }
438                                                         else{
439                                                                 if(!destServices.equals("ANY")){
440                                                                         ServiceList sl= new ServiceList();
441                                                                         sl= mappingServiceList(destServices);
442                                                                         displayString.append("\n\t"+"Name:  "+
443                                                                                         sl.getServiceName());
444                                                                         displayString.append("\n\t"+"Description:  "+
445                                                                                         sl.getServiceDescription());    
446                                                                         displayString.append("\n\t"+"Transport-Protocol:  "+
447                                                                                         sl.getServiceTransProtocol());
448                                                                         displayString.append("\n\t"+"Ports:  "+
449                                                                                         sl.getServicePorts());
450                                                                         displayString.append("\n");
451                                                                 }
452                                                         }
453                                                 }
454                                                 displayString.append("\n");
455                                         }
456
457                                         ruleAction=(jpaTermList).getAction();
458                                         if ( ruleAction!= null && (!ruleAction.isEmpty())) {
459                                                 displayString.append("\n"+"Action List:"
460                                                                 + ruleAction);
461                                                 displayString.append(" ; \t\n");
462                                         } 
463                                 }
464                         }
465                         response.setCharacterEncoding("UTF-8");
466                         response.setContentType("application / json");
467                         request.setCharacterEncoding("UTF-8");
468
469                         PrintWriter out = response.getWriter();
470                         String responseString = mapper.writeValueAsString(displayString);
471                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
472                         out.write(j.toString());
473                         return null;
474                 } catch (Exception e) {
475                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
476                 }
477                 return null;    
478         }
479
480         private String constructJson(PolicyRestAdapter policyData) {
481                 int ruleCount=1;
482                 //Maps to assosciate the values read from the TermList dictionary
483                 Map<Integer, String> srcIP_map =null;
484                 Map<Integer, String> destIP_map=null;
485                 Map<Integer, String> srcPort_map =null;
486                 Map<Integer, String> destPort_map =null;
487                 Map<Integer, String> action_map=null;
488                 Map<Integer, String> fromZone_map=null;
489                 Map<Integer, String> toZone_map=null;
490
491                 String ruleDesc=null;
492                 String ruleFromZone=null;
493                 String ruleToZone=null;
494                 String ruleSrcPrefixList=null;
495                 String ruleDestPrefixList=null;
496                 String ruleSrcPort=null;
497                 String ruleDestPort=null;
498                 String ruleAction=null;
499
500                 String json = null;
501
502
503                 List<String> expandableList = new ArrayList<String>();
504                 TermList jpaTermList;
505                 TermCollector tc = new TermCollector();
506                 SecurityZone jpaSecurityZone;
507                 List<Term> termList = new ArrayList<Term>();
508                 
509                 Tags tags=null;
510                 List<Tags>tagsList= new ArrayList<Tags>();
511                 
512                 TagDefines tagDefine= new TagDefines();
513                 List<TagDefines> tagList=null;
514                 ServiceListJson targetSl=null;
515                 int i=0;
516                 try{
517                         
518                         for(String tag:tagCollectorList){
519                                 tags= new Tags();
520                                 List<Object> tagListData = commonClassDao.getData(FWTagPicker.class);
521                                 for(int tagCounter=0; tagCounter<tagListData.size(); tagCounter++){
522                                         FWTagPicker jpaTagPickerList=(FWTagPicker) tagListData.get(tagCounter);
523                                         if (jpaTagPickerList.getTagPickerName().equals(tag) ){
524                                                 String tagValues=jpaTagPickerList.getTagValues();
525                                                 tagList= new ArrayList<TagDefines>();
526                                                 for(String val:tagValues.split("#")) {
527                                                         int index=val.indexOf(":");
528                                                         String keyToStore=val.substring(0,index);
529                                                         String valueToStore=val.substring(index+1,val.length());
530                                                         
531                                                         tagDefine= new TagDefines();
532                                                         tagDefine.setKey(keyToStore);
533                                                         tagDefine.setValue(valueToStore);
534                                                         //Add to the collection.
535                                                         tagList.add(tagDefine);
536                                                         
537                                                 }
538                                                 
539                                         }
540                                 }       
541                                 tags.setTags(tagList);
542                                 tags.setTagPickerName(tag);
543                                 tags.setRuleName(termCollectorList.get(i));
544                                 tagsList.add(tags);
545                                 i++;
546                         }
547                         tc.setRuleToTag(tagsList);
548
549                         for (int tl = 0 ; tl< termCollectorList.size(); tl++) {
550                                 expandableList.add(termCollectorList.get(tl));
551                                 Term targetTerm = new Term();
552                                 //targetSl= new ServiceListJson();
553                                 targetTerm.setRuleName(termCollectorList.get(tl));
554                                 List<Object> termListData = commonClassDao.getData(TermList.class);
555                                 for (int j =0; j < termListData.size(); j++) {
556                                         jpaTermList = (TermList) termListData.get(j);
557                                         if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){
558                                                 ruleDesc=jpaTermList.getTermDescription();
559                                                 if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){
560                                                         targetTerm.setDescription(ruleDesc);
561                                                 }       
562                                                 ruleFromZone=jpaTermList.getFromZone(); 
563
564                                                 if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){
565                                                         fromZone_map = new HashMap<Integer, String>();
566                                                         fromZone_map.put(tl, ruleFromZone);
567                                                 }       
568                                                 ruleToZone=jpaTermList.getToZone();
569
570                                                 if ((ruleToZone != null) && (!ruleToZone.isEmpty())){
571                                                         toZone_map = new HashMap<Integer, String>();
572                                                         toZone_map.put(tl, ruleToZone);
573                                                 } 
574                                                 ruleSrcPrefixList=jpaTermList.getSrcIPList();
575
576                                                 if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){
577                                                         srcIP_map = new HashMap<Integer, String>();
578                                                         srcIP_map.put(tl, ruleSrcPrefixList);
579                                                 } 
580
581                                                 ruleDestPrefixList= jpaTermList.getDestIPList();
582                                                 if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){
583                                                         destIP_map = new HashMap<Integer, String>();
584                                                         destIP_map.put(tl, ruleDestPrefixList);
585                                                 } 
586
587                                                 ruleSrcPort=jpaTermList.getSrcPortList();
588
589                                                 if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){
590                                                         srcPort_map = new HashMap<Integer, String>();
591                                                         srcPort_map.put(tl, ruleSrcPort);
592                                                 } 
593
594                                                 ruleDestPort= jpaTermList.getDestPortList();
595
596                                                 if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){
597                                                         destPort_map = new HashMap<Integer, String>();
598                                                         destPort_map.put(tl, ruleDestPort);
599                                                 } 
600
601                                                 ruleAction=jpaTermList.getAction();
602
603                                                 if (( ruleAction!= null) && (!ruleAction.isEmpty())){
604                                                         action_map = new HashMap<Integer, String>();
605                                                         action_map.put(tl, ruleAction);
606                                                 } 
607                                         }
608                                 }
609                                 targetTerm.setEnabled(true);
610                                 targetTerm.setLog(true);
611                                 targetTerm.setNegateSource(false);
612                                 targetTerm.setNegateDestination(false);
613
614                                 if(action_map!=null){
615                                         targetTerm.setAction(action_map.get(tl));
616                                 }
617
618                                 //FromZone arrays
619                                 if(fromZone_map!=null){
620                                         List<String> fromZone= new ArrayList<String>();
621                                         for(String fromZoneStr:fromZone_map.get(tl).split(",") ){
622                                                 fromZone.add(fromZoneStr);
623                                         }
624                                         targetTerm.setFromZones(fromZone);
625                                 }
626
627                                 //ToZone arrays
628                                 if(toZone_map!=null){
629                                         List<String> toZone= new ArrayList<String>();
630                                         for(String toZoneStr:toZone_map.get(tl).split(",") ){
631                                                 toZone.add(toZoneStr);
632                                         }
633                                         targetTerm.setToZones(toZone);
634                                 }
635
636                                 //Destination Services.
637                                 if(destPort_map!=null){
638                                         Set<ServicesJson> destServicesJsonList= new HashSet<ServicesJson>();
639                                         for(String destServices:destPort_map.get(tl).split(",") ){
640                                                 ServicesJson destServicesJson= new ServicesJson();
641                                                 destServicesJson.setType("REFERENCE");
642                                                 if(destServices.equals("ANY")){
643                                                         destServicesJson.setName("any");
644                                                         destServicesJsonList.add(destServicesJson);
645                                                         break;
646                                                 }else{
647                                                         if(destServices.startsWith("Group_")){
648                                                                 destServicesJson.setName(destServices.substring(6,destServices.length()));
649                                                         } else{
650                                                                 destServicesJson.setName(destServices);
651                                                         }
652                                                         destServicesJsonList.add(destServicesJson);
653                                                 }
654                                         }                       
655                                         targetTerm.setDestServices(destServicesJsonList);
656                                 }
657                                 //ExpandableServicesList
658                                 if((srcPort_map!=null) && (destPort_map!=null)){
659                                         String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl));
660                                         expandableServicesList.add(servicesCollateString);
661                                 }else if (srcPort_map!=null){
662                                         expandableServicesList.add(srcPort_map.get(tl));
663                                 }else if (destPort_map!=null){
664                                         expandableServicesList.add(destPort_map.get(tl));
665                                 }
666
667                                 if(srcIP_map!=null){
668                                         //Source List
669                                         List<AddressJson> sourceListArrayJson= new ArrayList<AddressJson>();                    
670                                         for(String srcList:srcIP_map.get(tl).split(",") ){
671                                                 AddressJson srcListJson= new AddressJson();
672                                                 if(srcList.equals("ANY")){
673                                                         srcListJson.setType("any");
674                                                         sourceListArrayJson.add(srcListJson);
675                                                         break;
676                                                 }else{
677                                                         srcListJson.setType("REFERENCE");
678                                                         if(srcList.startsWith("Group_")){
679                                                                 srcListJson.setName(srcList.substring(6,srcList.length()));
680                                                         }else{
681                                                                 srcListJson.setName(srcList);
682                                                         }
683                                                         sourceListArrayJson.add(srcListJson);
684                                                 }
685                                         }
686                                         targetTerm.setSourceList(sourceListArrayJson);
687                                 }
688                                 if(destIP_map!=null){
689                                         //Destination List
690                                         List<AddressJson> destListArrayJson= new ArrayList<AddressJson>();                              
691                                         for(String destList:destIP_map.get(tl).split(",")){
692                                                 AddressJson destListJson= new AddressJson();
693                                                 if(destList.equals("ANY")){
694                                                         destListJson.setType("any");
695                                                         destListArrayJson.add(destListJson);
696                                                         break;
697                                                 }else{
698                                                         destListJson.setType("REFERENCE");
699                                                         if(destList.startsWith("Group_")){
700                                                                 destListJson.setName(destList.substring(6,destList.length()));
701                                                         }else{
702                                                                 destListJson.setName(destList);
703                                                         }
704                                                         destListArrayJson.add(destListJson);
705                                                 }
706                                         }
707                                         targetTerm.setDestinationList(destListArrayJson);       
708                                 }
709                                 //ExpandablePrefixIPList
710                                 if ((srcIP_map!=null) && (destIP_map!=null)) 
711                                 {
712                                         String collateString = (srcIP_map.get(tl) + "," + destIP_map
713                                                         .get(tl));
714                                         expandablePrefixIPList.add(collateString);
715                                 }
716                                 else if(srcIP_map!=null){
717                                         expandablePrefixIPList.add(srcIP_map.get(tl));
718                                 }
719                                 else if(destIP_map!=null){
720                                         expandablePrefixIPList.add(destIP_map.get(tl));
721                                 }
722                                 termList.add(targetTerm);
723                                 targetTerm.setPosition("" + (ruleCount++));
724                         }
725                         
726                         List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
727                         for (int j =0 ; j< securityZoneData.size() ; j++){
728                                 jpaSecurityZone = (SecurityZone) securityZoneData.get(j);
729                                 if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())){
730                                         tc.setSecurityZoneId(jpaSecurityZone.getZoneValue());
731                                         //setParentSecurityZone(jpaSecurityZone.getZoneValue());//For storing the securityZone IDs to the DB
732                                         break;
733                                 }
734                         }
735
736                         tc.setServiceTypeId("/v0/firewall/pan");
737                         tc.setConfigName(policyData.getConfigName());
738                         
739                         //Astra is rejecting the packet when it sees a new JSON field, so removing it for now. 
740                         //tc.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_FW));
741
742                         DeployNowJson deployNow= new DeployNowJson();
743                         deployNow.setDeployNow(false);
744
745                         tc.setDeploymentOption(deployNow);
746
747                         Set<ServiceListJson> servListArray = new HashSet<ServiceListJson>();
748                         Set<ServiceGroupJson> servGroupArray= new HashSet<ServiceGroupJson>();
749                         Set<AddressGroupJson> addrGroupArray= new HashSet<AddressGroupJson>();
750
751                         ServiceGroupJson targetSg= null;
752                         AddressGroupJson addressSg=null;
753                         ServiceListJson targetAny= null;
754                         ServiceListJson targetAnyTcp=null;
755                         ServiceListJson targetAnyUdp=null;
756
757                         for(String serviceList:expandableServicesList){
758                                 for(String t: serviceList.split(",")){
759                                         if((!t.startsWith("Group_"))){
760                                                 if(!t.equals("ANY")){
761                                                         ServiceList sl = new ServiceList();
762                                                         targetSl= new ServiceListJson();
763                                                         sl= mappingServiceList(t);
764                                                         targetSl.setName(sl.getServiceName());
765                                                         targetSl.setDescription(sl.getServiceDescription());
766                                                         targetSl.setTransportProtocol(sl.getServiceTransProtocol());
767                                                         targetSl.setType(sl.getServiceType());
768                                                         targetSl.setPorts(sl.getServicePorts());
769                                                         servListArray.add(targetSl);
770                                                 }else{
771                                                         //Any for destinationServices.
772                                                         //Add names any, any-tcp, any-udp to the serviceGroup object. 
773                                                         targetAny= new ServiceListJson();
774                                                         targetAny.setName("any");
775                                                         targetAny.setType("SERVICE");
776                                                         targetAny.setTransportProtocol("any");
777                                                         targetAny.setPorts("any");
778
779                                                         servListArray.add(targetAny);
780
781                                                         targetAnyTcp= new ServiceListJson();
782                                                         targetAnyTcp.setName("any-tcp");
783                                                         targetAnyTcp.setType("SERVICE");
784                                                         targetAnyTcp.setTransportProtocol("tcp");
785                                                         targetAnyTcp.setPorts("any");
786
787                                                         servListArray.add(targetAnyTcp);
788
789                                                         targetAnyUdp= new ServiceListJson();
790                                                         targetAnyUdp.setName("any-udp");
791                                                         targetAnyUdp.setType("SERVICE");
792                                                         targetAnyUdp.setTransportProtocol("udp");
793                                                         targetAnyUdp.setPorts("any");
794
795                                                         servListArray.add(targetAnyUdp);
796                                                 }
797                                         }else{//This is a group
798                                                 GroupServiceList sg= new GroupServiceList();
799                                                 targetSg= new ServiceGroupJson();
800                                                 sg= mappingServiceGroup(t);
801
802                                                 String name=sg.getGroupName();
803                                                 //Removing the "Group_" prepending string before packing the JSON 
804                                                 targetSg.setName(name.substring(6,name.length()));
805                                                 List<ServiceMembers> servMembersList= new ArrayList<ServiceMembers>();
806
807                                                 for(String groupString: sg.getServiceList().split(",")){
808                                                         ServiceMembers serviceMembers= new ServiceMembers();
809                                                         serviceMembers.setType("REFERENCE");
810                                                         serviceMembers.setName(groupString);
811                                                         servMembersList.add(serviceMembers);
812                                                         //Expand the group Name
813                                                         ServiceList expandGroupSl = new ServiceList();
814                                                         targetSl= new ServiceListJson();
815                                                         expandGroupSl= mappingServiceList(groupString);
816
817                                                         targetSl.setName(expandGroupSl.getServiceName());
818                                                         targetSl.setDescription(expandGroupSl.getServiceDescription());
819                                                         targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol());
820                                                         targetSl.setType(expandGroupSl.getServiceType());
821                                                         targetSl.setPorts(expandGroupSl.getServicePorts());
822                                                         servListArray.add(targetSl);
823                                                 }
824
825                                                 targetSg.setMembers(servMembersList);
826                                                 servGroupArray.add(targetSg);
827
828                                         }
829                                 }
830                         }
831
832                         Set<PrefixIPList> prefixIPList = new HashSet<PrefixIPList>();
833                         for(String prefixList:expandablePrefixIPList){
834                                 for(String prefixIP: prefixList.split(",")){
835                                         if((!prefixIP.startsWith("Group_"))){
836                                                 if(!prefixIP.equals("ANY")){
837                                                         List<AddressMembers> addMembersList= new ArrayList<AddressMembers>();
838                                                         List<String> valueDesc= new ArrayList<String>();
839                                                         PrefixIPList targetAddressList = new PrefixIPList();
840                                                         AddressMembers addressMembers= new AddressMembers();
841                                                         targetAddressList.setName(prefixIP);
842                                                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP);
843                                                         valueDesc = mapping(prefixIP);
844                                                         if(!valueDesc.isEmpty()){
845                                                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"+valueDesc.get(1));
846                                                                 targetAddressList.setDescription(valueDesc.get(1));
847                                                         }
848                                                         
849
850                                                         addressMembers.setType("SUBNET");
851                                                         if(!valueDesc.isEmpty()) {
852                                                                 addressMembers.setValue(valueDesc.get(0));
853                                                         }
854
855                                                         addMembersList.add(addressMembers);
856
857                                                         targetAddressList.setMembers(addMembersList);
858                                                         prefixIPList.add(targetAddressList);
859                                                 }
860                                         }
861                                         else{//This is a group
862                                                 AddressGroup ag= new AddressGroup();
863                                                 addressSg= new AddressGroupJson();
864                                                 ag= mappingAddressGroup(prefixIP);              
865
866                                                 String name=ag.getGroupName();
867                                                 //Removing the "Group_" prepending string before packing the JSON 
868                                                 addressSg.setName(name.substring(6,name.length()));
869
870                                                 List<AddressMembers> addrMembersList= new ArrayList<AddressMembers>();
871                                                 for(String groupString: ag.getPrefixList().split(",")){
872                                                         List<String> valueDesc= new ArrayList<String>();
873                                                         AddressMembers addressMembers= new AddressMembers();
874                                                         valueDesc= mapping (groupString);
875                                                         if(valueDesc.size() > 0){
876                                                                 addressMembers.setValue(valueDesc.get(0));
877                                                         }
878                                                         addressMembers.setType("SUBNET");
879                                                         addrMembersList.add(addressMembers);
880                                                         //Expand the group Name
881                                                 }
882                                                 addressSg.setMembers(addrMembersList);
883                                                 addrGroupArray.add(addressSg);
884                                         }
885
886
887                                 }
888                         }
889
890                         Set<Object> serviceGroup= new HashSet<Object>();
891
892                         for(Object obj1:servGroupArray){
893                                 serviceGroup.add(obj1);
894                         }
895
896                         for(Object obj:servListArray){
897                                 serviceGroup.add(obj);
898                         }
899
900                         Set<Object> addressGroup= new HashSet<Object>();
901
902                         for(Object addObj:prefixIPList){
903                                 addressGroup.add(addObj);
904                         }
905
906                         for(Object addObj1:addrGroupArray){
907                                 addressGroup.add(addObj1);
908                         }
909
910                         tc.setServiceGroups(serviceGroup);
911                         tc.setAddressGroups(addressGroup);
912                         tc.setFirewallRuleList(termList);
913
914                         ObjectWriter om = new ObjectMapper().writer();
915                         try {
916                                 json = om.writeValueAsString(tc);
917                         } catch (JsonGenerationException e) {
918                                 e.printStackTrace();
919                         } catch (JsonMappingException e) {
920                                 e.printStackTrace();
921                         } catch (IOException e) {
922                                 e.printStackTrace();
923                         }       
924
925                 }catch (Exception e) {
926                         e.printStackTrace();
927                 }
928
929                 return json;
930         }
931
932 }