aboutsummaryrefslogtreecommitdiffstats
path: root/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java
blob: eca473f41687d6a958e8ed77737a224d0c946549 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
/*-
 * ============LICENSE_START=======================================================
 * ONAP-PAP-REST
 * ================================================================================
 * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved.
 * Modified Copyright (C) 2019 Bell Canada.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.pap.xacml.rest.components;

import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.std.IdentifierImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonpatch.diff.JsonDiff;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.script.SimpleBindings;
import org.apache.commons.io.FilenameUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.ActionList;
import org.onap.policy.rest.jpa.AddressGroup;
import org.onap.policy.rest.jpa.GroupServiceList;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PortList;
import org.onap.policy.rest.jpa.PrefixList;
import org.onap.policy.rest.jpa.ProtocolList;
import org.onap.policy.rest.jpa.ServiceList;
import org.onap.policy.rest.jpa.TermList;
import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;

@Component
public class FirewallConfigPolicy extends Policy {

    private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class);

    public FirewallConfigPolicy() {
        super();
    }

    private static CommonClassDao commonClassDao;

    @Autowired
    public FirewallConfigPolicy(CommonClassDao commonClassDao) {
        FirewallConfigPolicy.commonClassDao = commonClassDao;
    }

    public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
        this.policyAdapter = policyAdapter;
        this.policyAdapter.setConfigType(policyAdapter.getConfigType());
    }

    // Saving the Configurations file at server location for config policy.
    protected void saveConfigurations(String policyName, String jsonBody) {
        String configurationName = policyName;
        if (configurationName.endsWith(".xml")) {
            configurationName = configurationName.replace(".xml", "");
        }
        String fileName = CONFIG_HOME + File.separator + configurationName + ".json";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
            bw.write(jsonBody);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Configuration is succesfully saved");
            }
        } catch (IOException e) {
            LOGGER.error("Save of configuration to file" +fileName+ "failed",e);
        }
    }

   //Utility to read json data from the existing file to a string
    static String readFile(String path, Charset encoding) throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }

    @Override
    public Map<String, String> savePolicies() throws PAPException {
        Map<String, String> successMap = new HashMap<>();
        if(isPolicyExists()){
            successMap.put("EXISTS", "This Policy already exist on the PAP");
            return successMap;
        }
        if(!isPreparedToSave()){
            prepareToSave();
        }

        // Until here we prepared the data and here calling the method to create xml.
        Path newPolicyPath = null;
        newPolicyPath = Paths.get(policyAdapter.getNewFileName());
        Boolean dbIsUpdated = false;
        if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){
            if (policyAdapter.isEditPolicy()) {
                dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
            } else {
                try {
                    dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
                } catch (SQLException e) {
                    throw new PAPException(e);
                }
            }
        } else {
            dbIsUpdated = true;
        }

        if(dbIsUpdated) {
            successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
        } else {
            PolicyLogger.error("Failed to Update the Database Dictionary Tables.");

            //remove the new json file
            String jsonBody = policyAdapter.getPrevJsonBody();
            if (jsonBody!=null){
                saveConfigurations(policyName, jsonBody);
            } else {
                saveConfigurations(policyName, "");
            }
            successMap.put("fwdberror", "DB UPDATE");
        }

        return successMap;
    }

    //This is the method for preparing the policy for saving.  We have broken it out
    //separately because the fully configured policy is used for multiple things
    @Override
    public boolean prepareToSave() throws PAPException{

        if(isPreparedToSave()){
            //we have already done this
            return true;
        }

        int version = 0;
        String policyID = policyAdapter.getPolicyID();
        version = policyAdapter.getHighestVersion();

        // Create the Instance for pojo, PolicyType object is used in marshaling.
        if ("Config".equals(policyAdapter.getPolicyType())) {
            PolicyType policyConfig = new PolicyType();

            policyConfig.setVersion(Integer.toString(version));
            policyConfig.setPolicyId(policyID);
            policyConfig.setTarget(new TargetType());
            policyAdapter.setData(policyConfig);
        }
        policyName = policyAdapter.getNewFileName();

        //String oldPolicyName = policyName.replace(".xml", "");
        String scope = policyName.substring(0, policyName.indexOf('.'));
        String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", "");

        int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1));
        dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1);
        if(oldversion > 1){
            oldversion = oldversion - 1;
            dbPolicyName = dbPolicyName + oldversion + ".xml";
        }
        String createPolicyQuery = "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName";
        SimpleBindings params = new SimpleBindings();
        params.put("scope", scope);
        params.put("policyName", dbPolicyName);
        List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params);
        if (!createPolicyQueryList.isEmpty()) {
            PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0);
            policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody());
        }
        if (policyAdapter.getData() != null) {
            String jsonBody = policyAdapter.getJsonBody();
            saveConfigurations(policyName, jsonBody);

            // Make sure the filename ends with an extension
            if (!policyName.endsWith(".xml")) {
                policyName = policyName + ".xml";
            }

            PolicyType configPolicy = (PolicyType) policyAdapter.getData();

            configPolicy.setDescription(policyAdapter.getPolicyDescription());

            configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());

            AllOfType allOfOne = new AllOfType();
            String fileName = policyAdapter.getNewFileName();
            String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
            if ((name == null) || (name.equals(""))) {
                name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
            }
            allOfOne.getMatch().add(createMatch("PolicyName", name));
            AllOfType allOf = new AllOfType();

            // Match for ConfigName
            allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
            // Match for riskType
            allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
            // Match for riskLevel
            allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
            // Match for riskguard
            allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
            // Match for ttlDate
            allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
            AnyOfType anyOf = new AnyOfType();
            anyOf.getAllOf().add(allOfOne);
            anyOf.getAllOf().add(allOf);

            TargetType target = new TargetType();
            target.getAnyOf().add(anyOf);

            // Adding the target to the policy element
            configPolicy.setTarget(target);

            RuleType rule = new RuleType();
            rule.setRuleId(policyAdapter.getRuleID());
            rule.setEffect(EffectType.PERMIT);

            // Create Target in Rule
            AllOfType allOfInRule = new AllOfType();

            // Creating match for ACCESS in rule target
            MatchType accessMatch = new MatchType();
            AttributeValueType accessAttributeValue = new AttributeValueType();
            accessAttributeValue.setDataType(STRING_DATATYPE);
            accessAttributeValue.getContent().add("ACCESS");
            accessMatch.setAttributeValue(accessAttributeValue);
            AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
            URI accessURI = null;
            try {
                accessURI = new URI(ACTION_ID);
            } catch (URISyntaxException e) {
                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
            }
            accessAttributeDesignator.setCategory(CATEGORY_ACTION);
            accessAttributeDesignator.setDataType(STRING_DATATYPE);
            accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
            accessMatch.setAttributeDesignator(accessAttributeDesignator);
            accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);

            // Creating Config Match in rule Target
            MatchType configMatch = new MatchType();
            AttributeValueType configAttributeValue = new AttributeValueType();
            configAttributeValue.setDataType(STRING_DATATYPE);

            configAttributeValue.getContent().add("Config");

            configMatch.setAttributeValue(configAttributeValue);
            AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
            URI configURI = null;
            try {
                configURI = new URI(RESOURCE_ID);
            } catch (URISyntaxException e) {
                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
            }

            configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
            configAttributeDesignator.setDataType(STRING_DATATYPE);
            configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
            configMatch.setAttributeDesignator(configAttributeDesignator);
            configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);

            allOfInRule.getMatch().add(accessMatch);
            allOfInRule.getMatch().add(configMatch);

            AnyOfType anyOfInRule = new AnyOfType();
            anyOfInRule.getAllOf().add(allOfInRule);

            TargetType targetInRule = new TargetType();
            targetInRule.getAnyOf().add(anyOfInRule);

            rule.setTarget(targetInRule);
            rule.setAdviceExpressions(getAdviceExpressions(version, policyName));

            configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
            policyAdapter.setPolicyData(configPolicy);

        } else {
            PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
        }
        setPreparedToSave(true);
        return true;
    }

    // Data required for Advice part is setting here.
    private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {

        //Firewall Config ID Assignment
        AdviceExpressionsType advices = new AdviceExpressionsType();
        AdviceExpressionType advice = new AdviceExpressionType();
        advice.setAdviceId("firewallConfigID");
        advice.setAppliesTo(EffectType.PERMIT);
        // For Configuration
        AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
        assignment1.setAttributeId("type");
        assignment1.setCategory(CATEGORY_RESOURCE);
        assignment1.setIssuer("");
        AttributeValueType configNameAttributeValue = new AttributeValueType();
        configNameAttributeValue.setDataType(STRING_DATATYPE);
        configNameAttributeValue.getContent().add("Configuration");
        assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
        advice.getAttributeAssignmentExpression().add(assignment1);

        // For Config file Url if configurations are provided.
        //URL ID Assignment
        AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
        assignment2.setAttributeId("URLID");
        assignment2.setCategory(CATEGORY_RESOURCE);
        assignment2.setIssuer("");
        AttributeValueType AttributeValue = new AttributeValueType();
        AttributeValue.setDataType(URI_DATATYPE);
        if (policyName.endsWith(".xml")) {
            policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
        }
        String content = CONFIG_URL + "/Config/" + policyName + ".json";

        AttributeValue.getContent().add(content);
        assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
        advice.getAttributeAssignmentExpression().add(assignment2);

        //Policy Name Assignment
        AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
        assignment3.setAttributeId("PolicyName");
        assignment3.setCategory(CATEGORY_RESOURCE);
        assignment3.setIssuer("");
        AttributeValueType attributeValue3 = new AttributeValueType();
        attributeValue3.setDataType(STRING_DATATYPE);
        fileName = FilenameUtils.removeExtension(fileName);
        fileName = fileName + ".xml";
        String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
        if ((name == null) || (name.equals(""))) {
            name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
        }
        attributeValue3.getContent().add(name);
        assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
        advice.getAttributeAssignmentExpression().add(assignment3);

        //Version Number Assignment
        AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
        assignment4.setAttributeId("VersionNumber");
        assignment4.setCategory(CATEGORY_RESOURCE);
        assignment4.setIssuer("");
        AttributeValueType configNameAttributeValue4 = new AttributeValueType();
        configNameAttributeValue4.setDataType(STRING_DATATYPE);
        configNameAttributeValue4.getContent().add(Integer.toString(version));
        assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
        advice.getAttributeAssignmentExpression().add(assignment4);

        //Onap Name Assignment
        AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
        assignment5.setAttributeId("matching:" + ONAPID);
        assignment5.setCategory(CATEGORY_RESOURCE);
        assignment5.setIssuer("");
        AttributeValueType configNameAttributeValue5 = new AttributeValueType();
        configNameAttributeValue5.setDataType(STRING_DATATYPE);
        assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
        advice.getAttributeAssignmentExpression().add(assignment5);

        //Config Name Assignment
        AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
        assignment6.setAttributeId("matching:" + CONFIGID);
        assignment6.setCategory(CATEGORY_RESOURCE);
        assignment6.setIssuer("");
        AttributeValueType configNameAttributeValue6 = new AttributeValueType();
        configNameAttributeValue6.setDataType(STRING_DATATYPE);
        configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
        assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
        advice.getAttributeAssignmentExpression().add(assignment6);

        //Risk Attributes
        AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
        assignment7.setAttributeId("RiskType");
        assignment7.setCategory(CATEGORY_RESOURCE);
        assignment7.setIssuer("");

        AttributeValueType configNameAttributeValue7 = new AttributeValueType();
        configNameAttributeValue7.setDataType(STRING_DATATYPE);
        configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
        assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));

        advice.getAttributeAssignmentExpression().add(assignment7);

        AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
        assignment8.setAttributeId("RiskLevel");
        assignment8.setCategory(CATEGORY_RESOURCE);
        assignment8.setIssuer("");

        AttributeValueType configNameAttributeValue8 = new AttributeValueType();
        configNameAttributeValue8.setDataType(STRING_DATATYPE);
        configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
        assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));

        advice.getAttributeAssignmentExpression().add(assignment8);

        AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
        assignment9.setAttributeId("guard");
        assignment9.setCategory(CATEGORY_RESOURCE);
        assignment9.setIssuer("");

        AttributeValueType configNameAttributeValue9 = new AttributeValueType();
        configNameAttributeValue9.setDataType(STRING_DATATYPE);
        configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
        assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));

        advice.getAttributeAssignmentExpression().add(assignment9);

        AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
        assignment10.setAttributeId("TTLDate");
        assignment10.setCategory(CATEGORY_RESOURCE);
        assignment10.setIssuer("");

        AttributeValueType configNameAttributeValue10 = new AttributeValueType();
        configNameAttributeValue10.setDataType(STRING_DATATYPE);
        configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
        assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));

        advice.getAttributeAssignmentExpression().add(assignment10);
        advices.getAdviceExpression().add(advice);
        return advices;
    }


    private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
        CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
        JsonObject json = null;
        if (jsonBody != null) {

            //Read jsonBody to JsonObject
            json = stringToJson(jsonBody);

            JsonArray firewallRules = null;
            JsonArray serviceGroup = null;
            JsonArray addressGroup = null;
            //insert data into tables
            try {
                firewallRules = json.getJsonArray("firewallRuleList");
                serviceGroup = json.getJsonArray("serviceGroups");
                addressGroup = json.getJsonArray("addressGroups");
                /*
                 * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
                 */
                if (firewallRules != null) {
                    for(int i = 0;i<firewallRules.size();i++) {
                        /*
                         * Populate ArrayLists with values from the JSON
                         */
                        //create the JSON object from the JSON Array for each iteration through the for loop
                        JsonObject ruleListobj = firewallRules.getJsonObject(i);

                        //get values from JSON fields of firewallRulesList Array
                        String ruleName = ruleListobj.get("ruleName").toString();
                        String action = ruleListobj.get("action").toString();
                        String description = ruleListobj.get("description").toString();
                        List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
                        if(result != null && !result.isEmpty()){
                            TermList termEntry = (TermList) result.get(0);
                            dbConnection.delete(termEntry);
                        }

                        //getting fromZone Array field from the firewallRulesList
                        JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
                        String fromZoneString = null;

                        for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
                            String value = fromZoneArray.get(fromZoneIndex).toString();
                            value = value.replace("\"", "");
                            if (fromZoneString != null) {
                                fromZoneString = fromZoneString.concat(",").concat(value);
                            } else {
                                fromZoneString = value;
                            }
                        }
                        String fromZoneInsert = "'"+fromZoneString+"'";

                        //getting toZone Array field from the firewallRulesList
                        JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
                        String toZoneString = null;
                        for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
                            String value = toZoneArray.get(toZoneIndex).toString();
                            value = value.replace("\"", "");
                            if (toZoneString != null) {
                                toZoneString = toZoneString.concat(",").concat(value);
                            } else {
                                toZoneString = value;
                            }
                        }
                        String toZoneInsert = "'"+toZoneString+"'";

                        //getting sourceList Array fields from the firewallRulesList
                        JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
                        String srcListString = null;
                        for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
                            JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
                            String type = srcListObj.get("type").toString().replace("\"", "");

                            String value = null;
                            if(type.equals("REFERENCE")||type.equals("GROUP")){
                                value = srcListObj.get("name").toString();
                            } else if (type.equalsIgnoreCase("ANY")){
                                value = null;
                            } else {
                                value = srcListObj.get("value").toString();
                            }

                            srcListString = getLeftOrRight(srcListString, value);

                        }
                        String srcListInsert = "'"+srcListString+"'";

                        //getting destinationList Array fields from the firewallRulesList
                        JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
                        String destListString = null;
                        for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
                            JsonObject destListObj = destListArray.getJsonObject(destListIndex);
                            String type = destListObj.get("type").toString().replace("\"", "");

                            String value = null;
                            if(type.equals("REFERENCE")||type.equals("GROUP")){
                                value = destListObj.get("name").toString();
                            } else if (type.equalsIgnoreCase("ANY")){
                                value = null;
                            } else {
                                value = destListObj.get("value").toString();
                            }

                            destListString = getLeftOrRight(destListString, value);
                        }
                        String destListInsert = "'"+destListString+"'";

                        //getting destServices Array fields from the firewallRulesList
                        JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
                        String destPortListString = null;
                        for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
                            JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
                            String type = destServicesObj.get("type").toString().replace("\"", "");

                            String value = null;
                            if(type.equals("REFERENCE")||type.equals("GROUP")){
                                value = destServicesObj.get("name").toString();
                            } else if (type.equalsIgnoreCase("ANY")){
                                value = null;
                            } else {
                                value = destServicesObj.get("value").toString();
                            }

                            destPortListString = getLeftOrRight(destPortListString, value);
                        }
                        String destPortListInsert = "'"+destPortListString+"'";

                        /*
                         * Create Queries to INSERT data into database tables and execute
                         */
                        UserInfo userInfo = new UserInfo();
                        userInfo.setUserLoginId("API");
                        userInfo.setUserName("API");

                        TermList termEntry = new TermList();
                        termEntry.setTermName(ruleName);
                        termEntry.setSrcIPList(srcListInsert);
                        termEntry.setDestIPList(destListInsert);
                        termEntry.setProtocolList("null");
                        termEntry.setPortList("null");
                        termEntry.setSrcPortList("null");
                        termEntry.setDestPortList(destPortListInsert);
                        termEntry.setAction(action);
                        termEntry.setDescription(description);
                        termEntry.setFromZones(fromZoneInsert);
                        termEntry.setToZones(toZoneInsert);
                        termEntry.setUserCreatedBy(userInfo);
                        dbConnection.save(termEntry);

                        saveActionListToDb(dbConnection, action);
                    }
                }

                /*
                 * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
                 */
                if (serviceGroup != null) {
                    for(int i = 0; i < serviceGroup.size() ; i++) {
                        /*
                         * Populate ArrayLists with values from the JSON
                         */
                        //create the JSON object from the JSON Array for each iteration through the for loop
                        JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);

                        String serviceListName = svcGroupListobj.get("name").toString();
                        String description = null;
                        if (svcGroupListobj.containsKey("description")){
                            description = svcGroupListobj.get("description").toString();
                        }

                        //getting members Array from the serviceGroup
                        JsonArray membersArray = svcGroupListobj.getJsonArray("members");

                        //String type = svcGroupListobj.get("type").toString();
                        Boolean isServiceGroup = false;
                        if (membersArray!=null){
                            String membersType = membersArray.getJsonObject(0).get("type").toString();
                            if (membersType.contains("REFERENCE")) {
                                isServiceGroup = true;
                            }
                        }

                        //Insert values into GROUPSERVICELIST table if name begins with Group
                        if (isServiceGroup) {
                            saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray);
                        } else { //Insert JSON data serviceList table, protollist table, and portlist table
                            String type = svcGroupListobj.get("type").toString();
                            String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
                            String ports = svcGroupListobj.get("ports").toString();

                            /*
                             * Create Queries to INSERT data into database table and execute
                             */
                            saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports);

                            saveProtocolListToDb(dbConnection, transportProtocol);

                            savePortListToDb(dbConnection, ports);
                        }
                    }
                }

                /*
                 * Inserting addressGroup data into the ADDRESSGROUP table
                 */
                if (addressGroup != null) {
                    for(int i = 0; i < addressGroup.size(); i++) {
                        /*
                         * Populate ArrayLists with values from the JSON
                         */
                        //create the JSON object from the JSON Array for each iteration through the for loop
                        JsonObject addressGroupObj = addressGroup.getJsonObject(i);

                        //create JSON array for members
                        JsonArray membersArray = addressGroupObj.getJsonArray("members");
                        String addressGroupName = addressGroupObj.get("name").toString();

                        String description = null;
                        if (addressGroupObj.containsKey("description")){
                            description = addressGroupObj.get("description").toString();
                        }

                        String prefixIP = null;
                        String type = null;
                        for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
                            JsonObject membersObj = membersArray.getJsonObject(membersIndex);
                            //String value = membersObj.get("value").toString();
                            type = membersObj.get("type").toString().replace("\"", "");

                            String value = null;
                            prefixIP = getName(prefixIP, membersObj, type);
                        }
                        String prefixList = "'"+prefixIP+"'";

                        Boolean isAddressGroup = type.contains("REFERENCE");

                        if (isAddressGroup) {
                            saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
                        } else {
                            savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
                        }
                    }
                }
                removeDuplicateValuesFromLookup(dbConnection);
            }catch (Exception e) {
                PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
                return false;
            }
            return true;

        } else {
            return false;
        }

    }

    /*
     * Remove duplicate values from 'lookup' dictionary tables
     */
    private void removeDuplicateValuesFromLookup(CommonClassDaoImpl dbConnection) {
        String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
                + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
        dbConnection.updateQuery(protoDelete);

        //PortList Table
        String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
                + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
        dbConnection.updateQuery(portListDelete);

        //PrefixList Table
        String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
                + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
                + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
        dbConnection.updateQuery(prefixListDelete);

        //GroupServiceList
        String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
                + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
                + "groupservicelist.serviceList = g1.serviceList; ";
        dbConnection.updateQuery(groupServiceDelete);
    }

    private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) {
        String name = null;
        for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
            JsonObject membersObj = membersArray.getJsonObject(membersIndex);
            String type = membersObj.get("type").toString().replace("\"", "");

            name = getName(name, membersObj, type);
        }
        String nameInsert = "'"+name+"'";
        GroupServiceList groupServiceEntry = new GroupServiceList();
        groupServiceEntry.setGroupName(serviceListName);
        groupServiceEntry.setServiceList(nameInsert);
        dbConnection.save(groupServiceEntry);
    }

    private String getName(String name, JsonObject membersObj, String type) {
        String value;
        if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
            value = membersObj.get("name").toString();
        } else if (type.equalsIgnoreCase("ANY")){
            value = null;
        } else {
            value = membersObj.get("value").toString();
        }

        name = getLeftOrRight(name, value);
        return name;
    }

    private String getLeftOrRight(String name, String value) {
        if (value != null) {
            value = value.replace("\"", "");
        }

        if (name != null) {
            name = name.concat(",").concat(value);
        } else {
            name = value.replace("\"", "");;
        }
        return name;
    }


    private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
        CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
        JsonObject oldJson = null;
        JsonObject newJson = null;

        if (jsonBody != null || prevJsonBody != null) {

            oldJson = stringToJson(prevJsonBody);
            newJson = stringToJson(jsonBody);

            //if no changes to the json then return true
            if (oldJson != null && oldJson.equals(newJson)) {
                return true;
            }

            JsonArray firewallRules = null;
            JsonArray serviceGroup = null;
            JsonArray addressGroup = null;

            firewallRules = newJson.getJsonArray("firewallRuleList");
            serviceGroup = newJson.getJsonArray("serviceGroups");
            addressGroup = newJson.getJsonArray("addressGroups");

            //insert data into tables
            try {
                JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);

                for (int i = 0; i<jsonDiff.size(); i++) {
                    //String path = jsonDiff.get(i).asText();
                    String jsonpatch = jsonDiff.get(i).toString();

                    JsonObject patchObj = stringToJson(jsonpatch);

                    String path = patchObj.get("path").toString().replace('"', ' ').trim();

                    if (path.contains("firewallRuleList")) {
                        /*
                         * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
                         */
                        for(int ri = 0; ri < firewallRules.size(); ri++) {
                            /*
                             * Populate ArrayLists with values from the JSON
                             */
                            //create the JSON object from the JSON Array for each iteration through the for loop
                            JsonObject ruleListobj = firewallRules.getJsonObject(ri);

                            //get values from JSON fields of firewallRulesList Array
                            String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
                            String action = ruleListobj.get("action").toString().replace('"', '\'');
                            String description = ruleListobj.get("description").toString().replace('"', '\'');

                            List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
                            if(result != null && !result.isEmpty()){
                                TermList termEntry = (TermList) result.get(0);
                                dbConnection.delete(termEntry);
                            }

                            //getting fromZone Array field from the firewallRulesList
                            JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
                            String fromZoneString = null;

                            for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
                                String value = fromZoneArray.get(fromZoneIndex).toString();
                                value = value.replace("\"", "");

                                if (fromZoneString != null) {
                                    fromZoneString = fromZoneString.concat(",").concat(value);

                                } else {
                                    fromZoneString = value;
                                }

                            }
                            String fromZoneInsert = "'"+fromZoneString+"'";

                            //getting toZone Array field from the firewallRulesList
                            JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
                            String toZoneString = null;


                            for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
                                String value = toZoneArray.get(toZoneIndex).toString();
                                value = value.replace("\"", "");

                                if (toZoneString != null) {
                                    toZoneString = toZoneString.concat(",").concat(value);

                                } else {
                                    toZoneString = value;
                                }

                            }
                            String toZoneInsert = "'"+toZoneString+"'";
                            //getting sourceList Array fields from the firewallRulesList
                            JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
                            String srcListString = null;
                            for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
                                JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
                                String type = srcListObj.get("type").toString().replace("\"", "");

                                String value = null;
                                if(type.equals("REFERENCE")||type.equals("GROUP")){
                                    value = srcListObj.get("name").toString();
                                } else if (type.equalsIgnoreCase("ANY")){
                                    value = null;
                                } else {
                                    value = srcListObj.get("value").toString();
                                }

                                srcListString = getLeftOrRight(srcListString, value);

                            }
                            String srcListInsert = "'"+srcListString+"'";

                            //getting destinationList Array fields from the firewallRulesList
                            JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
                            String destListString = null;
                            for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
                                JsonObject destListObj = destListArray.getJsonObject(destListIndex);
                                String type = destListObj.get("type").toString().replace("\"", "");

                                String value = null;
                                if(type.equals("REFERENCE")||type.equals("GROUP")){
                                    value = destListObj.get("name").toString();
                                } else if (type.equalsIgnoreCase("ANY")){
                                    value = null;
                                } else {
                                    value = destListObj.get("value").toString();
                                }

                                destListString = getLeftOrRight(destListString, value);
                            }
                            String destListInsert = "'"+destListString+"'";

                            //getting destServices Array fields from the firewallRulesList
                            JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
                            String destPortListString = null;
                            for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
                                JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
                                String type = destServicesObj.get("type").toString().replace("\"", "");

                                String value = null;
                                if(type.equals("REFERENCE")||type.equals("GROUP")){
                                    value = destServicesObj.get("name").toString();
                                } else if (type.equalsIgnoreCase("ANY")){
                                    value = null;
                                } else {
                                    value = destServicesObj.get("value").toString();
                                }

                                destPortListString = getLeftOrRight(destPortListString, value);
                            }
                            String destPortListInsert = "'"+destPortListString+"'";

                            /*
                             * Create Queries to INSERT data into database tables and execute
                             */
                            UserInfo userInfo = new UserInfo();
                            userInfo.setUserLoginId("API");
                            userInfo.setUserName("API");

                            TermList termEntry = new TermList();
                            termEntry.setTermName(ruleName);
                            termEntry.setSrcIPList(srcListInsert);
                            termEntry.setDestIPList(destListInsert);
                            termEntry.setProtocolList("null");
                            termEntry.setPortList("null");
                            termEntry.setSrcPortList("null");
                            termEntry.setDestPortList(destPortListInsert);
                            termEntry.setAction(action);
                            termEntry.setDescription(description);
                            termEntry.setFromZones(fromZoneInsert);
                            termEntry.setToZones(toZoneInsert);
                            termEntry.setUserCreatedBy(userInfo);
                            dbConnection.save(termEntry);

                            List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action);
                            if(actionResult == null || actionResult.isEmpty()){
                                saveActionListToDb(dbConnection, action);
                            }
                        }
                    }

                    if (path.contains("serviceGroups")) {
                        /*
                         * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
                         */
                        for(int si = 0; si < serviceGroup.size(); si++) {
                            /*
                             * Populate ArrayLists with values from the JSON
                             */
                            //create the JSON object from the JSON Array for each iteration through the for loop
                            JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);

                            String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');

                            String description = null;
                            if (svcGroupListobj.containsKey("description")){
                                description = svcGroupListobj.get("description").toString().replace('"', '\'');
                            }

                            JsonArray membersArray = svcGroupListobj.getJsonArray("members");

                            Boolean isServiceGroup = false;
                            if (membersArray!=null){
                                String membersType = membersArray.getJsonObject(0).get("type").toString();
                                if (membersType.contains("REFERENCE")) {
                                    isServiceGroup = true;
                                }
                            }

                            //Insert values into GROUPSERVICELIST table if name begins with Group
                            if (isServiceGroup) {
                                List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName);
                                if(result != null && !result.isEmpty()){
                                    GroupServiceList groupEntry = (GroupServiceList) result.get(0);
                                    dbConnection.delete(groupEntry);
                                }

                                saveGroupServiceListTableToDb(dbConnection, groupName, membersArray);
                            } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
                                String type = svcGroupListobj.get("type").toString().replace('"', '\'');
                                String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
                                String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');

                                List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
                                if(result != null && !result.isEmpty()){
                                    ServiceList serviceEntry = (ServiceList) result.get(0);
                                    dbConnection.delete(serviceEntry);
                                }

                                saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports);

                                List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
                                if(protocolResult == null || protocolResult.isEmpty()){
                                    saveProtocolListToDb(dbConnection, transportProtocol);
                                }

                                List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
                                if(portResult == null || portResult.isEmpty()){
                                    savePortListToDb(dbConnection, ports);
                                }
                            }
                        }
                    }

                    if (path.contains("addressGroups")) {
                        /*
                         * Inserting addressGroup data into the ADDRESSGROUP table
                         */
                        for(int ai=0; ai < addressGroup.size() ; ai++) {

                            /*
                             * Populate ArrayLists with values from the JSON
                             */
                            //create the JSON object from the JSON Array for each iteration through the for loop
                            JsonObject addressGroupObj = addressGroup.getJsonObject(ai);

                            //create JSON array for members
                            JsonArray membersArray = addressGroupObj.getJsonArray("members");
                            String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');

                            String description = null;
                            if (addressGroupObj.containsKey("description")){
                                description = addressGroupObj.get("description").toString().replace('"', '\'');
                            }

                            String prefixIP = null;
                            String type = null;
                            for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
                                JsonObject membersObj = membersArray.getJsonObject(membersIndex);
                                type = membersObj.get("type").toString().replace("\"", "");

                                String value = null;
                                prefixIP = getName(prefixIP, membersObj, type);
                            }

                            String prefixList = "'"+prefixIP+"'";
                            Boolean isAddressGroup = type.contains("REFERENCE");

                            if (isAddressGroup) {
                                List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
                                if(result != null && !result.isEmpty()){
                                    AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
                                    dbConnection.delete(addressGroupEntry);
                                }
                                saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
                            } else {
                                List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
                                if(result != null && !result.isEmpty()){
                                    PrefixList prefixListEntry = (PrefixList) result.get(0);
                                    dbConnection.delete(prefixListEntry);
                                }
                                savePrefixListToDb(dbConnection, addressGroupName, description, prefixList);
                            }
                        }
                    }
                }
                removeDuplicateValuesFromLookup(dbConnection);
            }catch (Exception e) {
                PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
                return false;
            }
            return true;
        } else {
            return false;
        }

    }

    private void saveActionListToDb(CommonClassDaoImpl dbConnection, String action) {
        ActionList actionEntry = new ActionList();
        actionEntry.setActionName(action);
        actionEntry.setDescription(action);
        dbConnection.save(actionEntry);
    }

    private void savePortListToDb(CommonClassDaoImpl dbConnection, String ports) {
        PortList portEntry = new PortList();
        portEntry.setPortName(ports);
        portEntry.setDescription(ports);
        dbConnection.save(portEntry);
    }

    private void saveProtocolListToDb(CommonClassDaoImpl dbConnection, String transportProtocol) {
        ProtocolList protocolEntry = new ProtocolList();
        protocolEntry.setProtocolName(transportProtocol);
        protocolEntry.setDescription(transportProtocol);
        dbConnection.save(protocolEntry);
    }

    private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) {
        ServiceList serviceListEntry = new ServiceList();
        serviceListEntry.setServiceName(groupName);
        serviceListEntry.setServiceDescription(description);
        serviceListEntry.setServiceType(type);
        serviceListEntry.setServiceTransProtocol(transportProtocol);
        serviceListEntry.setServiceAppProtocol("null");
        serviceListEntry.setServicePorts(ports);
        dbConnection.save(serviceListEntry);
    }

    private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
        PrefixList newPrefixList = new PrefixList();
        newPrefixList.setPrefixListName(addressGroupName);
        newPrefixList.setDescription(description);
        newPrefixList.setPrefixListValue(prefixList);
        dbConnection.save(newPrefixList);
    }

    private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
        AddressGroup newAddressGroup = new AddressGroup();
        newAddressGroup.setGroupName(addressGroupName);
        newAddressGroup.setDescription(description);
        newAddressGroup.setServiceList(prefixList);
        dbConnection.save(newAddressGroup);
    }

    private JsonObject stringToJson(String jsonString) {
        //Read jsonBody to JsonObject
        StringReader in = new StringReader(jsonString);
        JsonReader jsonReader = Json.createReader(in);
        JsonObject json = jsonReader.readObject();
        jsonReader.close();
        return json;
    }

    private JsonNode createPatch(String json, String oldJson) {
        JsonNode oldJason = null;
        JsonNode updatedJason = null;

        try {
            oldJason = JsonLoader.fromString(oldJson);
            updatedJason = JsonLoader.fromString(json);
        } catch (IOException e) {
            LOGGER.error("Exception Occured"+e);
        }
        return JsonDiff.asJson(oldJason, updatedJason);
    }

    @Override
    public Object getCorrectPolicyDataObject() {
        return policyAdapter.getPolicyData();
    }

}