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