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