Remove useless imports and vars
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / FirewallConfigPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2019 Bell Canada.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.xacml.rest.components;
23
24 import com.att.research.xacml.api.pap.PAPException;
25 import com.att.research.xacml.std.IdentifierImpl;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.github.fge.jackson.JsonLoader;
28 import com.github.fge.jsonpatch.diff.JsonDiff;
29 import java.io.BufferedWriter;
30 import java.io.File;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.StringReader;
34 import java.net.URI;
35 import java.net.URISyntaxException;
36 import java.nio.charset.Charset;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.sql.SQLException;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import javax.json.Json;
45 import javax.json.JsonArray;
46 import javax.json.JsonObject;
47 import javax.json.JsonReader;
48 import javax.script.SimpleBindings;
49 import org.apache.commons.io.FilenameUtils;
50 import org.onap.policy.common.logging.eelf.MessageCodes;
51 import org.onap.policy.common.logging.eelf.PolicyLogger;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.rest.dao.CommonClassDao;
57 import org.onap.policy.rest.jpa.ActionList;
58 import org.onap.policy.rest.jpa.AddressGroup;
59 import org.onap.policy.rest.jpa.GroupServiceList;
60 import org.onap.policy.rest.jpa.PolicyEntity;
61 import org.onap.policy.rest.jpa.PortList;
62 import org.onap.policy.rest.jpa.PrefixList;
63 import org.onap.policy.rest.jpa.ProtocolList;
64 import org.onap.policy.rest.jpa.ServiceList;
65 import org.onap.policy.rest.jpa.TermList;
66 import org.onap.policy.rest.jpa.UserInfo;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.stereotype.Component;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
82
83 @Component
84 public class FirewallConfigPolicy extends Policy {
85
86     private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class);
87
88     public FirewallConfigPolicy() {
89         super();
90     }
91
92     private static CommonClassDao commonClassDao;
93
94     @Autowired
95     public FirewallConfigPolicy(CommonClassDao commonClassDao) {
96         FirewallConfigPolicy.commonClassDao = commonClassDao;
97     }
98
99     public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
100         this.policyAdapter = policyAdapter;
101         this.policyAdapter.setConfigType(policyAdapter.getConfigType());
102     }
103
104     // Saving the Configurations file at server location for config policy.
105     protected void saveConfigurations(String policyName, String jsonBody) {
106         String configurationName = policyName;
107         if (configurationName.endsWith(".xml")) {
108             configurationName = configurationName.replace(".xml", "");
109         }
110         String fileName = CONFIG_HOME + File.separator + configurationName + ".json";
111         try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
112             bw.write(jsonBody);
113             if (LOGGER.isDebugEnabled()) {
114                 LOGGER.debug("Configuration is succesfully saved");
115             }
116         } catch (IOException e) {
117             LOGGER.error("Save of configuration to file" +fileName+ "failed",e);
118         }
119     }
120
121    //Utility to read json data from the existing file to a string
122     static String readFile(String path, Charset encoding) throws IOException {
123         byte[] encoded = Files.readAllBytes(Paths.get(path));
124         return new String(encoded, encoding);
125     }
126
127     @Override
128     public Map<String, String> savePolicies() throws PAPException {
129         Map<String, String> successMap = new HashMap<>();
130         if(isPolicyExists()){
131             successMap.put("EXISTS", "This Policy already exist on the PAP");
132             return successMap;
133         }
134         if(!isPreparedToSave()){
135             prepareToSave();
136         }
137
138         // Until here we prepared the data and here calling the method to create xml.
139         Path newPolicyPath = null;
140         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
141         Boolean dbIsUpdated = false;
142         if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){
143             if (policyAdapter.isEditPolicy()) {
144                 dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
145             } else {
146                 try {
147                     dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
148                 } catch (SQLException e) {
149                     throw new PAPException(e);
150                 }
151             }
152         } else {
153             dbIsUpdated = true;
154         }
155
156         if(dbIsUpdated) {
157             successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
158         } else {
159             PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
160
161             //remove the new json file
162             String jsonBody = policyAdapter.getPrevJsonBody();
163             if (jsonBody!=null){
164                 saveConfigurations(policyName, jsonBody);
165             } else {
166                 saveConfigurations(policyName, "");
167             }
168             successMap.put("fwdberror", "DB UPDATE");
169         }
170
171         return successMap;
172     }
173
174     //This is the method for preparing the policy for saving.  We have broken it out
175     //separately because the fully configured policy is used for multiple things
176     @Override
177     public boolean prepareToSave() throws PAPException{
178
179         if(isPreparedToSave()){
180             //we have already done this
181             return true;
182         }
183
184         int version = 0;
185         String policyID = policyAdapter.getPolicyID();
186         version = policyAdapter.getHighestVersion();
187
188         // Create the Instance for pojo, PolicyType object is used in marshaling.
189         if ("Config".equals(policyAdapter.getPolicyType())) {
190             PolicyType policyConfig = new PolicyType();
191
192             policyConfig.setVersion(Integer.toString(version));
193             policyConfig.setPolicyId(policyID);
194             policyConfig.setTarget(new TargetType());
195             policyAdapter.setData(policyConfig);
196         }
197         policyName = policyAdapter.getNewFileName();
198
199         //String oldPolicyName = policyName.replace(".xml", "");
200         String scope = policyName.substring(0, policyName.indexOf('.'));
201         String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", "");
202
203         int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1));
204         dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1);
205         if(oldversion > 1){
206             oldversion = oldversion - 1;
207             dbPolicyName = dbPolicyName + oldversion + ".xml";
208         }
209         String createPolicyQuery = "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName";
210         SimpleBindings params = new SimpleBindings();
211         params.put("scope", scope);
212         params.put("policyName", dbPolicyName);
213         List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params);
214         if (!createPolicyQueryList.isEmpty()) {
215             PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0);
216             policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody());
217         }
218         if (policyAdapter.getData() != null) {
219             String jsonBody = policyAdapter.getJsonBody();
220             saveConfigurations(policyName, jsonBody);
221
222             // Make sure the filename ends with an extension
223             if (!policyName.endsWith(".xml")) {
224                 policyName = policyName + ".xml";
225             }
226
227             PolicyType configPolicy = (PolicyType) policyAdapter.getData();
228
229             configPolicy.setDescription(policyAdapter.getPolicyDescription());
230
231             configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
232
233             AllOfType allOfOne = new AllOfType();
234             String fileName = policyAdapter.getNewFileName();
235             String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
236             if ((name == null) || (name.equals(""))) {
237                 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
238             }
239             allOfOne.getMatch().add(createMatch("PolicyName", name));
240             AllOfType allOf = new AllOfType();
241
242             // Match for ConfigName
243             allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
244             // Match for riskType
245             allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
246             // Match for riskLevel
247             allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
248             // Match for riskguard
249             allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
250             // Match for ttlDate
251             allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
252             AnyOfType anyOf = new AnyOfType();
253             anyOf.getAllOf().add(allOfOne);
254             anyOf.getAllOf().add(allOf);
255
256             TargetType target = new TargetType();
257             target.getAnyOf().add(anyOf);
258
259             // Adding the target to the policy element
260             configPolicy.setTarget(target);
261
262             RuleType rule = new RuleType();
263             rule.setRuleId(policyAdapter.getRuleID());
264             rule.setEffect(EffectType.PERMIT);
265
266             // Create Target in Rule
267             AllOfType allOfInRule = new AllOfType();
268
269             // Creating match for ACCESS in rule target
270             MatchType accessMatch = new MatchType();
271             AttributeValueType accessAttributeValue = new AttributeValueType();
272             accessAttributeValue.setDataType(STRING_DATATYPE);
273             accessAttributeValue.getContent().add("ACCESS");
274             accessMatch.setAttributeValue(accessAttributeValue);
275             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
276             URI accessURI = null;
277             try {
278                 accessURI = new URI(ACTION_ID);
279             } catch (URISyntaxException e) {
280                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
281             }
282             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
283             accessAttributeDesignator.setDataType(STRING_DATATYPE);
284             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
285             accessMatch.setAttributeDesignator(accessAttributeDesignator);
286             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
287
288             // Creating Config Match in rule Target
289             MatchType configMatch = new MatchType();
290             AttributeValueType configAttributeValue = new AttributeValueType();
291             configAttributeValue.setDataType(STRING_DATATYPE);
292
293             configAttributeValue.getContent().add("Config");
294
295             configMatch.setAttributeValue(configAttributeValue);
296             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
297             URI configURI = null;
298             try {
299                 configURI = new URI(RESOURCE_ID);
300             } catch (URISyntaxException e) {
301                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
302             }
303
304             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
305             configAttributeDesignator.setDataType(STRING_DATATYPE);
306             configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
307             configMatch.setAttributeDesignator(configAttributeDesignator);
308             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
309
310             allOfInRule.getMatch().add(accessMatch);
311             allOfInRule.getMatch().add(configMatch);
312
313             AnyOfType anyOfInRule = new AnyOfType();
314             anyOfInRule.getAllOf().add(allOfInRule);
315
316             TargetType targetInRule = new TargetType();
317             targetInRule.getAnyOf().add(anyOfInRule);
318
319             rule.setTarget(targetInRule);
320             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
321
322             configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
323             policyAdapter.setPolicyData(configPolicy);
324
325         } else {
326             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
327         }
328         setPreparedToSave(true);
329         return true;
330     }
331
332     // Data required for Advice part is setting here.
333     private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
334
335         //Firewall Config ID Assignment
336         AdviceExpressionsType advices = new AdviceExpressionsType();
337         AdviceExpressionType advice = new AdviceExpressionType();
338         advice.setAdviceId("firewallConfigID");
339         advice.setAppliesTo(EffectType.PERMIT);
340         // For Configuration
341         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
342         assignment1.setAttributeId("type");
343         assignment1.setCategory(CATEGORY_RESOURCE);
344         assignment1.setIssuer("");
345         AttributeValueType configNameAttributeValue = new AttributeValueType();
346         configNameAttributeValue.setDataType(STRING_DATATYPE);
347         configNameAttributeValue.getContent().add("Configuration");
348         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
349         advice.getAttributeAssignmentExpression().add(assignment1);
350
351         // For Config file Url if configurations are provided.
352         //URL ID Assignment
353         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
354         assignment2.setAttributeId("URLID");
355         assignment2.setCategory(CATEGORY_RESOURCE);
356         assignment2.setIssuer("");
357         AttributeValueType AttributeValue = new AttributeValueType();
358         AttributeValue.setDataType(URI_DATATYPE);
359         if (policyName.endsWith(".xml")) {
360             policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
361         }
362         String content = CONFIG_URL + "/Config/" + policyName + ".json";
363
364         AttributeValue.getContent().add(content);
365         assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
366         advice.getAttributeAssignmentExpression().add(assignment2);
367
368         //Policy Name Assignment
369         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
370         assignment3.setAttributeId("PolicyName");
371         assignment3.setCategory(CATEGORY_RESOURCE);
372         assignment3.setIssuer("");
373         AttributeValueType attributeValue3 = new AttributeValueType();
374         attributeValue3.setDataType(STRING_DATATYPE);
375         fileName = FilenameUtils.removeExtension(fileName);
376         fileName = fileName + ".xml";
377         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
378         if ((name == null) || (name.equals(""))) {
379             name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
380         }
381         attributeValue3.getContent().add(name);
382         assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
383         advice.getAttributeAssignmentExpression().add(assignment3);
384
385         //Version Number Assignment
386         AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
387         assignment4.setAttributeId("VersionNumber");
388         assignment4.setCategory(CATEGORY_RESOURCE);
389         assignment4.setIssuer("");
390         AttributeValueType configNameAttributeValue4 = new AttributeValueType();
391         configNameAttributeValue4.setDataType(STRING_DATATYPE);
392         configNameAttributeValue4.getContent().add(Integer.toString(version));
393         assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
394         advice.getAttributeAssignmentExpression().add(assignment4);
395
396         //Onap Name Assignment
397         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
398         assignment5.setAttributeId("matching:" + ONAPID);
399         assignment5.setCategory(CATEGORY_RESOURCE);
400         assignment5.setIssuer("");
401         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
402         configNameAttributeValue5.setDataType(STRING_DATATYPE);
403         assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
404         advice.getAttributeAssignmentExpression().add(assignment5);
405
406         //Config Name Assignment
407         AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
408         assignment6.setAttributeId("matching:" + CONFIGID);
409         assignment6.setCategory(CATEGORY_RESOURCE);
410         assignment6.setIssuer("");
411         AttributeValueType configNameAttributeValue6 = new AttributeValueType();
412         configNameAttributeValue6.setDataType(STRING_DATATYPE);
413         configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
414         assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
415         advice.getAttributeAssignmentExpression().add(assignment6);
416
417         //Risk Attributes
418         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
419         assignment7.setAttributeId("RiskType");
420         assignment7.setCategory(CATEGORY_RESOURCE);
421         assignment7.setIssuer("");
422
423         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
424         configNameAttributeValue7.setDataType(STRING_DATATYPE);
425         configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
426         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
427
428         advice.getAttributeAssignmentExpression().add(assignment7);
429
430         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
431         assignment8.setAttributeId("RiskLevel");
432         assignment8.setCategory(CATEGORY_RESOURCE);
433         assignment8.setIssuer("");
434
435         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
436         configNameAttributeValue8.setDataType(STRING_DATATYPE);
437         configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
438         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
439
440         advice.getAttributeAssignmentExpression().add(assignment8);
441
442         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
443         assignment9.setAttributeId("guard");
444         assignment9.setCategory(CATEGORY_RESOURCE);
445         assignment9.setIssuer("");
446
447         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
448         configNameAttributeValue9.setDataType(STRING_DATATYPE);
449         configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
450         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
451
452         advice.getAttributeAssignmentExpression().add(assignment9);
453
454         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
455         assignment10.setAttributeId("TTLDate");
456         assignment10.setCategory(CATEGORY_RESOURCE);
457         assignment10.setIssuer("");
458
459         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
460         configNameAttributeValue10.setDataType(STRING_DATATYPE);
461         configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
462         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
463
464         advice.getAttributeAssignmentExpression().add(assignment10);
465         advices.getAdviceExpression().add(advice);
466         return advices;
467     }
468
469
470     private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
471         CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
472         JsonObject json = null;
473         if (jsonBody != null) {
474
475             //Read jsonBody to JsonObject
476             json = stringToJson(jsonBody);
477
478             JsonArray firewallRules = null;
479             JsonArray serviceGroup = null;
480             JsonArray addressGroup = null;
481             //insert data into tables
482             try {
483                 firewallRules = json.getJsonArray("firewallRuleList");
484                 serviceGroup = json.getJsonArray("serviceGroups");
485                 addressGroup = json.getJsonArray("addressGroups");
486                 /*
487                  * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
488                  */
489                 if (firewallRules != null) {
490                     for(int i = 0;i<firewallRules.size();i++) {
491                         /*
492                          * Populate ArrayLists with values from the JSON
493                          */
494                         //create the JSON object from the JSON Array for each iteration through the for loop
495                         JsonObject ruleListobj = firewallRules.getJsonObject(i);
496
497                         //get values from JSON fields of firewallRulesList Array
498                         String ruleName = ruleListobj.get("ruleName").toString();
499                         String action = ruleListobj.get("action").toString();
500                         String description = ruleListobj.get("description").toString();
501                         List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
502                         if(result != null && !result.isEmpty()){
503                             TermList termEntry = (TermList) result.get(0);
504                             dbConnection.delete(termEntry);
505                         }
506
507                         //getting fromZone Array field from the firewallRulesList
508                         JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
509                         String fromZoneString = null;
510
511                         for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
512                             String value = fromZoneArray.get(fromZoneIndex).toString();
513                             value = value.replace("\"", "");
514                             if (fromZoneString != null) {
515                                 fromZoneString = fromZoneString.concat(",").concat(value);
516                             } else {
517                                 fromZoneString = value;
518                             }
519                         }
520                         String fromZoneInsert = "'"+fromZoneString+"'";
521
522                         //getting toZone Array field from the firewallRulesList
523                         JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
524                         String toZoneString = null;
525                         for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
526                             String value = toZoneArray.get(toZoneIndex).toString();
527                             value = value.replace("\"", "");
528                             if (toZoneString != null) {
529                                 toZoneString = toZoneString.concat(",").concat(value);
530                             } else {
531                                 toZoneString = value;
532                             }
533                         }
534                         String toZoneInsert = "'"+toZoneString+"'";
535
536                         //getting sourceList Array fields from the firewallRulesList
537                         JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
538                         String srcListString = null;
539                         for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
540                             JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
541                             String type = srcListObj.get("type").toString().replace("\"", "");
542
543                             String value = null;
544                             if(type.equals("REFERENCE")||type.equals("GROUP")){
545                                 value = srcListObj.get("name").toString();
546                             } else if (type.equalsIgnoreCase("ANY")){
547                                 value = null;
548                             } else {
549                                 value = srcListObj.get("value").toString();
550                             }
551
552                             srcListString = getLeftOrRight(srcListString, value);
553
554                         }
555                         String srcListInsert = "'"+srcListString+"'";
556
557                         //getting destinationList Array fields from the firewallRulesList
558                         JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
559                         String destListString = null;
560                         for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
561                             JsonObject destListObj = destListArray.getJsonObject(destListIndex);
562                             String type = destListObj.get("type").toString().replace("\"", "");
563
564                             String value = null;
565                             if(type.equals("REFERENCE")||type.equals("GROUP")){
566                                 value = destListObj.get("name").toString();
567                             } else if (type.equalsIgnoreCase("ANY")){
568                                 value = null;
569                             } else {
570                                 value = destListObj.get("value").toString();
571                             }
572
573                             destListString = getLeftOrRight(destListString, value);
574                         }
575                         String destListInsert = "'"+destListString+"'";
576
577                         //getting destServices Array fields from the firewallRulesList
578                         JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
579                         String destPortListString = null;
580                         for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
581                             JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
582                             String type = destServicesObj.get("type").toString().replace("\"", "");
583
584                             String value = null;
585                             if(type.equals("REFERENCE")||type.equals("GROUP")){
586                                 value = destServicesObj.get("name").toString();
587                             } else if (type.equalsIgnoreCase("ANY")){
588                                 value = null;
589                             } else {
590                                 value = destServicesObj.get("value").toString();
591                             }
592
593                             destPortListString = getLeftOrRight(destPortListString, value);
594                         }
595                         String destPortListInsert = "'"+destPortListString+"'";
596
597                         /*
598                          * Create Queries to INSERT data into database tables and execute
599                          */
600                         UserInfo userInfo = new UserInfo();
601                         userInfo.setUserLoginId("API");
602                         userInfo.setUserName("API");
603
604                         TermList termEntry = new TermList();
605                         termEntry.setTermName(ruleName);
606                         termEntry.setSrcIPList(srcListInsert);
607                         termEntry.setDestIPList(destListInsert);
608                         termEntry.setProtocolList("null");
609                         termEntry.setPortList("null");
610                         termEntry.setSrcPortList("null");
611                         termEntry.setDestPortList(destPortListInsert);
612                         termEntry.setAction(action);
613                         termEntry.setDescription(description);
614                         termEntry.setFromZones(fromZoneInsert);
615                         termEntry.setToZones(toZoneInsert);
616                         termEntry.setUserCreatedBy(userInfo);
617                         dbConnection.save(termEntry);
618
619                         saveActionListToDb(dbConnection, action);
620                     }
621                 }
622
623                 /*
624                  * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
625                  */
626                 if (serviceGroup != null) {
627                     for(int i = 0; i < serviceGroup.size() ; i++) {
628                         /*
629                          * Populate ArrayLists with values from the JSON
630                          */
631                         //create the JSON object from the JSON Array for each iteration through the for loop
632                         JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
633
634                         String serviceListName = svcGroupListobj.get("name").toString();
635                         String description = null;
636                         if (svcGroupListobj.containsKey("description")){
637                             description = svcGroupListobj.get("description").toString();
638                         }
639
640                         //getting members Array from the serviceGroup
641                         JsonArray membersArray = svcGroupListobj.getJsonArray("members");
642
643                         //String type = svcGroupListobj.get("type").toString();
644                         Boolean isServiceGroup = false;
645                         if (membersArray!=null){
646                             String membersType = membersArray.getJsonObject(0).get("type").toString();
647                             if (membersType.contains("REFERENCE")) {
648                                 isServiceGroup = true;
649                             }
650                         }
651
652                         //Insert values into GROUPSERVICELIST table if name begins with Group
653                         if (isServiceGroup) {
654                             saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray);
655                         } else { //Insert JSON data serviceList table, protollist table, and portlist table
656                             String type = svcGroupListobj.get("type").toString();
657                             String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
658                             String ports = svcGroupListobj.get("ports").toString();
659
660                             /*
661                              * Create Queries to INSERT data into database table and execute
662                              */
663                             saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports);
664
665                             saveProtocolListToDb(dbConnection, transportProtocol);
666
667                             savePortListToDb(dbConnection, ports);
668                         }
669                     }
670                 }
671
672                 /*
673                  * Inserting addressGroup data into the ADDRESSGROUP table
674                  */
675                 if (addressGroup != null) {
676                     for(int i = 0; i < addressGroup.size(); i++) {
677                         /*
678                          * Populate ArrayLists with values from the JSON
679                          */
680                         //create the JSON object from the JSON Array for each iteration through the for loop
681                         JsonObject addressGroupObj = addressGroup.getJsonObject(i);
682
683                         //create JSON array for members
684                         JsonArray membersArray = addressGroupObj.getJsonArray("members");
685                         String addressGroupName = addressGroupObj.get("name").toString();
686
687                         String description = null;
688                         if (addressGroupObj.containsKey("description")){
689                             description = addressGroupObj.get("description").toString();
690                         }
691
692                         String prefixIP = null;
693                         String type = null;
694                         for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
695                             JsonObject membersObj = membersArray.getJsonObject(membersIndex);
696                             type = membersObj.get("type").toString().replace("\"", "");
697
698                             prefixIP = getName(prefixIP, membersObj, type);
699                         }
700                         String prefixList = "'"+prefixIP+"'";
701
702                         Boolean isAddressGroup = type.contains("REFERENCE");
703
704                         if (isAddressGroup) {
705                             saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
706                         } else {
707                             savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
708                         }
709                     }
710                 }
711                 removeDuplicateValuesFromLookup(dbConnection);
712             }catch (Exception e) {
713                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
714                 return false;
715             }
716             return true;
717
718         } else {
719             return false;
720         }
721
722     }
723
724     /*
725      * Remove duplicate values from 'lookup' dictionary tables
726      */
727     private void removeDuplicateValuesFromLookup(CommonClassDaoImpl dbConnection) {
728         String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
729                 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
730         dbConnection.updateQuery(protoDelete);
731
732         //PortList Table
733         String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
734                 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
735         dbConnection.updateQuery(portListDelete);
736
737         //PrefixList Table
738         String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
739                 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
740                 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
741         dbConnection.updateQuery(prefixListDelete);
742
743         //GroupServiceList
744         String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
745                 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
746                 + "groupservicelist.serviceList = g1.serviceList; ";
747         dbConnection.updateQuery(groupServiceDelete);
748     }
749
750     private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) {
751         String name = null;
752         for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
753             JsonObject membersObj = membersArray.getJsonObject(membersIndex);
754             String type = membersObj.get("type").toString().replace("\"", "");
755
756             name = getName(name, membersObj, type);
757         }
758         String nameInsert = "'"+name+"'";
759         GroupServiceList groupServiceEntry = new GroupServiceList();
760         groupServiceEntry.setGroupName(serviceListName);
761         groupServiceEntry.setServiceList(nameInsert);
762         dbConnection.save(groupServiceEntry);
763     }
764
765     private String getName(String name, JsonObject membersObj, String type) {
766         String value;
767         if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
768             value = membersObj.get("name").toString();
769         } else if (type.equalsIgnoreCase("ANY")){
770             value = null;
771         } else {
772             value = membersObj.get("value").toString();
773         }
774
775         name = getLeftOrRight(name, value);
776         return name;
777     }
778
779     private String getLeftOrRight(String name, String value) {
780         if (value != null) {
781             value = value.replace("\"", "");
782         }
783
784         if (name != null) {
785             name = name.concat(",").concat(value);
786         } else {
787             name = value.replace("\"", "");;
788         }
789         return name;
790     }
791
792
793     private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
794         CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
795         JsonObject oldJson = null;
796         JsonObject newJson = null;
797
798         if (jsonBody != null || prevJsonBody != null) {
799
800             oldJson = stringToJson(prevJsonBody);
801             newJson = stringToJson(jsonBody);
802
803             //if no changes to the json then return true
804             if (oldJson != null && oldJson.equals(newJson)) {
805                 return true;
806             }
807
808             JsonArray firewallRules = null;
809             JsonArray serviceGroup = null;
810             JsonArray addressGroup = null;
811
812             firewallRules = newJson.getJsonArray("firewallRuleList");
813             serviceGroup = newJson.getJsonArray("serviceGroups");
814             addressGroup = newJson.getJsonArray("addressGroups");
815
816             //insert data into tables
817             try {
818                 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
819
820                 for (int i = 0; i<jsonDiff.size(); i++) {
821                     //String path = jsonDiff.get(i).asText();
822                     String jsonpatch = jsonDiff.get(i).toString();
823
824                     JsonObject patchObj = stringToJson(jsonpatch);
825
826                     String path = patchObj.get("path").toString().replace('"', ' ').trim();
827
828                     if (path.contains("firewallRuleList")) {
829                         /*
830                          * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
831                          */
832                         for(int ri = 0; ri < firewallRules.size(); ri++) {
833                             /*
834                              * Populate ArrayLists with values from the JSON
835                              */
836                             //create the JSON object from the JSON Array for each iteration through the for loop
837                             JsonObject ruleListobj = firewallRules.getJsonObject(ri);
838
839                             //get values from JSON fields of firewallRulesList Array
840                             String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
841                             String action = ruleListobj.get("action").toString().replace('"', '\'');
842                             String description = ruleListobj.get("description").toString().replace('"', '\'');
843
844                             List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
845                             if(result != null && !result.isEmpty()){
846                                 TermList termEntry = (TermList) result.get(0);
847                                 dbConnection.delete(termEntry);
848                             }
849
850                             //getting fromZone Array field from the firewallRulesList
851                             JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
852                             String fromZoneString = null;
853
854                             for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
855                                 String value = fromZoneArray.get(fromZoneIndex).toString();
856                                 value = value.replace("\"", "");
857
858                                 if (fromZoneString != null) {
859                                     fromZoneString = fromZoneString.concat(",").concat(value);
860
861                                 } else {
862                                     fromZoneString = value;
863                                 }
864
865                             }
866                             String fromZoneInsert = "'"+fromZoneString+"'";
867
868                             //getting toZone Array field from the firewallRulesList
869                             JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
870                             String toZoneString = null;
871
872
873                             for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
874                                 String value = toZoneArray.get(toZoneIndex).toString();
875                                 value = value.replace("\"", "");
876
877                                 if (toZoneString != null) {
878                                     toZoneString = toZoneString.concat(",").concat(value);
879
880                                 } else {
881                                     toZoneString = value;
882                                 }
883
884                             }
885                             String toZoneInsert = "'"+toZoneString+"'";
886                             //getting sourceList Array fields from the firewallRulesList
887                             JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
888                             String srcListString = null;
889                             for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
890                                 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
891                                 String type = srcListObj.get("type").toString().replace("\"", "");
892
893                                 String value = null;
894                                 if(type.equals("REFERENCE")||type.equals("GROUP")){
895                                     value = srcListObj.get("name").toString();
896                                 } else if (type.equalsIgnoreCase("ANY")){
897                                     value = null;
898                                 } else {
899                                     value = srcListObj.get("value").toString();
900                                 }
901
902                                 srcListString = getLeftOrRight(srcListString, value);
903
904                             }
905                             String srcListInsert = "'"+srcListString+"'";
906
907                             //getting destinationList Array fields from the firewallRulesList
908                             JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
909                             String destListString = null;
910                             for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
911                                 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
912                                 String type = destListObj.get("type").toString().replace("\"", "");
913
914                                 String value = null;
915                                 if(type.equals("REFERENCE")||type.equals("GROUP")){
916                                     value = destListObj.get("name").toString();
917                                 } else if (type.equalsIgnoreCase("ANY")){
918                                     value = null;
919                                 } else {
920                                     value = destListObj.get("value").toString();
921                                 }
922
923                                 destListString = getLeftOrRight(destListString, value);
924                             }
925                             String destListInsert = "'"+destListString+"'";
926
927                             //getting destServices Array fields from the firewallRulesList
928                             JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
929                             String destPortListString = null;
930                             for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
931                                 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
932                                 String type = destServicesObj.get("type").toString().replace("\"", "");
933
934                                 String value = null;
935                                 if(type.equals("REFERENCE")||type.equals("GROUP")){
936                                     value = destServicesObj.get("name").toString();
937                                 } else if (type.equalsIgnoreCase("ANY")){
938                                     value = null;
939                                 } else {
940                                     value = destServicesObj.get("value").toString();
941                                 }
942
943                                 destPortListString = getLeftOrRight(destPortListString, value);
944                             }
945                             String destPortListInsert = "'"+destPortListString+"'";
946
947                             /*
948                              * Create Queries to INSERT data into database tables and execute
949                              */
950                             UserInfo userInfo = new UserInfo();
951                             userInfo.setUserLoginId("API");
952                             userInfo.setUserName("API");
953
954                             TermList termEntry = new TermList();
955                             termEntry.setTermName(ruleName);
956                             termEntry.setSrcIPList(srcListInsert);
957                             termEntry.setDestIPList(destListInsert);
958                             termEntry.setProtocolList("null");
959                             termEntry.setPortList("null");
960                             termEntry.setSrcPortList("null");
961                             termEntry.setDestPortList(destPortListInsert);
962                             termEntry.setAction(action);
963                             termEntry.setDescription(description);
964                             termEntry.setFromZones(fromZoneInsert);
965                             termEntry.setToZones(toZoneInsert);
966                             termEntry.setUserCreatedBy(userInfo);
967                             dbConnection.save(termEntry);
968
969                             List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action);
970                             if(actionResult == null || actionResult.isEmpty()){
971                                 saveActionListToDb(dbConnection, action);
972                             }
973                         }
974                     }
975
976                     if (path.contains("serviceGroups")) {
977                         /*
978                          * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
979                          */
980                         for(int si = 0; si < serviceGroup.size(); si++) {
981                             /*
982                              * Populate ArrayLists with values from the JSON
983                              */
984                             //create the JSON object from the JSON Array for each iteration through the for loop
985                             JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
986
987                             String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
988
989                             String description = null;
990                             if (svcGroupListobj.containsKey("description")){
991                                 description = svcGroupListobj.get("description").toString().replace('"', '\'');
992                             }
993
994                             JsonArray membersArray = svcGroupListobj.getJsonArray("members");
995
996                             Boolean isServiceGroup = false;
997                             if (membersArray!=null){
998                                 String membersType = membersArray.getJsonObject(0).get("type").toString();
999                                 if (membersType.contains("REFERENCE")) {
1000                                     isServiceGroup = true;
1001                                 }
1002                             }
1003
1004                             //Insert values into GROUPSERVICELIST table if name begins with Group
1005                             if (isServiceGroup) {
1006                                 List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName);
1007                                 if(result != null && !result.isEmpty()){
1008                                     GroupServiceList groupEntry = (GroupServiceList) result.get(0);
1009                                     dbConnection.delete(groupEntry);
1010                                 }
1011
1012                                 saveGroupServiceListTableToDb(dbConnection, groupName, membersArray);
1013                             } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1014                                 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1015                                 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1016                                 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1017
1018                                 List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
1019                                 if(result != null && !result.isEmpty()){
1020                                     ServiceList serviceEntry = (ServiceList) result.get(0);
1021                                     dbConnection.delete(serviceEntry);
1022                                 }
1023
1024                                 saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports);
1025
1026                                 List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
1027                                 if(protocolResult == null || protocolResult.isEmpty()){
1028                                     saveProtocolListToDb(dbConnection, transportProtocol);
1029                                 }
1030
1031                                 List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
1032                                 if(portResult == null || portResult.isEmpty()){
1033                                     savePortListToDb(dbConnection, ports);
1034                                 }
1035                             }
1036                         }
1037                     }
1038
1039                     if (path.contains("addressGroups")) {
1040                         /*
1041                          * Inserting addressGroup data into the ADDRESSGROUP table
1042                          */
1043                         for(int ai=0; ai < addressGroup.size() ; ai++) {
1044
1045                             /*
1046                              * Populate ArrayLists with values from the JSON
1047                              */
1048                             //create the JSON object from the JSON Array for each iteration through the for loop
1049                             JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1050
1051                             //create JSON array for members
1052                             JsonArray membersArray = addressGroupObj.getJsonArray("members");
1053                             String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1054
1055                             String description = null;
1056                             if (addressGroupObj.containsKey("description")){
1057                                 description = addressGroupObj.get("description").toString().replace('"', '\'');
1058                             }
1059
1060                             String prefixIP = null;
1061                             String type = null;
1062                             for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
1063                                 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1064                                 type = membersObj.get("type").toString().replace("\"", "");
1065
1066                                 prefixIP = getName(prefixIP, membersObj, type);
1067                             }
1068
1069                             String prefixList = "'"+prefixIP+"'";
1070                             Boolean isAddressGroup = type.contains("REFERENCE");
1071
1072                             if (isAddressGroup) {
1073                                 List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
1074                                 if(result != null && !result.isEmpty()){
1075                                     AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
1076                                     dbConnection.delete(addressGroupEntry);
1077                                 }
1078                                 saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
1079                             } else {
1080                                 List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
1081                                 if(result != null && !result.isEmpty()){
1082                                     PrefixList prefixListEntry = (PrefixList) result.get(0);
1083                                     dbConnection.delete(prefixListEntry);
1084                                 }
1085                                 savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
1086                             }
1087                         }
1088                     }
1089                 }
1090                 removeDuplicateValuesFromLookup(dbConnection);
1091             }catch (Exception e) {
1092                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1093                 return false;
1094             }
1095             return true;
1096         } else {
1097             return false;
1098         }
1099
1100     }
1101
1102     private void saveActionListToDb(CommonClassDaoImpl dbConnection, String action) {
1103         ActionList actionEntry = new ActionList();
1104         actionEntry.setActionName(action);
1105         actionEntry.setDescription(action);
1106         dbConnection.save(actionEntry);
1107     }
1108
1109     private void savePortListToDb(CommonClassDaoImpl dbConnection, String ports) {
1110         PortList portEntry = new PortList();
1111         portEntry.setPortName(ports);
1112         portEntry.setDescription(ports);
1113         dbConnection.save(portEntry);
1114     }
1115
1116     private void saveProtocolListToDb(CommonClassDaoImpl dbConnection, String transportProtocol) {
1117         ProtocolList protocolEntry = new ProtocolList();
1118         protocolEntry.setProtocolName(transportProtocol);
1119         protocolEntry.setDescription(transportProtocol);
1120         dbConnection.save(protocolEntry);
1121     }
1122
1123     private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) {
1124         ServiceList serviceListEntry = new ServiceList();
1125         serviceListEntry.setServiceName(groupName);
1126         serviceListEntry.setServiceDescription(description);
1127         serviceListEntry.setServiceType(type);
1128         serviceListEntry.setServiceTransProtocol(transportProtocol);
1129         serviceListEntry.setServiceAppProtocol("null");
1130         serviceListEntry.setServicePorts(ports);
1131         dbConnection.save(serviceListEntry);
1132     }
1133
1134     private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
1135         PrefixList newPrefixList = new PrefixList();
1136         newPrefixList.setPrefixListName(addressGroupName);
1137         newPrefixList.setDescription(description);
1138         newPrefixList.setPrefixListValue(prefixList);
1139         dbConnection.save(newPrefixList);
1140     }
1141
1142     private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
1143         AddressGroup newAddressGroup = new AddressGroup();
1144         newAddressGroup.setGroupName(addressGroupName);
1145         newAddressGroup.setDescription(description);
1146         newAddressGroup.setServiceList(prefixList);
1147         dbConnection.save(newAddressGroup);
1148     }
1149
1150     private JsonObject stringToJson(String jsonString) {
1151         //Read jsonBody to JsonObject
1152         StringReader in = new StringReader(jsonString);
1153         JsonReader jsonReader = Json.createReader(in);
1154         JsonObject json = jsonReader.readObject();
1155         jsonReader.close();
1156         return json;
1157     }
1158
1159     private JsonNode createPatch(String json, String oldJson) {
1160         JsonNode oldJason = null;
1161         JsonNode updatedJason = null;
1162
1163         try {
1164             oldJason = JsonLoader.fromString(oldJson);
1165             updatedJason = JsonLoader.fromString(json);
1166         } catch (IOException e) {
1167             LOGGER.error("Exception Occured"+e);
1168         }
1169         return JsonDiff.asJson(oldJason, updatedJason);
1170     }
1171
1172     @Override
1173     public Object getCorrectPolicyDataObject() {
1174         return policyAdapter.getPolicyData();
1175     }
1176
1177 }