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