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