Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / FirewallConfigPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-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.openecomp.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.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.sql.Connection;
36 import java.sql.DriverManager;
37 import java.sql.ResultSet;
38 import java.sql.SQLException;
39 import java.sql.Statement;
40 import java.util.HashMap;
41 import java.util.Map;
42 import java.util.StringTokenizer;
43
44 import javax.json.Json;
45 import javax.json.JsonArray;
46 import javax.json.JsonException;
47 import javax.json.JsonObject;
48 import javax.json.JsonReader;
49 import javax.json.JsonString;
50 import javax.json.JsonValue;
51
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
65
66 import org.apache.commons.io.FilenameUtils;
67 import org.apache.commons.logging.Log;
68 import org.apache.commons.logging.LogFactory;
69 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
70 import org.openecomp.policy.rest.XACMLRestProperties;
71 import org.openecomp.policy.common.logging.eelf.MessageCodes;
72 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
73
74 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
75 import com.att.research.xacml.std.IdentifierImpl;
76 import com.att.research.xacml.util.XACMLProperties;
77 import com.fasterxml.jackson.databind.JsonNode;
78 import com.github.fge.jackson.JsonLoader;
79 import com.github.fge.jsonpatch.JsonPatch;
80 import com.github.fge.jsonpatch.diff.JsonDiff;
81 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
82 import org.openecomp.policy.common.logging.flexlogger.Logger; 
83
84 public class FirewallConfigPolicy extends Policy {
85         /**
86          * Config Fields
87          */
88         private static final Logger logger = FlexLogger.getLogger(FirewallConfigPolicy.class);
89
90         public static final String JSON_CONFIG = "JSON";
91         public static final String XML_CONFIG = "XML";
92         public static final String PROPERTIES_CONFIG = "PROPERTIES";
93         public static final String OTHER_CONFIG = "OTHER";
94         
95         /*
96          * These are the parameters needed for DB access from the PAP
97          */
98         private static String papDbDriver = null;
99         private static String papDbUrl = null;
100         private static String papDbUser = null;
101         private static String papDbPassword = null;
102
103         public FirewallConfigPolicy() {
104                 super();
105         }
106         
107         public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) {
108                 this.policyAdapter = policyAdapter;
109                 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
110                 
111         }
112         
113         // Saving the Configurations file at server location for config policy.
114         protected void saveConfigurations(String policyName, String prevPolicyName, String jsonBody) {
115                 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
116                 String policyDir = policyAdapter.getParentPath().toString();
117                 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
118                 policyDir = policyDir.substring(startIndex, policyDir.length());
119                 logger.info("print the main domain value"+policyDir);
120                 String path = policyDir.replace('\\', '.');
121                 if(path.contains("/")){
122                         path = policyDir.replace('/', '.');
123                         logger.info("print the path:" +path);
124                 }
125                 
126                 try {
127                         String configFileName = getConfigFile(policyName);
128                         
129                         File file;
130                         if(CONFIG_HOME.contains("\\"))
131                         {
132                          file = new File(CONFIG_HOME + "\\" + path + "."+ configFileName);
133                         }
134                         else
135                         {
136                          file = new File(CONFIG_HOME + "/" + path + "."+ configFileName);
137                         }
138                         
139                         // if file doesnt exists, then create it
140                         if (!file.exists()) {
141                                 file.createNewFile();
142                         }
143                         
144                         //Getting the previous policy Config Json file to be used for updating the dictionary tables
145                         if (policyAdapter.isEditPolicy()) {
146                                 
147                                 String prevConfigFileName = getConfigFile(prevPolicyName);
148                                 
149                                 File oldFile;
150                                 if(CONFIG_HOME.contains("\\"))
151                                 {
152                                         oldFile = new File(CONFIG_HOME + "\\" + path + "."+ prevConfigFileName);
153                                 }
154                                 else
155                                 {
156                                         oldFile = new File(CONFIG_HOME + "/" + path + "."+ prevConfigFileName);
157                                 }
158                                 
159                                 String filepath = oldFile.toString();
160                                 
161                                 String prevJsonBody = readFile(filepath, StandardCharsets.UTF_8);
162                                 policyAdapter.setPrevJsonBody(prevJsonBody);
163                         }
164
165
166                         File configHomeDir = new File(CONFIG_HOME);
167                         File[] listOfFiles = configHomeDir.listFiles();
168                         if (listOfFiles != null){
169                                 for(File eachFile : listOfFiles){
170                                         if(eachFile.isFile()){
171                                                 String fileNameWithoutExtension = FilenameUtils.removeExtension(eachFile.getName());
172                                                 String configFileNameWithoutExtension = FilenameUtils.removeExtension(configFileName);
173                                                 if (fileNameWithoutExtension.equals(configFileNameWithoutExtension)){
174                                                         //delete the file
175                                                         eachFile.delete();
176                                                 }
177                                         }
178                                 }
179                         }
180
181                         FileWriter fw = new FileWriter(file.getAbsoluteFile());
182                         BufferedWriter bw = new BufferedWriter(fw);
183                         bw.write(jsonBody);
184                         bw.close();
185                         if (logger.isDebugEnabled()) {
186                                 logger.debug("Configuration is succesfully saved");
187                         }
188                 } catch (IOException e) {
189                         e.printStackTrace();
190                 }
191         }
192         
193         //Utility to read json data from the existing file to a string
194         static String readFile(String path, Charset encoding) throws IOException {
195                 
196                 byte[] encoded = Files.readAllBytes(Paths.get(path));
197                 return new String(encoded, encoding);
198                 
199         }
200
201         // Here we are adding the extension for the configurations file based on the
202         // config type selection for saving.
203         private String getConfigFile(String filename) {
204                 filename = FilenameUtils.removeExtension(filename);
205                 if (filename.endsWith(".json")) {
206                         filename = filename.substring(0, filename.length() - 4);
207                 }
208
209                 filename=filename+".json";
210                 return filename;
211         }
212         
213         
214         // Validations for Config form
215         public boolean validateConfigForm() {
216
217                 // Validating mandatory Fields.
218                 isValidForm = true;     
219                 return isValidForm;
220
221         }
222
223         @Override
224         public Map<String, String> savePolicies() throws Exception {
225                 
226                 Map<String, String> successMap = new HashMap<String,String>();
227                 if(isPolicyExists()){
228                         successMap.put("EXISTS", "This Policy already exist on the PAP");
229                         return successMap;
230                 }
231                 
232                 if(!isPreparedToSave()){
233                         prepareToSave();
234                 }
235                 
236                 // Until here we prepared the data and here calling the method to create xml.
237                 Path newPolicyPath = null;
238                 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
239                 Boolean dbIsUpdated = false;
240                 if (policyAdapter.getApiflag().equalsIgnoreCase("admin")){
241                         dbIsUpdated = true;
242                 } else {
243                         if (policyAdapter.isEditPolicy()) {
244                                 dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
245                         } else {
246                                 dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
247                         }
248                 }
249                 
250                 if(dbIsUpdated) {
251                         successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() ); 
252                 } else {
253                         //TODO:EELF Cleanup - Remove logger
254                         //logger.error("Failed to Update the Database Dictionary Tables.");
255                         PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
256                         
257                         //remove the new json file 
258                         String jsonBody = policyAdapter.getPrevJsonBody();
259                         if (jsonBody!=null){
260                                 saveConfigurations(policyName, "", jsonBody);
261                         } else {
262                                 saveConfigurations(policyName, "", "");
263                         }
264                         successMap.put("fwdberror", "DB UPDATE");
265                 }
266
267                 if (successMap.containsKey("success")) {
268                         Path finalPolicyPath = getFinalPolicyPath();
269                         policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
270                 }
271                 return successMap;              
272         }
273
274         //This is the method for preparing the policy for saving.  We have broken it out
275         //separately because the fully configured policy is used for multiple things
276         @Override
277         public boolean prepareToSave() throws Exception{
278                 
279                 if(isPreparedToSave()){
280                         //we have already done this
281                         return true;
282                 }
283                 
284                 int version = 0;
285                 String policyID = policyAdapter.getPolicyID();
286
287                 if (policyAdapter.isEditPolicy()) {
288                         version = policyAdapter.getHighestVersion() + 1;
289                 } else {
290                         version = 1;
291                 }
292                 
293                 // Create the Instance for pojo, PolicyType object is used in marshalling.
294                 if (policyAdapter.getPolicyType().equals("Config")) {
295                         PolicyType policyConfig = new PolicyType();
296
297                         policyConfig.setVersion(Integer.toString(version));
298                         policyConfig.setPolicyId(policyID);
299                         policyConfig.setTarget(new TargetType());
300                         policyAdapter.setData(policyConfig);
301                 }
302
303                 if (policyAdapter.getData() != null) {
304         
305                         // Save off everything
306                         // making ready all the required elements to generate the action policy xml.
307                         // Get the uniqueness for policy name.
308                         String prevPolicyName = null;
309                         if(policyAdapter.isEditPolicy()){
310                                 prevPolicyName = "Config_FW_" + policyAdapter.getPolicyName() + "." + policyAdapter.getHighestVersion() + ".xml";
311                         }
312
313                         Path newFile = getNextFilename(Paths.get(policyAdapter.getParentPath().toString()),
314                                         (policyAdapter.getPolicyType() + "_FW"), policyAdapter.getPolicyName(), version);
315
316                         if (newFile == null) {
317                                 //TODO:EELF Cleanup - Remove logger
318                                 //logger.error("Policy already Exists, cannot create the policy.");
319                                 PolicyLogger.error("Policy already Exists, cannot create the policy.");
320                                 setPolicyExists(true);
321                                 return false;
322                         }
323                         policyName = newFile.getFileName().toString();
324
325                         String jsonBody = policyAdapter.getJsonBody();
326                         saveConfigurations(policyName, prevPolicyName, jsonBody);
327                         
328                         // Make sure the filename ends with an extension
329                         if (policyName.endsWith(".xml") == false) {
330                                 policyName = policyName + ".xml";
331                         }
332
333                         PolicyType configPolicy = (PolicyType) policyAdapter.getData();
334                         
335                         configPolicy.setDescription(policyAdapter.getPolicyDescription());
336
337                         configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
338
339                         AllOfType allOfOne = new AllOfType();
340                         File policyFilePath = new File(policyAdapter.getParentPath().toString(), policyName);
341                         String policyDir = policyFilePath.getParentFile().getName();
342                         String fileName = FilenameUtils.removeExtension(policyName);
343                         fileName = policyDir + "." + fileName + ".xml";
344                         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
345                         if ((name == null) || (name.equals(""))) {
346                                 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
347                         }
348                         allOfOne.getMatch().add(createMatch("PolicyName", name));
349                         AllOfType allOf = new AllOfType();
350                         
351                         // Match for ConfigName
352                         allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
353                         // Match for riskType
354                         allOf.getMatch().add(
355                                         createDynamicMatch("RiskType", policyAdapter.getRiskType()));
356                         // Match for riskLevel
357                         allOf.getMatch().add(
358                                         createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
359                         // Match for riskguard
360                         allOf.getMatch().add(
361                                         createDynamicMatch("guard", policyAdapter.getGuard()));
362                         // Match for ttlDate
363                         allOf.getMatch().add(
364                                         createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
365                         AnyOfType anyOf = new AnyOfType();
366                         anyOf.getAllOf().add(allOfOne);
367                         anyOf.getAllOf().add(allOf);
368
369                         TargetType target = new TargetType();
370                         ((TargetType) target).getAnyOf().add(anyOf);
371                         
372                         // Adding the target to the policy element
373                         configPolicy.setTarget((TargetType) target);
374
375                         RuleType rule = new RuleType();
376                         rule.setRuleId(policyAdapter.getRuleID());
377                         
378                         rule.setEffect(EffectType.PERMIT);
379                         
380                         // Create Target in Rule
381                         AllOfType allOfInRule = new AllOfType();
382                         
383                         // Creating match for ACCESS in rule target
384                         MatchType accessMatch = new MatchType();
385                         AttributeValueType accessAttributeValue = new AttributeValueType();
386                         accessAttributeValue.setDataType(STRING_DATATYPE);
387                         accessAttributeValue.getContent().add("ACCESS");
388                         accessMatch.setAttributeValue(accessAttributeValue);
389                         AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
390                         URI accessURI = null;
391                         try {
392                                 accessURI = new URI(ACTION_ID);
393                         } catch (URISyntaxException e) {
394                                 //TODO:EELF Cleanup - Remove logger
395                                 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
396                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
397                         }
398                         accessAttributeDesignator.setCategory(CATEGORY_ACTION);
399                         accessAttributeDesignator.setDataType(STRING_DATATYPE);
400                         accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
401                         accessMatch.setAttributeDesignator(accessAttributeDesignator);
402                         accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
403                         
404                         // Creating Config Match in rule Target
405                         MatchType configMatch = new MatchType();
406                         AttributeValueType configAttributeValue = new AttributeValueType();
407                         configAttributeValue.setDataType(STRING_DATATYPE);
408                         
409                         configAttributeValue.getContent().add("Config");
410                         
411                         configMatch.setAttributeValue(configAttributeValue);
412                         AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
413                         URI configURI = null;
414                         try {
415                                 configURI = new URI(RESOURCE_ID);
416                         } catch (URISyntaxException e) {
417                                 //TODO:EELF Cleanup - Remove logger
418                                 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
419                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
420                         }
421                         
422                         configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
423                         configAttributeDesignator.setDataType(STRING_DATATYPE);
424                         configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
425                         configMatch.setAttributeDesignator(configAttributeDesignator);
426                         configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
427
428                         allOfInRule.getMatch().add(accessMatch);
429                         allOfInRule.getMatch().add(configMatch);
430
431                         AnyOfType anyOfInRule = new AnyOfType();
432                         anyOfInRule.getAllOf().add(allOfInRule);
433                         
434                         TargetType targetInRule = new TargetType();
435                         targetInRule.getAnyOf().add(anyOfInRule);
436
437                         rule.setTarget(targetInRule);
438                         rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
439
440                         configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
441                         policyAdapter.setPolicyData(configPolicy);
442
443                 } else {
444                         //TODO:EELF Cleanup - Remove logger
445                         //logger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
446                         PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
447                 }
448                 setPreparedToSave(true);
449                 return true;
450         }
451
452         // Data required for Advice part is setting here.
453         private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
454                 
455                 //Firewall Config ID Assignment
456                 AdviceExpressionsType advices = new AdviceExpressionsType();
457                 AdviceExpressionType advice = new AdviceExpressionType();
458                 advice.setAdviceId("firewallConfigID");
459                 advice.setAppliesTo(EffectType.PERMIT);
460                 // For Configuration
461                 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
462                 assignment1.setAttributeId("type");
463                 assignment1.setCategory(CATEGORY_RESOURCE);
464                 assignment1.setIssuer("");
465                 AttributeValueType configNameAttributeValue = new AttributeValueType();
466                 configNameAttributeValue.setDataType(STRING_DATATYPE);
467                 configNameAttributeValue.getContent().add("Configuration");
468                 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
469                 advice.getAttributeAssignmentExpression().add(assignment1);
470                 
471                 // For Config file Url if configurations are provided.
472                 //URL ID Assignment
473                 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
474                 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
475                 assignment2.setAttributeId("URLID");
476                 assignment2.setCategory(CATEGORY_RESOURCE);
477                 assignment2.setIssuer("");
478                 AttributeValueType AttributeValue = new AttributeValueType();
479                 AttributeValue.setDataType(URI_DATATYPE);
480                 String policyDir1 = policyAdapter.getParentPath().toString();
481                 int startIndex1 = policyDir1.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
482                 policyDir1 = policyDir1.substring(startIndex1, policyDir1.length());
483                 logger.info("print the main domain value"+policyDir1);
484                 String path = policyDir1.replace('\\', '.');
485                 if(path.contains("/")){
486                         path = policyDir1.replace('/', '.');
487                         logger.info("print the path:" +path);
488                 }               
489                 String content = CONFIG_URL + "/Config/" + path + "." + getConfigFile(policyName);
490
491                 AttributeValue.getContent().add(content);
492                 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
493                 advice.getAttributeAssignmentExpression().add(assignment2);
494                 
495                 //Policy Name Assignment
496                 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
497                 assignment3.setAttributeId("PolicyName");
498                 assignment3.setCategory(CATEGORY_RESOURCE);
499                 assignment3.setIssuer("");
500                 AttributeValueType attributeValue3 = new AttributeValueType();
501                 attributeValue3.setDataType(STRING_DATATYPE);
502                 String policyDir = policyAdapter.getParentPath().toString();
503                 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
504                 policyDir = policyDir.substring(startIndex, policyDir.length());
505                 StringTokenizer tokenizer = null;
506                 StringBuffer buffer = new StringBuffer();
507                 if (policyDir.contains("\\")) {
508                         tokenizer = new StringTokenizer(policyDir, "\\");
509                 } else {
510                         tokenizer = new StringTokenizer(policyDir, "/");
511                         }
512                 if (tokenizer != null) {
513                         while (tokenizer.hasMoreElements()) {
514                                 String value = tokenizer.nextToken();
515                                 buffer.append(value);
516                                 buffer.append(".");
517                         }
518                 }
519                 fileName = FilenameUtils.removeExtension(fileName);
520                 fileName = buffer.toString() + fileName + ".xml";
521                 System.out.println(fileName);
522                 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
523                 if ((name == null) || (name.equals(""))) {
524                         name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
525                 }
526                 System.out.println(name);
527                 attributeValue3.getContent().add(name);
528                 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
529                 advice.getAttributeAssignmentExpression().add(assignment3);
530                 
531                 //Version Number Assignment
532                 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
533                 assignment4.setAttributeId("VersionNumber");
534                 assignment4.setCategory(CATEGORY_RESOURCE);
535                 assignment4.setIssuer("");
536                 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
537                 configNameAttributeValue4.setDataType(STRING_DATATYPE);
538                 configNameAttributeValue4.getContent().add(Integer.toString(version));
539                 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
540                 advice.getAttributeAssignmentExpression().add(assignment4);
541                 
542                 //Ecomp Name Assignment
543                 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
544                 assignment5.setAttributeId("matching:" + this.ECOMPID);
545                 assignment5.setCategory(CATEGORY_RESOURCE);
546                 assignment5.setIssuer("");
547                 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
548                 configNameAttributeValue5.setDataType(STRING_DATATYPE);
549                 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
550                 advice.getAttributeAssignmentExpression().add(assignment5);
551                 
552                 //Config Name Assignment
553                 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
554                 assignment6.setAttributeId("matching:" + this.CONFIGID);
555                 assignment6.setCategory(CATEGORY_RESOURCE);
556                 assignment6.setIssuer("");
557                 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
558                 configNameAttributeValue6.setDataType(STRING_DATATYPE);
559                 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
560                 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
561                 advice.getAttributeAssignmentExpression().add(assignment6);
562
563                 //Risk Attributes
564                 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
565                 assignment7.setAttributeId("RiskType");
566                 assignment7.setCategory(CATEGORY_RESOURCE);
567                 assignment7.setIssuer("");
568
569                 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
570                 configNameAttributeValue7.setDataType(STRING_DATATYPE);
571                 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
572                 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
573
574                 advice.getAttributeAssignmentExpression().add(assignment7);
575                                 
576                 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
577                 assignment8.setAttributeId("RiskLevel");
578                 assignment8.setCategory(CATEGORY_RESOURCE);
579                 assignment8.setIssuer("");
580
581                 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
582                 configNameAttributeValue8.setDataType(STRING_DATATYPE);
583                 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
584                 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
585
586                 advice.getAttributeAssignmentExpression().add(assignment8);     
587
588                 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
589                 assignment9.setAttributeId("guard");
590                 assignment9.setCategory(CATEGORY_RESOURCE);
591                 assignment9.setIssuer("");
592
593                 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
594                 configNameAttributeValue9.setDataType(STRING_DATATYPE);
595                 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
596                 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
597
598                 advice.getAttributeAssignmentExpression().add(assignment9);
599                                 
600                 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
601                 assignment10.setAttributeId("TTLDate");
602                 assignment10.setCategory(CATEGORY_RESOURCE);
603                 assignment10.setIssuer("");
604
605                 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
606                 configNameAttributeValue10.setDataType(STRING_DATATYPE);
607                 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
608                 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
609
610                 advice.getAttributeAssignmentExpression().add(assignment10);
611                 
612                 int index = 0;
613
614                 advices.getAdviceExpression().add(advice);
615                 return advices;
616         }
617         
618         
619         private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
620
621                 
622                 JsonObject json = null;
623                 if (jsonBody != null) {
624                         
625                         //Read jsonBody to JsonObject
626                         json = stringToJson(jsonBody);
627                         
628                         JsonArray firewallRules = null;
629                         JsonArray serviceGroup = null;
630                         JsonArray addressGroup = null;
631                         String securityZone=null;
632                         
633                         Connection con = null;
634                         Statement st = null;
635                         ResultSet rs = null;
636                         
637                         /*
638                          * Retrieve the property values for db access from the xacml.pap.properties
639                          */
640                         papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
641                         papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
642                         papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
643                         papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
644
645                         //insert data into tables
646                         try {
647                                 //Get DB Connection
648                                 Class.forName(papDbDriver);
649                                 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
650                                 st = con.createStatement();
651                                 
652                                 firewallRules = json.getJsonArray("firewallRuleList");
653                                 serviceGroup = json.getJsonArray("serviceGroups");
654                                 addressGroup = json.getJsonArray("addressGroups");      
655                                 securityZone=json.getString("primaryParentZoneId").toString();
656                                 
657                                 logger.info("Parent child: securityZone from JSON: "+securityZone);
658                                 String insertQuery = null;
659                                 
660                                 //Inserting childPolicy and its parent to the FWChildToParent DB table
661                                 if(securityZone!=null){
662                                         //Its a child Policy. 
663                                         //Retrieve the parent name from the securityZone Id
664                                         String retrieveParentQuery= "select parent from fwparent where securityZone='";
665                                         
666                                         retrieveParentQuery=retrieveParentQuery+securityZone+"';";
667                                         logger.info("Parent child: Query to retrieve parent "+retrieveParentQuery);
668                                         rs = st.executeQuery(retrieveParentQuery);
669                                         
670                                         String parent=null;
671                                         if(rs.next()){
672                                                 parent = rs.getString("parent");
673                                         }
674                                         rs.close();
675                                         
676                                         
677                                         String insertQueryChildTable="INSERT INTO FWChildToParent(child, parent) VALUES ('";
678                                         insertQueryChildTable=insertQueryChildTable+policyAdapter.getPolicyName()+"','"+parent+"');";
679                                         logger.info("Parent child: Insert child and parent to DB: "+insertQueryChildTable);
680                                         st.executeUpdate(insertQueryChildTable);
681                                         
682                                 }
683                                 
684                                 /*
685                                  * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
686                                  */
687                                 if (firewallRules != null) {
688                                         
689                                         int termID = 0;
690                                         int zoneID = 0;
691                                         int actionID = 0;
692                                         
693                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
694                                         if(rs.next()){
695                                                 termID = rs.getInt("ID");
696                                         }
697                                         rs.close();
698                                         
699                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
700                                         if(rs.next()){
701                                                 zoneID = rs.getInt("ID");
702                                         }
703                                         rs.close();
704                                         
705                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
706                                         if(rs.next()){
707                                                 actionID = rs.getInt("ID");
708                                         }
709                                         rs.close();
710                                         
711                                         int i = 0;
712                                         for(JsonValue jsonValue : firewallRules) {
713                                                 
714                                                 //increment ID Primary Keys
715                                                 termID = termID + 1;
716                                                 zoneID = zoneID + 1;
717                                                 actionID = actionID + 1;
718                                                 
719                                                 /*
720                                                  * Populate ArrayLists with values from the JSON
721                                                  */
722                                                 //create the JSON object from the JSON Array for each iteration through the for loop
723                                                 JsonObject ruleListobj = firewallRules.getJsonObject(i);
724                                                                                                 
725                                                 //get values from JSON fields of firewallRulesList Array
726                                                 String ruleName = ruleListobj.get("ruleName").toString();
727                                                 String action = ruleListobj.get("action").toString();
728                                                 String description = ruleListobj.get("description").toString();
729                                                 
730                                                 rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
731                                                 
732                                                 if (rs.next()) {
733                                                         st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
734                                                 }
735                                                 rs.close();
736                                                 
737                                                 //getting fromZone Array field from the firewallRulesList
738                                                 JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
739                                                 String fromZoneString = null;
740                                                 
741                                                 int fromZoneIndex = 0;
742                                                 for (JsonValue fromZoneJsonValue : fromZoneArray) {
743                                                         String value = fromZoneArray.get(fromZoneIndex).toString();
744                                                         value = value.replace("\"", "");
745                                                         
746                                                         if (fromZoneString != null) {
747                                                                 fromZoneString = fromZoneString.concat(",").concat(value);
748                                                                 
749                                                         } else {
750                                                                 fromZoneString = value;
751                                                         }
752                                                         
753                                                         fromZoneIndex++;
754                                                         
755                                                 }
756                                                 String fromZoneInsert = "'"+fromZoneString+"'";
757                                                 
758                                                 //getting toZone Array field from the firewallRulesList
759                                                 JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
760                                                 String toZoneString = null;
761                                                 
762                                                 int toZoneIndex = 0;
763                                                 for (JsonValue toZoneJsonValue : toZoneArray) {
764                                                         String value = toZoneArray.get(toZoneIndex).toString();
765                                                         value = value.replace("\"", "");
766                                                         
767                                                         if (toZoneString != null) {
768                                                                 toZoneString = toZoneString.concat(",").concat(value);
769                                                                 
770                                                         } else {
771                                                                 toZoneString = value;
772                                                         }
773                                                         
774                                                         toZoneIndex++;
775                                                         
776                                                 }
777                                                 String toZoneInsert = "'"+toZoneString+"'";
778                                                 
779                                                 //getting sourceList Array fields from the firewallRulesList
780                                                 JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
781                                                 String srcListString = null;
782                                                 
783                                                 int srcListIndex = 0;
784                                                 for (JsonValue srcListJsonValue : srcListArray) {
785                                                         JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
786                                                         String type = srcListObj.get("type").toString().replace("\"", "");
787                                                         
788                                                         String value = null;
789                                                         if(type.equals("REFERENCE")||type.equals("GROUP")){
790                                                                 value = srcListObj.get("name").toString();
791                                                         } else if (type.equalsIgnoreCase("ANY")){
792                                                                 value = null;
793                                                         } else {
794                                                                 value = srcListObj.get("value").toString();
795                                                         }
796                                                         
797                                                         if (value!=null){
798                                                                 value = value.replace("\"", "");
799                                                         }
800                                                         
801                                                         if (srcListString != null) {
802                                                                 srcListString = srcListString.concat(",").concat(value);
803                                                                 
804                                                         } else {
805                                                                 srcListString = value;
806                                                         }
807                                                         
808                                                         srcListIndex++;
809                                                         
810                                                 }
811                                                 String srcListInsert = "'"+srcListString+"'";
812                                                 
813                                                 //getting destinationList Array fields from the firewallRulesList
814                                                 JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
815                                                 String destListString = null;
816                                                 
817                                                 int destListIndex = 0;
818                                                 for (JsonValue destListJsonValue : destListArray) {
819                                                         JsonObject destListObj = destListArray.getJsonObject(destListIndex);
820                                                         String type = destListObj.get("type").toString().replace("\"", "");
821                                                         
822                                                         String value = null;
823                                                         if(type.equals("REFERENCE")||type.equals("GROUP")){
824                                                                 value = destListObj.get("name").toString();
825                                                         } else if (type.equalsIgnoreCase("ANY")){
826                                                                 value = null;
827                                                         } else {
828                                                                 value = destListObj.get("value").toString();
829                                                         }
830                                                         
831                                                         if (value!=null){
832                                                                 value = value.replace("\"", "");
833                                                         }
834                                                         
835                                                         if (destListString != null) {
836                                                                 destListString = destListString.concat(",").concat(value);
837                                                         } else {
838                                                                 destListString = value;
839                                                         }
840                                                         
841                                                         destListIndex++;
842                                                 }
843                                                 String destListInsert = "'"+destListString+"'";
844                                                 
845                                                 //getting destServices Array fields from the firewallRulesList
846                                                 JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
847                                                 String destPortListString = null;
848                                                 
849                                                 int destPortListIndex = 0;
850                                                 for (JsonValue destListJsonValue : destServicesArray) {
851                                                         JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
852                                                         String type = destServicesObj.get("type").toString().replace("\"", "");
853                                                         
854                                                         String value = null;
855                                                         if(type.equals("REFERENCE")||type.equals("GROUP")){
856                                                                 value = destServicesObj.get("name").toString();
857                                                         } else if (type.equalsIgnoreCase("ANY")){
858                                                                 value = null;
859                                                         } else {
860                                                                 value = destServicesObj.get("value").toString();
861                                                         }
862                                                         
863                                                         if (value!=null){
864                                                                 value = value.replace("\"", "");
865                                                         }
866                                                         
867                                                         if (destPortListString != null) {
868                                                                 destPortListString = destPortListString.concat(",").concat(value);
869                                                         } else {
870                                                                 destPortListString = value;
871                                                         }
872                                                         
873                                                         destPortListIndex++;
874                                                 }
875                                                 String destPortListInsert = "'"+destPortListString+"'";                                 
876                                                 
877                                                 /*
878                                                  * Create Queries to INSERT data into database tables and execute 
879                                                  */                                     
880                         String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
881                                  + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
882                                  +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
883                                  +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
884                                                 termSql = termSql.replace('"', '\'');
885                                                 st.addBatch(termSql);
886
887                                                 String actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+"); ";
888                                                 actionSql = actionSql.replace('"', '\'');
889                                                 st.addBatch(actionSql);
890                                                 
891                                                 st.executeBatch();
892                                                 
893                                                 i++;
894                                         }
895                                         
896                                 }
897                                 
898                                 /*
899                                  * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
900                                  */
901                                 if (serviceGroup != null) {
902                                         
903                                         int serviceGroupID = 0;
904                                         int serviceListID = 0;
905                                         int protocolID = 0;
906                                         int portID = 0;
907
908                                         
909                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
910                                         if(rs.next()){
911                                                 serviceGroupID = rs.getInt("ID");
912                                         }
913                                         rs.close();
914                                         
915                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
916                                         if(rs.next()){
917                                                 serviceListID = rs.getInt("ID");
918                                         }
919                                         rs.close();
920                                         
921                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
922                                         if(rs.next()){
923                                                 protocolID = rs.getInt("ID");
924                                         }
925                                         rs.close();
926                                         
927                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
928                                         if(rs.next()){
929                                                 portID = rs.getInt("ID");
930                                         }
931                                         rs.close();
932                                         
933                                         int i = 0;
934                                         for(JsonValue jsonValue : serviceGroup) {
935                                                 
936                                                 /*
937                                                  * Populate ArrayLists with values from the JSON
938                                                  */
939                                                 //create the JSON object from the JSON Array for each iteration through the for loop
940                                                 JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
941                                                                                                 
942                                                 String serviceListName = svcGroupListobj.get("name").toString();
943                                                 
944                                                 String description = null;
945                                                 if (svcGroupListobj.containsKey("description")){
946                                                         description = svcGroupListobj.get("description").toString();
947                                                 }
948                                                 
949                                                 //getting members Array from the serviceGroup
950                                                 JsonArray membersArray = svcGroupListobj.getJsonArray("members");
951
952                                                 //String type = svcGroupListobj.get("type").toString();
953                                                 Boolean isServiceGroup = false;
954                                                 if (membersArray!=null){
955                                                         String membersType = membersArray.getJsonObject(0).get("type").toString();
956                                                         if (membersType.contains("REFERENCE")) {
957                                                                 isServiceGroup = true;
958                                                         }
959                                                 }
960                                                                                                 
961                                                 //Insert values into GROUPSERVICELIST table if name begins with Group 
962                                                 if (isServiceGroup) {
963                                                         
964                                                         //increment ID Primary Keys
965                                                         serviceListID = serviceListID + 1;
966
967                                                         String name = null;
968                                                         
969                                                         int membersIndex = 0;
970                                                         for (JsonValue membersValue : membersArray) {
971                                                                 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
972                                                                 //String value = membersObj.get("name").toString();
973                                                                 String type = membersObj.get("type").toString().replace("\"", "");
974                                                                 
975                                                                 String value = null;
976                                                                 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
977                                                                         value = membersObj.get("name").toString();
978                                                                 } else if (type.equalsIgnoreCase("ANY")){
979                                                                         value = null;
980                                                                 } else {
981                                                                         value = membersObj.get("value").toString();
982                                                                 }
983                                                                 
984                                                                 if(value != null){
985                                                                         value = value.replace("\"", "");
986                                                                 }
987                                                                 
988                                                                 if (name != null) {
989                                                                         name = name.concat(",").concat(value);
990                                                                 } else {
991                                                                         name = value;
992                                                                 }
993                                                                 
994                                                                 membersIndex++;
995                                                         }
996                                                         String nameInsert = "'"+name+"'";               
997                                                         
998                                                         insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
999                                                                         + "VALUES("+serviceListID+","+serviceListName+","+nameInsert+")";
1000                                                         
1001                                                         //Replace double quote with single quote
1002                                                         insertQuery = insertQuery.replace('"', '\'');
1003                                                         
1004                                                         //Execute the queries to Insert data
1005                                             st.executeUpdate(insertQuery);
1006                                                                                                         
1007                                                 } else { //Insert JSON data serviceList table, protollist table, and portlist table
1008
1009                                                         //increment ID Primary Keys
1010                                                         protocolID = protocolID + 1;
1011                                                         portID = portID + 1;
1012                                                         serviceGroupID = serviceGroupID + 1;
1013                                                         
1014                                                         String type = svcGroupListobj.get("type").toString();
1015                                                         String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
1016                                                         String ports = svcGroupListobj.get("ports").toString();
1017                                                         
1018                                                         /*
1019                                                          * Create Queries to INSERT data into database table and execute 
1020                                                          */
1021                                                         String serviceSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
1022                                                                         + "VALUES("+serviceGroupID+","+serviceListName+","+description+","+type+","
1023                                                                         + transportProtocol+","+"null,"+ports+"); ";
1024                                                         serviceSql = serviceSql.replace('"', '\'');
1025                                                         st.addBatch(serviceSql);
1026                                                         
1027                                                         String protSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
1028                                                         protSql = protSql.replace('"', '\'');
1029                                                         st.addBatch(protSql);
1030                                                         
1031                                                         String portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+");";
1032                                                         portSql = portSql.replace('"', '\'');
1033                                                         st.addBatch(portSql);
1034                                                         
1035                                                         st.executeBatch();
1036
1037                                                 }               
1038                                                 
1039                                                 
1040                                                 
1041                                                 i++;
1042                                         }
1043                                 }
1044                                 
1045                                 /*
1046                                  * Inserting addressGroup data into the ADDRESSGROUP table
1047                                  */
1048                                 if (addressGroup != null) {
1049                                         int prefixID = 0;
1050                                         int addressID = 0;
1051                                         
1052                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
1053                                         if(rs.next()){
1054                                                 prefixID = rs.getInt("ID");
1055                                         }
1056                                         rs.close();
1057                                         
1058                                         rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
1059                                         if(rs.next()){
1060                                                 addressID = rs.getInt("ID");
1061                                         }
1062                                         rs.close();
1063                                         
1064                                         
1065                                         int i = 0;
1066                                         for(JsonValue jsonValue : addressGroup) {
1067                                                 
1068                                                 /*
1069                                                  * Populate ArrayLists with values from the JSON
1070                                                  */
1071                                                 //create the JSON object from the JSON Array for each iteration through the for loop
1072                                                 JsonObject addressGroupObj = addressGroup.getJsonObject(i);
1073                                                 
1074                                                 //create JSON array for members
1075                                                 JsonArray membersArray = addressGroupObj.getJsonArray("members");
1076                                                 String addressGroupName = addressGroupObj.get("name").toString();
1077                                                 
1078                                                 String description = null;
1079                                                 if (addressGroupObj.containsKey("description")){
1080                                                         description = addressGroupObj.get("description").toString();
1081                                                 }
1082                                                 
1083                                                 String prefixIP = null;
1084                                                 String type = null;
1085                                                 
1086                                                 int membersIndex = 0;
1087                                                 for (JsonValue membersValue : membersArray) {
1088                                                         JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1089                                                         //String value = membersObj.get("value").toString();
1090                                                         type = membersObj.get("type").toString().replace("\"", "");
1091                                                         
1092                                                         String value = null;
1093                                                         if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1094                                                                 value = membersObj.get("name").toString();
1095                                                         } else if (type.equalsIgnoreCase("ANY")){
1096                                                                 value = null;
1097                                                         } else {
1098                                                                 value = membersObj.get("value").toString();
1099                                                         }
1100                                                         
1101                                                         if(value != null){
1102                                                                 value = value.replace("\"", "");
1103                                                         }
1104                                                         
1105                                                         if (prefixIP != null) {
1106                                                                 prefixIP = prefixIP.concat(",").concat(value);
1107                                                         } else {
1108                                                                 prefixIP = value;
1109                                                         }
1110                                                         
1111                                                         membersIndex++;
1112                                                 }
1113                                                 String prefixList = "'"+prefixIP+"'";
1114                                                 
1115                                                 Boolean isAddressGroup = type.contains("REFERENCE");
1116                                                 
1117                                                 if (isAddressGroup) {                                                           
1118                                                         //increment ID Primary Keys
1119                                                         addressID = addressID + 1;
1120                                                         
1121                                                         insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
1122                                                                                 + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";  
1123                                                 } else {
1124                                                          //increment ID Primary Key
1125                                                         prefixID = prefixID + 1;
1126                                                         
1127                                                         insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
1128                                                                                 + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
1129                                                         
1130                                                 }
1131                 
1132                                                 
1133                                                 //Replace double quote with single quote
1134                                                 insertQuery = insertQuery.replace('"', '\'');
1135                                                 
1136                                                 //Execute the queries to Insert data
1137                                     st.executeUpdate(insertQuery);
1138                                                 
1139                                                 i++;
1140                                         }
1141                                         
1142                                 }
1143                                 
1144                                 /*
1145                                  * Remove duplicate values from 'lookup' dictionary tables
1146                                  */
1147                                 //ProtocolList Table
1148                                 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1149                                                 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1150                                 st.addBatch(protoDelete);
1151                                 
1152                                 //PortList Table
1153                                 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1154                                                 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1155                                 st.addBatch(portListDelete);
1156                                 
1157                                 //PrefixList Table
1158                                 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1159                                                 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1160                                                 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1161                                 st.addBatch(prefixListDelete);
1162                                 
1163                                 //GroupServiceList
1164                                 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1165                                                 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1166                                                 + "groupservicelist.serviceList = g1.serviceList; ";
1167                                 st.addBatch(groupServiceDelete);
1168                                 
1169                                 st.executeBatch();
1170                                 
1171                         } catch (ClassNotFoundException e) {
1172                                 //TODO:EELF Cleanup - Remove logger
1173                                 //logger.error(e.getMessage());
1174                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries ");
1175                                 System.out.println(e.getMessage());
1176                                 return false;
1177         
1178                         } catch (SQLException e) {
1179                                 //TODO:EELF Cleanup - Remove logger
1180                                 //logger.error(e.getMessage());
1181                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1182                                 System.out.println(e.getMessage());
1183                                 return false;
1184                         } catch (Exception e) {
1185                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
1186                                 System.out.println(e.getMessage());
1187                                 return false;
1188                         } finally {
1189                                 try{
1190                                         if (con!=null) con.close();
1191                                         if (rs!=null) rs.close();
1192                                         if (st!=null) st.close();
1193                                 } catch (Exception ex){}
1194                         }
1195                         return true;
1196
1197                 } else {
1198                         return false;
1199                 }
1200                 
1201         }
1202
1203
1204         private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
1205                 
1206                 JsonObject oldJson = null;
1207                 JsonObject newJson = null;
1208                 
1209                 if (jsonBody != null || prevJsonBody != null) {
1210                         
1211                         oldJson = stringToJson(prevJsonBody);
1212                         newJson = stringToJson(jsonBody);
1213                         
1214                         //if no changes to the json then return true
1215                         if (oldJson.equals(newJson)) {
1216                                 return true;
1217                         }
1218                         
1219                         JsonArray firewallRules = null;
1220                         JsonArray serviceGroup = null;
1221                         JsonArray addressGroup = null;
1222                         
1223                         firewallRules = newJson.getJsonArray("firewallRuleList");
1224                         serviceGroup = newJson.getJsonArray("serviceGroups");
1225                         addressGroup = newJson.getJsonArray("addressGroups");   
1226                         
1227                         Connection con = null;
1228                         Statement st = null;
1229                         ResultSet rs = null;
1230                         
1231                         /*
1232                          * Retrieve the property values for db access from the xacml.pap.properties
1233                          */
1234                         papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
1235                         papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
1236                         papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
1237                         papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
1238         
1239                         //insert data into tables
1240                         try {
1241                                 
1242                                 //Get DB Connection
1243                                 Class.forName(papDbDriver);
1244                                 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
1245                                 st = con.createStatement();
1246                                 
1247                                 JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
1248                                 
1249                                 int i = 0;
1250                                 for (JsonNode node : jsonDiff) {
1251                                         //String path = jsonDiff.get(i).asText();
1252                                         String jsonpatch = jsonDiff.get(i).toString();
1253                                         
1254                                         JsonObject patchObj = stringToJson(jsonpatch);
1255                                         
1256                                         String path = patchObj.get("path").toString().replace('"', ' ').trim();
1257                                                                                 
1258                                         if (path.contains("firewallRuleList")) {
1259                                                 int termID = 0;
1260                                                 int zoneID = 0;
1261                                                 int actionID = 0;
1262                                                 
1263                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;");
1264                                                 if(rs.next()){
1265                                                         termID = rs.getInt("ID");
1266                                                 }
1267                                                 rs.close();
1268                                                 
1269                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;");
1270                                                 if(rs.next()){
1271                                                         zoneID = rs.getInt("ID");
1272                                                 }
1273                                                 rs.close();
1274                                                 
1275                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;");
1276                                                 if(rs.next()){
1277                                                         actionID = rs.getInt("ID");
1278                                                 }
1279                                                 rs.close();
1280                                                 
1281                                                 String insertQuery = null;
1282                                                 
1283                                                 /*
1284                                                  * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
1285                                                  */
1286                                                 int ri = 0;
1287                                                 for(JsonValue jsonValue : firewallRules) {
1288                                                         
1289                                                         //increment ID Primary Keys
1290                                                         termID = termID + 1;
1291                                                         zoneID = zoneID + 1;
1292                                                         actionID = actionID + 1;
1293                                                         
1294                                                         /*
1295                                                          * Populate ArrayLists with values from the JSON
1296                                                          */
1297                                                         //create the JSON object from the JSON Array for each iteration through the for loop
1298                                                         JsonObject ruleListobj = firewallRules.getJsonObject(ri);
1299                                                         
1300                                                         //get values from JSON fields of firewallRulesList Array
1301                                                         String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
1302                                                         String action = ruleListobj.get("action").toString().replace('"', '\'');
1303                                                         String description = ruleListobj.get("description").toString().replace('"', '\'');
1304                                                         
1305                                                         rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1306                                                         
1307                                                         if (rs.next()) {
1308                                                                 st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";");
1309                                                         }
1310                                                         rs.close();
1311                                                         
1312                                                         //getting fromZone Array field from the firewallRulesList
1313                                                         JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
1314                                                         String fromZoneString = null;
1315                                                         
1316                                                         int fromZoneIndex = 0;
1317                                                         for (JsonValue fromZoneJsonValue : fromZoneArray) {
1318                                                                 String value = fromZoneArray.get(fromZoneIndex).toString();
1319                                                                 value = value.replace("\"", "");
1320                                                                 
1321                                                                 if (fromZoneString != null) {
1322                                                                         fromZoneString = fromZoneString.concat(",").concat(value);
1323                                                                         
1324                                                                 } else {
1325                                                                         fromZoneString = value;
1326                                                                 }
1327                                                                 
1328                                                                 fromZoneIndex++;
1329                                                                 
1330                                                         }
1331                                                         String fromZoneInsert = "'"+fromZoneString+"'";
1332                                                         
1333                                                         //getting toZone Array field from the firewallRulesList
1334                                                         JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
1335                                                         String toZoneString = null;
1336                                                         
1337                                                         int toZoneIndex = 0;
1338                                                         for (JsonValue toZoneJsonValue : toZoneArray) {
1339                                                                 String value = toZoneArray.get(toZoneIndex).toString();
1340                                                                 value = value.replace("\"", "");
1341                                                                 
1342                                                                 if (toZoneString != null) {
1343                                                                         toZoneString = toZoneString.concat(",").concat(value);
1344                                                                         
1345                                                                 } else {
1346                                                                         toZoneString = value;
1347                                                                 }
1348                                                                 
1349                                                                 toZoneIndex++;
1350                                                                 
1351                                                         }
1352                                                         String toZoneInsert = "'"+toZoneString+"'";
1353                                                         //getting sourceList Array fields from the firewallRulesList
1354                                                         JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
1355                                                         String srcListString = null;
1356                                                         
1357                                                         int srcListIndex = 0;
1358                                                         for (JsonValue srcListJsonValue : srcListArray) {
1359                                                                 JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
1360                                                                 String type = srcListObj.get("type").toString().replace("\"", "");
1361                                                                 
1362                                                                 String value = null;
1363                                                                 if(type.equals("REFERENCE")||type.equals("GROUP")){
1364                                                                         value = srcListObj.get("name").toString();
1365                                                                 } else if (type.equalsIgnoreCase("ANY")){
1366                                                                         value = null;
1367                                                                 } else {
1368                                                                         value = srcListObj.get("value").toString();
1369                                                                 }
1370                                                                 
1371                                                                 if(value != null){
1372                                                                         value = value.replace("\"", "");
1373                                                                 }
1374                                                                 
1375                                                                 if (srcListString != null) {
1376                                                                         srcListString = srcListString.concat(",").concat(value);
1377                                                                         
1378                                                                 } else {
1379                                                                         srcListString = value;
1380                                                                 }
1381                                                                 
1382                                                                 srcListIndex++;
1383                                                                 
1384                                                         }
1385                                                         String srcListInsert = "'"+srcListString+"'";
1386                                                         
1387                                                         //getting destinationList Array fields from the firewallRulesList
1388                                                         JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
1389                                                         String destListString = null;
1390                                                         
1391                                                         int destListIndex = 0;
1392                                                         for (JsonValue destListJsonValue : destListArray) {
1393                                                                 JsonObject destListObj = destListArray.getJsonObject(destListIndex);
1394                                                                 String type = destListObj.get("type").toString().replace("\"", "");
1395                                                                 
1396                                                                 String value = null;
1397                                                                 if(type.equals("REFERENCE")||type.equals("GROUP")){
1398                                                                         value = destListObj.get("name").toString();
1399                                                                 } else if (type.equalsIgnoreCase("ANY")){
1400                                                                         value = null;
1401                                                                 } else {
1402                                                                         value = destListObj.get("value").toString();
1403                                                                 }
1404                                                                 
1405                                                                 if(value != null){
1406                                                                         value = value.replace("\"", "");
1407                                                                 }
1408                                                                 
1409                                                                 if (destListString != null) {
1410                                                                         destListString = destListString.concat(",").concat(value);
1411                                                                 } else {
1412                                                                         destListString = value;
1413                                                                 }
1414                                                                 
1415                                                                 destListIndex++;
1416                                                         }
1417                                                         String destListInsert = "'"+destListString+"'";
1418                                                         
1419                                                         //getting destServices Array fields from the firewallRulesList
1420                                                         JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
1421                                                         String destPortListString = null;
1422                                                         
1423                                                         int destPortListIndex = 0;
1424                                                         for (JsonValue destListJsonValue : destServicesArray) {
1425                                                                 JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
1426                                                                 String type = destServicesObj.get("type").toString().replace("\"", "");
1427                                                                 
1428                                                                 String value = null;
1429                                                                 if(type.equals("REFERENCE")||type.equals("GROUP")){
1430                                                                         value = destServicesObj.get("name").toString();
1431                                                                 } else if (type.equalsIgnoreCase("ANY")){
1432                                                                         value = null;
1433                                                                 } else {
1434                                                                         value = destServicesObj.get("value").toString();
1435                                                                 }
1436                                                                 
1437                                                                 if(value != null){
1438                                                                         value = value.replace("\"", "");
1439                                                                 }
1440                                                                 
1441                                                                 if (destPortListString != null) {
1442                                                                         destPortListString = destPortListString.concat(",").concat(value);
1443                                                                 } else {
1444                                                                         destPortListString = value;
1445                                                                 }
1446                                                                 
1447                                                                 destPortListIndex++;
1448                                                         }
1449                                                         String destPortListInsert = "'"+destPortListString+"'";                                 
1450                                                         
1451                                                         /*
1452                                                          * Create Queries to INSERT data into database tables and execute 
1453                                                          */
1454                                                         
1455                                                         //Insert Into Terms table
1456                                 String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST,"
1457                                          + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+","
1458                                          +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+","
1459                                          +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); ";
1460                                                         
1461                                                         termSql = termSql.replace('"', '\'');
1462                                                         st.addBatch(termSql);
1463                                                         
1464                                                         rs = st.executeQuery("SELECT * FROM ACTIONLIST WHERE ACTIONNAME = " + action + ";");
1465                                                         
1466                                                         String actionSql = null;
1467                                                         if (rs.next()) {
1468                                                                 //do nothing
1469                                                         } else {
1470                                                                 actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+") ";
1471                                                                 actionSql = actionSql.replace('"', '\'');
1472                                                                 st.addBatch(actionSql);
1473                                                         }
1474
1475                                                         st.executeBatch();
1476                                                         
1477                                                         ri++;
1478                                                 }
1479                                                 
1480                                         }
1481                                         
1482                                         if (path.contains("serviceGroups")) {
1483                                                 int serviceGroupID = 0;
1484                                                 int serviceListID = 0;
1485                                                 int protocolID = 0;
1486                                                 int portID = 0;
1487
1488                                                 
1489                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;");
1490                                                 if(rs.next()){
1491                                                         serviceGroupID = rs.getInt("ID");
1492                                                 }
1493                                                 rs.close();
1494                                                 
1495                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;");
1496                                                 if(rs.next()){
1497                                                         serviceListID = rs.getInt("ID");
1498                                                 }
1499                                                 rs.close();
1500                                                 
1501                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;");
1502                                                 if(rs.next()){
1503                                                         protocolID = rs.getInt("ID");
1504                                                 }
1505                                                 rs.close();
1506                                                 
1507                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;");
1508                                                 if(rs.next()){
1509                                                         portID = rs.getInt("ID");
1510                                                 }
1511                                                 rs.close();
1512                                                 
1513                                                 String insertQuery = null;
1514                                                 
1515                                                 /*
1516                                                  * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
1517                                                  */
1518                                                 int si = 0;
1519                                                 for(JsonValue jsonValue : serviceGroup) {
1520                                                         
1521                                                         /*
1522                                                          * Populate ArrayLists with values from the JSON
1523                                                          */
1524                                                         //create the JSON object from the JSON Array for each iteration through the for loop
1525                                                         JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
1526                                                         
1527                                                         String groupName = svcGroupListobj.get("name").toString().replace('"', '\''); 
1528                                                         
1529                                                         String description = null;
1530                                                         if (svcGroupListobj.containsKey("description")){
1531                                                                 description = svcGroupListobj.get("description").toString().replace('"', '\'');
1532                                                         }
1533                                                         
1534                                                         JsonArray membersArray = svcGroupListobj.getJsonArray("members");
1535
1536                                                         Boolean isServiceGroup = false;
1537                                                         if (membersArray!=null){
1538                                                                 String membersType = membersArray.getJsonObject(0).get("type").toString();
1539                                                                 if (membersType.contains("REFERENCE")) {
1540                                                                         isServiceGroup = true;
1541                                                                 }
1542                                                         }
1543                                                         
1544                                                         //Insert values into GROUPSERVICELIST table if name begins with Group 
1545                                                         if (isServiceGroup) {
1546                                                                 
1547                                                                 rs = st.executeQuery("SELECT * FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1548                                                                 
1549                                                                 if (rs.next()) {
1550                                                                         st.executeUpdate("DELETE FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";");
1551                                                                 }
1552                                                                 rs.close();
1553                                                                 //increment ID Primary Keys
1554                                                                 serviceListID = serviceListID + 1;
1555                                                                 
1556                                                                 String name = null;
1557                                                                 int membersIndex = 0;
1558                                                                 for (JsonValue membersValue : membersArray) {
1559                                                                         JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1560                                                                         String type = membersObj.get("type").toString().replace("\"", "");
1561                                                                         
1562                                                                         String value = null;
1563                                                                         if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1564                                                                                 value = membersObj.get("name").toString();
1565                                                                         } else if (type.equalsIgnoreCase("ANY")){
1566                                                                                 value = null;
1567                                                                         } else {
1568                                                                                 value = membersObj.get("value").toString();
1569                                                                         }
1570                                                                         
1571                                                                         if(value != null){
1572                                                                                 value = value.replace("\"", "");
1573                                                                         }
1574                                                                         
1575                                                                         if (name != null) {
1576                                                                                 name = name.concat(",").concat(value);
1577                                                                         } else {
1578                                                                                 name = value;
1579                                                                         }
1580                                                                         
1581                                                                         membersIndex++;
1582                                                                 }
1583                                                                 String nameInsert = "'"+name+"'";               
1584                                                                 
1585                                                                 insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) "
1586                                                                                 + "VALUES("+serviceListID+","+groupName+","+nameInsert+")";
1587                                                                 
1588                                                                 //Replace double quote with single quote
1589                                                                 insertQuery = insertQuery.replace('"', '\'');
1590                                                                 
1591                                                                 //Execute the queries to Insert data
1592                                                     st.executeUpdate(insertQuery);
1593                                                                                                                 
1594                                                         } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
1595                                                                                                                                 
1596                                                                 //increment ID Primary Keys
1597                                                                 protocolID = protocolID + 1;
1598                                                                 portID = portID + 1;
1599                                                                 serviceGroupID = serviceGroupID + 1;
1600                                                                 
1601                                                                 String type = svcGroupListobj.get("type").toString().replace('"', '\'');
1602                                                                 String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
1603                                                                 String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
1604                                                                 
1605                                                                 rs = st.executeQuery("SELECT * FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1606                                                                 
1607                                                                 if (rs.next()) {
1608                                                                         st.executeUpdate("DELETE FROM SERVICEGROUP WHERE NAME = "+ groupName + ";");
1609                                                                 }
1610                                                                 rs.close();
1611                                                                 
1612                                                                 String svcGroupSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) "
1613                                                                                         + "VALUES("+serviceGroupID+","+groupName+","+description+","+type+","
1614                                                                                         + transportProtocol+","+"null,"+ports+"); ";
1615                                                                 svcGroupSql = svcGroupSql.replace('"', '\'');
1616                                                                 st.addBatch(svcGroupSql);
1617                                                                 
1618                                                                 rs = st.executeQuery("SELECT * FROM PROTOCOLLIST WHERE PROTOCOLNAME = " + transportProtocol + ";");
1619                                                                 
1620                                                                 String protoSql = null;
1621                                                                 if (rs.next()) {
1622                                                                         //do nothing
1623                                                                 } else {
1624                                                                         protoSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) "
1625                                                                                         + "VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); ";
1626                                                                         protoSql = protoSql.replace('"', '\'');
1627                                                                         st.addBatch(protoSql);
1628
1629                                                                 }
1630                                                                 rs.close();
1631
1632                                                                 rs = st.executeQuery("SELECT * FROM PORTLIST WHERE PORTNAME = " + ports + ";");
1633                                                                 
1634                                                                 String portSql = null;
1635                                                                 if (rs.next()) {
1636                                                                         //do nothing
1637                                                                 } else {
1638                                                                         portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+"); ";
1639                                                                         portSql = portSql.replace('"', '\'');
1640                                                                         st.addBatch(portSql);
1641                                                                 }
1642                                                                 rs.close();
1643                                                                 
1644                                                                 st.executeBatch();
1645
1646                                                         }               
1647                                                         
1648                                                         
1649                                             si++;
1650                                                 }
1651                                                 
1652                                         }
1653                                         
1654                                         if (path.contains("addressGroups")) {
1655                                                 /*
1656                                                  * Inserting addressGroup data into the ADDRESSGROUP table
1657                                                  */
1658                                                 int prefixID = 0;
1659                                                 int addressID = 0;
1660                                                 
1661                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;");
1662                                                 if(rs.next()){
1663                                                         prefixID = rs.getInt("ID");
1664                                                 }
1665                                                 rs.close();
1666                                                 
1667                                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;");
1668                                                 if(rs.next()){
1669                                                         addressID = rs.getInt("ID");
1670                                                 }
1671                                                 rs.close();
1672                                                 
1673                                                 String insertQuery = null;
1674                                                 
1675                                                 int ai = 0;
1676                                                 for(JsonValue jsonValue : addressGroup) {
1677                                                         
1678                                                         /*
1679                                                          * Populate ArrayLists with values from the JSON
1680                                                          */
1681                                                         //create the JSON object from the JSON Array for each iteration through the for loop
1682                                                         JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
1683                                                         
1684                                                         //create JSON array for members
1685                                                         JsonArray membersArray = addressGroupObj.getJsonArray("members");
1686                                                         String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
1687                                                         
1688                                                         String description = null;
1689                                                         if (addressGroupObj.containsKey("description")){
1690                                                                 description = addressGroupObj.get("description").toString().replace('"', '\'');
1691                                                         }
1692                                                         
1693                                                         String prefixIP = null;
1694                                                         String type = null;
1695                                                         int membersIndex = 0;
1696                                                         for (JsonValue membersValue : membersArray) {
1697                                                                 JsonObject membersObj = membersArray.getJsonObject(membersIndex);
1698                                                                 type = membersObj.get("type").toString().replace("\"", "");
1699                                                                 
1700                                                                 String value = null;
1701                                                                 if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
1702                                                                         value = membersObj.get("name").toString();
1703                                                                 } else if (type.equalsIgnoreCase("ANY")){
1704                                                                         value = null;
1705                                                                 } else {
1706                                                                         value = membersObj.get("value").toString();
1707                                                                 }
1708                                                                 
1709                                                                 if(value != null){
1710                                                                         value = value.replace("\"", "");
1711                                                                 }
1712                                                                 
1713                                                                 if (prefixIP != null) {
1714                                                                         prefixIP = prefixIP.concat(",").concat(value);
1715                                                                 } else {
1716                                                                         prefixIP = value;
1717                                                                 }
1718                                                                 
1719                                                                 membersIndex++;
1720                                                         }
1721                                                         String prefixList = "'"+prefixIP+"'";
1722                                                         
1723                                                         Boolean isAddressGroup = type.contains("REFERENCE");
1724                                                         
1725                                                         if (isAddressGroup) {           
1726                                                                 
1727                                                                 rs = st.executeQuery("SELECT * FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1728                                                                 
1729                                                                 if (rs.next()) {
1730                                                                         st.executeUpdate("DELETE FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";");
1731                                                                 }
1732                                                                 rs.close();
1733                                                                 //increment ID Primary Keys
1734                                                                 addressID = addressID + 1;
1735                                                                 
1736                                                                 insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) "
1737                                                                                         + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")";  
1738                                                                 
1739                                                                 
1740                                                                 
1741                                                         } else {
1742                                                                 
1743                                                                 rs = st.executeQuery("SELECT * FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1744                                                                 
1745                                                                 if (rs.next()) {
1746                                                                         st.executeUpdate("DELETE FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";");
1747                                                                 }
1748                                                                 rs.close();
1749                                                                  //increment ID Primary Key
1750                                                                 prefixID = prefixID + 1;
1751                                                                 
1752                                                                 insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) "
1753                                                                                         + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")";
1754                                                                 
1755                                                         }
1756                         
1757                                                         
1758                                                         //Replace double quote with single quote
1759                                                         insertQuery = insertQuery.replace('"', '\'');
1760                                                         
1761                                                         //Execute the queries to Insert data
1762                                             st.executeUpdate(insertQuery);
1763                                                         
1764                                                         ai++;
1765                                                 }
1766                                                 
1767                                         }
1768                                                 
1769                                         i++;    
1770                                 }
1771                                 
1772                                 /*
1773                                  * Remove duplicate values from 'lookup' dictionary tables
1774                                  */
1775                                 //ProtocolList Table
1776                                 String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 "
1777                                                 + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
1778                                 st.addBatch(protoDelete);
1779                                 
1780                                 //PortList Table
1781                                 String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
1782                                                 + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
1783                                 st.addBatch(portListDelete);
1784                                 
1785                                 //PrefixList Table
1786                                 String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
1787                                                 + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
1788                                                 + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
1789                                 st.addBatch(prefixListDelete);
1790                                 
1791                                 //GroupServiceList
1792                                 String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
1793                                                 + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
1794                                                 + "groupservicelist.serviceList = g1.serviceList; ";
1795                                 st.addBatch(groupServiceDelete);
1796                                 
1797                                 st.executeBatch();
1798                                 
1799                         } catch (ClassNotFoundException e) {
1800                                 //TODO:EELF Cleanup - Remove logger
1801                                 //logger.error(e.getMessage());
1802                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries");
1803                                 System.out.println(e.getMessage());
1804                                 return false;
1805         
1806                         } catch (SQLException e) {
1807                                 //TODO:EELF Cleanup - Remove logger
1808                                 //logger.error(e.getMessage());
1809                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
1810                                 System.out.println(e.getMessage());
1811                                 return false;
1812                         } finally {
1813                                 try{
1814                                         if (con!=null) con.close();
1815                                         if (rs!=null) rs.close();
1816                                         if (st!=null) st.close();
1817                                 } catch (Exception ex){}
1818                         }
1819                         return true;
1820         
1821                 } else {
1822                         return false;
1823                 }
1824         
1825 }
1826         
1827         private JsonObject stringToJson(String jsonString) {
1828                 
1829                 JsonObject json = null;
1830                 if (jsonString != null) {
1831                         
1832                         //Read jsonBody to JsonObject
1833                         StringReader in = null;
1834                         
1835                         in = new StringReader(jsonString);
1836                         
1837                         JsonReader jsonReader = Json.createReader(in);
1838                         json = jsonReader.readObject();
1839                 }
1840                 
1841                 return json;
1842         }
1843                 
1844                 
1845         private JsonNode createPatch(String json, String oldJson) {
1846                 JsonNode oldJason = null;
1847                 JsonNode updatedJason = null;
1848
1849                 try {
1850                 oldJason = JsonLoader.fromString(oldJson);
1851                 updatedJason = JsonLoader.fromString(json);
1852                 } catch (IOException e) {
1853                 e.printStackTrace();
1854                 }
1855
1856                 JsonPatch jsonPatch = JsonDiff.asJsonPatch(oldJason, updatedJason);
1857                 JsonNode patchNode = JsonDiff.asJson(oldJason, updatedJason);
1858                 System.out.println("Sending Patch:" + jsonPatch);
1859                 return patchNode;
1860
1861                 }
1862
1863         @Override
1864         public Object getCorrectPolicyDataObject() {
1865                 return policyAdapter.getPolicyData();
1866         }
1867
1868 }
1869         
1870         
1871