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