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