diff options
Diffstat (limited to 'ECOMP-PAP-REST/src/main/java')
8 files changed, 416 insertions, 669 deletions
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/HibernateSession.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/HibernateSession.java index 93fe33727..2aca54cc7 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/HibernateSession.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/HibernateSession.java @@ -32,14 +32,18 @@ public class HibernateSession{ private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class); private static SessionFactory xacmlsessionFactory; + private HibernateSession(){ + //Default Constructor + } + static { try { Configuration configuration= new Configuration(); - configuration.setProperty("hibernate.connection.url", XACMLPapServlet.papDbUrl); - configuration.setProperty("hibernate.connection.username", XACMLPapServlet.papDbUser); - configuration.setProperty("hibernate.connection.password", XACMLPapServlet.papDbPassword); + configuration.setProperty("hibernate.connection.url", XACMLPapServlet.getPapDbUrl()); + configuration.setProperty("hibernate.connection.username", XACMLPapServlet.getPapDbUser()); + configuration.setProperty("hibernate.connection.password", XACMLPapServlet.getPapDbPassword()); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty("hibernate.connection.driver_class", XACMLPapServlet.papDbDriver); + configuration.setProperty("hibernate.connection.driver_class", XACMLPapServlet.getPapDbDriver()); configuration.setProperty("hibernate.show_sql", "false"); configuration.setProperty("hibernate.connection.autocommit", "true"); configuration.setProperty("hibernate.c3p0.min_size", "5"); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java index 5e7e2436f..685582e29 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java @@ -152,10 +152,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * These are the parameters needed for DB access from the PAP */ private static int papIntegrityAuditPeriodSeconds = -1; - public static String papDbDriver = null; - public static String papDbUrl = null; - public static String papDbUser = null; - public static String papDbPassword = null; + private static String papDbDriver = null; + private static String papDbUrl = null; + private static String papDbUser = null; + private static String papDbPassword = null; private static Integer papTransWait = null; private static Integer papTransTimeout = null; private static Integer papAuditTimeout = null; @@ -179,8 +179,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private IntegrityAudit ia; //MicroService Model Properties - public static String msEcompName; - public static String msPolicyName; + private static String msEcompName; + private static String msPolicyName; /* * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when * this servlet starts. Its configurable by the admin. @@ -224,21 +224,25 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry"); throw new PAPException("papDbDriver is null"); } + setPapDbDriver(papDbDriver); papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); if(papDbUrl == null){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); throw new PAPException("papDbUrl is null"); } + setPapDbUrl(papDbUrl); papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); if(papDbUser == null){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry"); throw new PAPException("papDbUser is null"); } + setPapDbUser(papDbUser); papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); if(papDbPassword == null){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry"); throw new PAPException("papDbPassword is null"); } + setPapDbPassword(papDbPassword); papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME); if(papResourceName == null){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry"); @@ -350,7 +354,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } //Micro Service Properties msEcompName=properties.getProperty("xacml.policy.msEcompName"); + setMsEcompName(msEcompName); msPolicyName=properties.getProperty("xacml.policy.msPolicyName"); + setMsPolicyName(msPolicyName); // PDPId File location XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); if (XACMLPapServlet.pdpFile == null) { @@ -2594,4 +2600,51 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList public static PolicyDBDaoTransaction getDbDaoTransaction(){ return policyDBDao.getNewTransaction(); } + public static String getPapDbDriver() { + return papDbDriver; + } + + public static void setPapDbDriver(String papDbDriver) { + XACMLPapServlet.papDbDriver = papDbDriver; + } + + public static String getPapDbUrl() { + return papDbUrl; + } + + public static void setPapDbUrl(String papDbUrl) { + XACMLPapServlet.papDbUrl = papDbUrl; + } + + public static String getPapDbUser() { + return papDbUser; + } + + public static void setPapDbUser(String papDbUser) { + XACMLPapServlet.papDbUser = papDbUser; + } + + public static String getPapDbPassword() { + return papDbPassword; + } + + public static void setPapDbPassword(String papDbPassword) { + XACMLPapServlet.papDbPassword = papDbPassword; + } + + public static String getMsEcompName() { + return msEcompName; + } + + public static void setMsEcompName(String msEcompName) { + XACMLPapServlet.msEcompName = msEcompName; + } + + public static String getMsPolicyName() { + return msPolicyName; + } + + public static void setMsPolicyName(String msPolicyName) { + XACMLPapServlet.msPolicyName = msPolicyName; + } } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java index 63fa04210..1884aab62 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java @@ -86,7 +86,7 @@ public class ActionPolicy extends Policy { public static final String URL_ATTRIBUTEID = "url"; public static final String BODY_ATTRIBUTEID = "body"; - public static boolean isAttribute = false; + private static boolean isAttribute = false; List<String> dynamicLabelRuleAlgorithms = new LinkedList<>(); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java index 30a95f901..0e4e409d3 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java @@ -68,7 +68,7 @@ public class CreateNewMicroSerivceModel { private static String papDbUser = null; private static String papDbPassword = null; - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.msEcompName, XACMLPapServlet.msPolicyName); + MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsEcompName(), XACMLPapServlet.getMsPolicyName()); public CreateNewMicroSerivceModel(String fileName, String serviceName, String string, String version) { super(); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java index b4b1a410e..9f780fd28 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java @@ -31,11 +31,7 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -47,66 +43,66 @@ import javax.json.JsonReader; import javax.persistence.EntityManager; import javax.persistence.Query; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - import org.apache.commons.io.FilenameUtils; import org.openecomp.policy.common.logging.eelf.MessageCodes; import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.ActionList; +import org.openecomp.policy.rest.jpa.AddressGroup; +import org.openecomp.policy.rest.jpa.GroupServiceList; import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.jpa.PortList; +import org.openecomp.policy.rest.jpa.PrefixList; +import org.openecomp.policy.rest.jpa.ProtocolList; +import org.openecomp.policy.rest.jpa.ServiceList; +import org.openecomp.policy.rest.jpa.TermList; +import org.openecomp.policy.rest.jpa.UserInfo; import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; -import com.github.fge.jsonpatch.JsonPatch; import com.github.fge.jsonpatch.diff.JsonDiff; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + public class FirewallConfigPolicy extends Policy { private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class); - - /* - * These are the parameters needed for DB access from the PAP - */ - private static String papDbDriver = null; - private static String papDbUrl = null; - private static String papDbUser = null; - private static String papDbPassword = null; public FirewallConfigPolicy() { super(); } - + public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; this.policyAdapter.setConfigType(policyAdapter.getConfigType()); - } - + // Saving the Configurations file at server location for config policy. protected void saveConfigurations(String policyName, String jsonBody) { + String configurationName = policyName; + FileWriter fw = null; try{ - if(policyName.endsWith(".xml")){ - policyName = policyName.replace(".xml", ""); + if(configurationName.endsWith(".xml")){ + configurationName = configurationName.replace(".xml", ""); } - FileWriter fw = new FileWriter(CONFIG_HOME + File.separator + policyName + ".json"); + fw = new FileWriter(CONFIG_HOME + File.separator + configurationName + ".json"); BufferedWriter bw = new BufferedWriter(fw); bw.write(jsonBody); bw.close(); @@ -115,35 +111,30 @@ public class FirewallConfigPolicy extends Policy { } } catch (IOException e) { LOGGER.error("Exception Occured"+e); + }finally{ + try{ + if(fw != null){ + fw.close(); + } + }catch(Exception e){ + LOGGER.error("Exception Occured"+e); + } } } - + //Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { - byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); - - } - - // Validations for Config form - public boolean validateConfigForm() { - - // Validating mandatory Fields. - isValidForm = true; - return isValidForm; - } @Override public Map<String, String> savePolicies() throws Exception { - Map<String, String> successMap = new HashMap<>(); if(isPolicyExists()){ successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ prepareToSave(); } @@ -152,7 +143,7 @@ public class FirewallConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); Boolean dbIsUpdated = false; - if (policyAdapter.getApiflag() != null && policyAdapter.getApiflag().equalsIgnoreCase("admin")){ + if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){ if (policyAdapter.isEditPolicy()) { dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); } else { @@ -176,7 +167,7 @@ public class FirewallConfigPolicy extends Policy { } successMap.put("fwdberror", "DB UPDATE"); } - + return successMap; } @@ -184,18 +175,18 @@ public class FirewallConfigPolicy extends Policy { //separately because the fully configured policy is used for multiple things @Override public boolean prepareToSave() throws Exception{ - + if(isPreparedToSave()){ //we have already done this return true; } - + int version = 0; String policyID = policyAdapter.getPolicyID(); version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshalling. - if (policyAdapter.getPolicyType().equals("Config")) { + + // Create the Instance for pojo, PolicyType object is used in marshaling. + if ("Config".equals(policyAdapter.getPolicyType())) { PolicyType policyConfig = new PolicyType(); policyConfig.setVersion(Integer.toString(version)); @@ -204,15 +195,13 @@ public class FirewallConfigPolicy extends Policy { policyAdapter.setData(policyConfig); } policyName = policyAdapter.getNewFileName(); - + //String oldPolicyName = policyName.replace(".xml", ""); - String scope = policyName.substring(0, policyName.indexOf(".")); - String dbPolicyName = policyName.substring(policyName.indexOf(".")+1).replace(".xml", ""); - - int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf(".")+1)); - dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf(".")+1); - //String scope = oldPolicyName.substring(0, oldPolicyName.lastIndexOf(".")); - //scope = scope.substring(0, scope.lastIndexOf(".")); + String scope = policyName.substring(0, policyName.indexOf('.')); + String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", ""); + + int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1)); + dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1); if(oldversion > 1){ oldversion = oldversion - 1; dbPolicyName = dbPolicyName + oldversion + ".xml"; @@ -230,59 +219,54 @@ public class FirewallConfigPolicy extends Policy { if (policyAdapter.getData() != null) { String jsonBody = policyAdapter.getJsonBody(); saveConfigurations(policyName, jsonBody); - + // Make sure the filename ends with an extension - if (policyName.endsWith(".xml") == false) { + if (!policyName.endsWith(".xml")) { policyName = policyName + ".xml"; } PolicyType configPolicy = (PolicyType) policyAdapter.getData(); - + configPolicy.setDescription(policyAdapter.getPolicyDescription()); configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); AllOfType allOfOne = new AllOfType(); String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); } allOfOne.getMatch().add(createMatch("PolicyName", name)); AllOfType allOf = new AllOfType(); - + // Match for ConfigName allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); anyOf.getAllOf().add(allOf); TargetType target = new TargetType(); - ((TargetType) target).getAnyOf().add(anyOf); - + target.getAnyOf().add(anyOf); + // Adding the target to the policy element configPolicy.setTarget((TargetType) target); RuleType rule = new RuleType(); rule.setRuleId(policyAdapter.getRuleID()); - rule.setEffect(EffectType.PERMIT); - + // Create Target in Rule AllOfType allOfInRule = new AllOfType(); - + // Creating match for ACCESS in rule target MatchType accessMatch = new MatchType(); AttributeValueType accessAttributeValue = new AttributeValueType(); @@ -301,14 +285,14 @@ public class FirewallConfigPolicy extends Policy { accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); accessMatch.setAttributeDesignator(accessAttributeDesignator); accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - + // Creating Config Match in rule Target MatchType configMatch = new MatchType(); AttributeValueType configAttributeValue = new AttributeValueType(); configAttributeValue.setDataType(STRING_DATATYPE); - + configAttributeValue.getContent().add("Config"); - + configMatch.setAttributeValue(configAttributeValue); AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); URI configURI = null; @@ -317,7 +301,7 @@ public class FirewallConfigPolicy extends Policy { } catch (URISyntaxException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI"); } - + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); @@ -329,7 +313,7 @@ public class FirewallConfigPolicy extends Policy { AnyOfType anyOfInRule = new AnyOfType(); anyOfInRule.getAllOf().add(allOfInRule); - + TargetType targetInRule = new TargetType(); targetInRule.getAnyOf().add(anyOfInRule); @@ -348,7 +332,7 @@ public class FirewallConfigPolicy extends Policy { // Data required for Advice part is setting here. private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - + //Firewall Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); @@ -364,7 +348,7 @@ public class FirewallConfigPolicy extends Policy { configNameAttributeValue.getContent().add("Configuration"); assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); advice.getAttributeAssignmentExpression().add(assignment1); - + // For Config file Url if configurations are provided. //URL ID Assignment AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); @@ -381,7 +365,7 @@ public class FirewallConfigPolicy extends Policy { AttributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); - + //Policy Name Assignment AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); assignment3.setAttributeId("PolicyName"); @@ -398,7 +382,7 @@ public class FirewallConfigPolicy extends Policy { attributeValue3.getContent().add(name); assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); - + //Version Number Assignment AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); assignment4.setAttributeId("VersionNumber"); @@ -409,7 +393,7 @@ public class FirewallConfigPolicy extends Policy { configNameAttributeValue4.getContent().add(Integer.toString(version)); assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); - + //Ecomp Name Assignment AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); assignment5.setAttributeId("matching:" + ECOMPID); @@ -419,7 +403,7 @@ public class FirewallConfigPolicy extends Policy { configNameAttributeValue5.setDataType(STRING_DATATYPE); assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - + //Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); @@ -443,7 +427,7 @@ public class FirewallConfigPolicy extends Policy { assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); advice.getAttributeAssignmentExpression().add(assignment7); - + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskLevel"); assignment8.setCategory(CATEGORY_RESOURCE); @@ -467,7 +451,7 @@ public class FirewallConfigPolicy extends Policy { assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); advice.getAttributeAssignmentExpression().add(assignment9); - + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); assignment10.setAttributeId("TTLDate"); assignment10.setCategory(CATEGORY_RESOURCE); @@ -482,140 +466,81 @@ public class FirewallConfigPolicy extends Policy { advices.getAdviceExpression().add(advice); return advices; } - - - private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException { - + + private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException { + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject json = null; if (jsonBody != null) { - + //Read jsonBody to JsonObject json = stringToJson(jsonBody); - + JsonArray firewallRules = null; JsonArray serviceGroup = null; JsonArray addressGroup = null; - - Connection con = null; - Statement st = null; - ResultSet rs = null; - - /* - * Retrieve the property values for db access from the xacml.pap.properties - */ - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - //insert data into tables try { - //Get DB Connection - Class.forName(papDbDriver); - con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); - st = con.createStatement(); - firewallRules = json.getJsonArray("firewallRuleList"); serviceGroup = json.getJsonArray("serviceGroups"); addressGroup = json.getJsonArray("addressGroups"); - - String insertQuery = null; - /* * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ if (firewallRules != null) { - - int termID = 0; - int zoneID = 0; - int actionID = 0; - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;"); - if(rs.next()){ - termID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;"); - if(rs.next()){ - zoneID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;"); - if(rs.next()){ - actionID = rs.getInt("ID"); - } - rs.close(); for(int i = 0;i<firewallRules.size();i++) { - - //increment ID Primary Keys - termID = termID + 1; - zoneID = zoneID + 1; - actionID = actionID + 1; - /* * Populate ArrayLists with values from the JSON */ //create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(i); - + //get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString(); String action = ruleListobj.get("action").toString(); String description = ruleListobj.get("description").toString(); - - rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";"); - - if (rs.next()) { - st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";"); + List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); + if(result != null && !result.isEmpty()){ + TermList termEntry = (TermList) result.get(0); + dbConnection.delete(termEntry); } - rs.close(); //getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - - + for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); - if (fromZoneString != null) { fromZoneString = fromZoneString.concat(",").concat(value); - } else { fromZoneString = value; } - } String fromZoneInsert = "'"+fromZoneString+"'"; - + //getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); - if (toZoneString != null) { toZoneString = toZoneString.concat(",").concat(value); - } else { toZoneString = value; } - } String toZoneInsert = "'"+toZoneString+"'"; - + //getting sourceList Array fields from the firewallRulesList JsonArray srcListArray = ruleListobj.getJsonArray("sourceList"); String srcListString = null; for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")){ value = srcListObj.get("name").toString(); @@ -624,28 +549,28 @@ public class FirewallConfigPolicy extends Policy { } else { value = srcListObj.get("value").toString(); } - + if (value!=null){ value = value.replace("\"", ""); } - + if (srcListString != null) { srcListString = srcListString.concat(",").concat(value); - + } else { srcListString = value; } - + } String srcListInsert = "'"+srcListString+"'"; - + //getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")){ value = destListObj.get("name").toString(); @@ -654,11 +579,11 @@ public class FirewallConfigPolicy extends Policy { } else { value = destListObj.get("value").toString(); } - + if (value!=null){ value = value.replace("\"", ""); } - + if (destListString != null) { destListString = destListString.concat(",").concat(value); } else { @@ -666,14 +591,14 @@ public class FirewallConfigPolicy extends Policy { } } String destListInsert = "'"+destListString+"'"; - + //getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")){ value = destServicesObj.get("name").toString(); @@ -682,11 +607,11 @@ public class FirewallConfigPolicy extends Policy { } else { value = destServicesObj.get("value").toString(); } - + if (value!=null){ value = value.replace("\"", ""); } - + if (destPortListString != null) { destPortListString = destPortListString.concat(",").concat(value); } else { @@ -694,75 +619,53 @@ public class FirewallConfigPolicy extends Policy { } } String destPortListInsert = "'"+destPortListString+"'"; - + /* * Create Queries to INSERT data into database tables and execute - */ - String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST," - + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+"," - +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+"," - +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); "; - termSql = termSql.replace('"', '\''); - st.addBatch(termSql); - - String actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+"); "; - actionSql = actionSql.replace('"', '\''); - st.addBatch(actionSql); + */ + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId("API"); + userInfo.setUserName("API"); + + TermList termEntry = new TermList(); + termEntry.setTermName(ruleName); + termEntry.setSrcIPList(srcListInsert); + termEntry.setDestIPList(destListInsert); + termEntry.setProtocolList("null"); + termEntry.setPortList("null"); + termEntry.setSrcPortList("null"); + termEntry.setDestPortList(destPortListInsert); + termEntry.setAction(action); + termEntry.setDescription(description); + termEntry.setFromZones(fromZoneInsert); + termEntry.setToZones(toZoneInsert); + termEntry.setUserCreatedBy(userInfo); + dbConnection.save(termEntry); - st.executeBatch(); + ActionList actionEntry = new ActionList(); + actionEntry.setActionName(action); + actionEntry.setDescription(action); + dbConnection.save(actionEntry); } - } - + /* * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables */ if (serviceGroup != null) { - - int serviceGroupID = 0; - int serviceListID = 0; - int protocolID = 0; - int portID = 0; - - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;"); - if(rs.next()){ - serviceGroupID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;"); - if(rs.next()){ - serviceListID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;"); - if(rs.next()){ - protocolID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;"); - if(rs.next()){ - portID = rs.getInt("ID"); - } - rs.close(); for(int i = 0; i < serviceGroup.size() ; i++) { - /* * Populate ArrayLists with values from the JSON */ //create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(i); - + String serviceListName = svcGroupListobj.get("name").toString(); - String description = null; if (svcGroupListobj.containsKey("description")){ description = svcGroupListobj.get("description").toString(); } - + //getting members Array from the serviceGroup JsonArray membersArray = svcGroupListobj.getJsonArray("members"); @@ -774,19 +677,15 @@ public class FirewallConfigPolicy extends Policy { isServiceGroup = true; } } - + //Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { - - //increment ID Primary Keys - serviceListID = serviceListID + 1; - String name = null; for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); //String value = membersObj.get("name").toString(); String type = membersObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ value = membersObj.get("name").toString(); @@ -795,11 +694,11 @@ public class FirewallConfigPolicy extends Policy { } else { value = membersObj.get("value").toString(); } - + if(value != null){ value = value.replace("\"", ""); } - + if (name != null) { name = name.concat(",").concat(value); } else { @@ -807,91 +706,67 @@ public class FirewallConfigPolicy extends Policy { } } String nameInsert = "'"+name+"'"; - - insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) " - + "VALUES("+serviceListID+","+serviceListName+","+nameInsert+")"; - - //Replace double quote with single quote - insertQuery = insertQuery.replace('"', '\''); - - //Execute the queries to Insert data - st.executeUpdate(insertQuery); - + GroupServiceList groupServiceEntry = new GroupServiceList(); + groupServiceEntry.setGroupName(serviceListName); + groupServiceEntry.setServiceList(nameInsert); + dbConnection.save(groupServiceEntry); } else { //Insert JSON data serviceList table, protollist table, and portlist table - - //increment ID Primary Keys - protocolID = protocolID + 1; - portID = portID + 1; - serviceGroupID = serviceGroupID + 1; - String type = svcGroupListobj.get("type").toString(); String transportProtocol = svcGroupListobj.get("transportProtocol").toString(); String ports = svcGroupListobj.get("ports").toString(); - + /* * Create Queries to INSERT data into database table and execute */ - String serviceSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) " - + "VALUES("+serviceGroupID+","+serviceListName+","+description+","+type+"," - + transportProtocol+","+"null,"+ports+"); "; - serviceSql = serviceSql.replace('"', '\''); - st.addBatch(serviceSql); + ServiceList serviceListEntry = new ServiceList(); + serviceListEntry.setServiceName(serviceListName); + serviceListEntry.setServiceDescription(description); + serviceListEntry.setServiceType(type); + serviceListEntry.setServiceTransProtocol(transportProtocol); + serviceListEntry.setServiceAppProtocol("null"); + serviceListEntry.setServicePorts(ports); + dbConnection.save(serviceListEntry); - String protSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); "; - protSql = protSql.replace('"', '\''); - st.addBatch(protSql); + ProtocolList protocolEntry = new ProtocolList(); + protocolEntry.setProtocolName(transportProtocol); + protocolEntry.setDescription(transportProtocol); + dbConnection.save(protocolEntry); - String portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+");"; - portSql = portSql.replace('"', '\''); - st.addBatch(portSql); - - st.executeBatch(); - + PortList portListEntry = new PortList(); + portListEntry.setPortName(ports); + portListEntry.setDescription(ports); + dbConnection.save(portListEntry); } } } - + /* * Inserting addressGroup data into the ADDRESSGROUP table */ if (addressGroup != null) { - int prefixID = 0; - int addressID = 0; - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;"); - if(rs.next()){ - prefixID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;"); - if(rs.next()){ - addressID = rs.getInt("ID"); - } - rs.close(); for(int i = 0; i < addressGroup.size(); i++) { /* * Populate ArrayLists with values from the JSON */ //create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(i); - + //create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString(); - + String description = null; if (addressGroupObj.containsKey("description")){ description = addressGroupObj.get("description").toString(); } - + String prefixIP = null; String type = null; for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); //String value = membersObj.get("value").toString(); type = membersObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ value = membersObj.get("name").toString(); @@ -900,11 +775,11 @@ public class FirewallConfigPolicy extends Policy { } else { value = membersObj.get("value").toString(); } - + if(value != null){ value = value.replace("\"", ""); } - + if (prefixIP != null) { prefixIP = prefixIP.concat(",").concat(value); } else { @@ -912,229 +787,153 @@ public class FirewallConfigPolicy extends Policy { } } String prefixList = "'"+prefixIP+"'"; - + Boolean isAddressGroup = type.contains("REFERENCE"); - + if (isAddressGroup) { - //increment ID Primary Keys - addressID = addressID + 1; - - insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) " - + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")"; + AddressGroup addressGroupEntry = new AddressGroup(); + addressGroupEntry.setGroupName(addressGroupName); + addressGroupEntry.setDescription(description); + addressGroupEntry.setServiceList(prefixList); + dbConnection.save(addressGroupEntry); } else { - //increment ID Primary Key - prefixID = prefixID + 1; - - insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) " - + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")"; - + PrefixList prefixListEntry = new PrefixList(); + prefixListEntry.setPrefixListName(addressGroupName); + prefixListEntry.setDescription(description); + prefixListEntry.setPrefixListValue(prefixList); + dbConnection.save(prefixListEntry); } - - - //Replace double quote with single quote - insertQuery = insertQuery.replace('"', '\''); - - //Execute the queries to Insert data - st.executeUpdate(insertQuery); } - } - + /* * Remove duplicate values from 'lookup' dictionary tables */ //ProtocolList Table String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 " + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;"; - st.addBatch(protoDelete); - + dbConnection.updateQuery(protoDelete); + //PortList Table String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; - st.addBatch(portListDelete); - + dbConnection.updateQuery(portListDelete); + //PrefixList Table String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; - st.addBatch(prefixListDelete); - + dbConnection.updateQuery(prefixListDelete); + //GroupServiceList String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " + "groupservicelist.serviceList = g1.serviceList; "; - st.addBatch(groupServiceDelete); - - st.executeBatch(); - - } catch (ClassNotFoundException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries "); - System.out.println(e.getMessage()); - return false; - - } catch (SQLException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries"); - System.out.println(e.getMessage()); - return false; - } catch (Exception e) { + dbConnection.updateQuery(groupServiceDelete); + }catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values"); - System.out.println(e.getMessage()); return false; - } finally { - try{ - if (con!=null) con.close(); - if (rs!=null) rs.close(); - if (st!=null) st.close(); - } catch (Exception ex){} - } + } return true; } else { return false; } - + } private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) { - + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject oldJson = null; JsonObject newJson = null; - + if (jsonBody != null || prevJsonBody != null) { - + oldJson = stringToJson(prevJsonBody); newJson = stringToJson(jsonBody); - + //if no changes to the json then return true - if (oldJson.equals(newJson)) { + if (oldJson != null && oldJson.equals(newJson)) { return true; } - + JsonArray firewallRules = null; JsonArray serviceGroup = null; JsonArray addressGroup = null; - + firewallRules = newJson.getJsonArray("firewallRuleList"); serviceGroup = newJson.getJsonArray("serviceGroups"); addressGroup = newJson.getJsonArray("addressGroups"); - - Connection con = null; - Statement st = null; - ResultSet rs = null; - - /* - * Retrieve the property values for db access from the xacml.pap.properties - */ - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - + //insert data into tables try { - - //Get DB Connection - Class.forName(papDbDriver); - con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); - st = con.createStatement(); - JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody); - - + for (int i = 0; i<jsonDiff.size(); i++) { //String path = jsonDiff.get(i).asText(); String jsonpatch = jsonDiff.get(i).toString(); - + JsonObject patchObj = stringToJson(jsonpatch); - + String path = patchObj.get("path").toString().replace('"', ' ').trim(); - + if (path.contains("firewallRuleList")) { - int termID = 0; - int zoneID = 0; - int actionID = 0; - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM TERM;"); - if(rs.next()){ - termID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ZONE;"); - if(rs.next()){ - zoneID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ACTIONLIST;"); - if(rs.next()){ - actionID = rs.getInt("ID"); - } - rs.close(); - /* * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ for(int ri = 0; ri < firewallRules.size(); ri++) { - - //increment ID Primary Keys - termID = termID + 1; - zoneID = zoneID + 1; - actionID = actionID + 1; - /* * Populate ArrayLists with values from the JSON */ //create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(ri); - + //get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\''); String action = ruleListobj.get("action").toString().replace('"', '\''); String description = ruleListobj.get("description").toString().replace('"', '\''); - - rs = st.executeQuery("SELECT * FROM TERM WHERE TERMNAME = "+ ruleName + ";"); - - if (rs.next()) { - st.executeUpdate("DELETE FROM TERM WHERE TERMNAME = "+ ruleName + ";"); + + List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); + if(result != null && !result.isEmpty()){ + TermList termEntry = (TermList) result.get(0); + dbConnection.delete(termEntry); } - rs.close(); - + //getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - + for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); - + if (fromZoneString != null) { fromZoneString = fromZoneString.concat(",").concat(value); - + } else { fromZoneString = value; } - + } String fromZoneInsert = "'"+fromZoneString+"'"; - + //getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; - - + + for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); - + if (toZoneString != null) { toZoneString = toZoneString.concat(",").concat(value); - + } else { toZoneString = value; } - + } String toZoneInsert = "'"+toZoneString+"'"; //getting sourceList Array fields from the firewallRulesList @@ -1143,7 +942,7 @@ public class FirewallConfigPolicy extends Policy { for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")){ value = srcListObj.get("name").toString(); @@ -1152,28 +951,28 @@ public class FirewallConfigPolicy extends Policy { } else { value = srcListObj.get("value").toString(); } - + if(value != null){ value = value.replace("\"", ""); } - + if (srcListString != null) { srcListString = srcListString.concat(",").concat(value); - + } else { srcListString = value; } - + } String srcListInsert = "'"+srcListString+"'"; - + //getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")){ value = destListObj.get("name").toString(); @@ -1182,11 +981,11 @@ public class FirewallConfigPolicy extends Policy { } else { value = destListObj.get("value").toString(); } - + if(value != null){ value = value.replace("\"", ""); } - + if (destListString != null) { destListString = destListString.concat(",").concat(value); } else { @@ -1194,14 +993,14 @@ public class FirewallConfigPolicy extends Policy { } } String destListInsert = "'"+destListString+"'"; - + //getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")){ value = destServicesObj.get("name").toString(); @@ -1210,11 +1009,11 @@ public class FirewallConfigPolicy extends Policy { } else { value = destServicesObj.get("value").toString(); } - + if(value != null){ value = value.replace("\"", ""); } - + if (destPortListString != null) { destPortListString = destPortListString.concat(",").concat(value); } else { @@ -1222,68 +1021,40 @@ public class FirewallConfigPolicy extends Policy { } } String destPortListInsert = "'"+destPortListString+"'"; - + /* * Create Queries to INSERT data into database tables and execute */ + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId("API"); + userInfo.setUserName("API"); - //Insert Into Terms table - String termSql = "INSERT INTO Term (ID, TERMNAME, SRCIPLIST, DESTIPLIST, PROTOCOLLIST, PORTLIST, SRCPORTLIST," - + " DESTPORTLIST, ACTION, DESCRIPTION, FROMZONE, TOZONE, CREATED_BY, MODIFIED_DATE) VALUES ("+termID+"," - +ruleName+","+srcListInsert+","+destListInsert+","+ "null"+","+"null"+","+"null"+","+destPortListInsert+"," - +action+","+description+","+fromZoneInsert+","+toZoneInsert+",'API',"+ "null"+ "); "; - - termSql = termSql.replace('"', '\''); - st.addBatch(termSql); + TermList termEntry = new TermList(); + termEntry.setTermName(ruleName); + termEntry.setSrcIPList(srcListInsert); + termEntry.setDestIPList(destListInsert); + termEntry.setProtocolList("null"); + termEntry.setPortList("null"); + termEntry.setSrcPortList("null"); + termEntry.setDestPortList(destPortListInsert); + termEntry.setAction(action); + termEntry.setDescription(description); + termEntry.setFromZones(fromZoneInsert); + termEntry.setToZones(toZoneInsert); + termEntry.setUserCreatedBy(userInfo); + dbConnection.save(termEntry); - rs = st.executeQuery("SELECT * FROM ACTIONLIST WHERE ACTIONNAME = " + action + ";"); - - String actionSql = null; - if (rs.next()) { - //do nothing - } else { - actionSql = "INSERT INTO ACTIONLIST (ID, ACTIONNAME, DESCRIPTION) VALUES ("+actionID+","+action+","+action+") "; - actionSql = actionSql.replace('"', '\''); - st.addBatch(actionSql); + List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action); + if(actionResult == null || actionResult.isEmpty()){ + ActionList actionEntry = new ActionList(); + actionEntry.setActionName(action); + actionEntry.setDescription(action); + dbConnection.save(actionEntry); } - st.executeBatch(); } - } - - if (path.contains("serviceGroups")) { - int serviceGroupID = 0; - int serviceListID = 0; - int protocolID = 0; - int portID = 0; - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM SERVICEGROUP;"); - if(rs.next()){ - serviceGroupID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM GROUPSERVICELIST;"); - if(rs.next()){ - serviceListID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PROTOCOLLIST;"); - if(rs.next()){ - protocolID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PORTLIST;"); - if(rs.next()){ - portID = rs.getInt("ID"); - } - rs.close(); - - String insertQuery = null; - + if (path.contains("serviceGroups")) { /* * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables */ @@ -1293,14 +1064,14 @@ public class FirewallConfigPolicy extends Policy { */ //create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(si); - + String groupName = svcGroupListobj.get("name").toString().replace('"', '\''); - + String description = null; if (svcGroupListobj.containsKey("description")){ description = svcGroupListobj.get("description").toString().replace('"', '\''); } - + JsonArray membersArray = svcGroupListobj.getJsonArray("members"); Boolean isServiceGroup = false; @@ -1310,23 +1081,20 @@ public class FirewallConfigPolicy extends Policy { isServiceGroup = true; } } - + //Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { - - rs = st.executeQuery("SELECT * FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";"); - - if (rs.next()) { - st.executeUpdate("DELETE FROM GROUPSERVICELIST WHERE NAME = "+ groupName + ";"); + List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName); + if(result != null && !result.isEmpty()){ + GroupServiceList groupEntry = (GroupServiceList) result.get(0); + dbConnection.delete(groupEntry); } - rs.close(); - //increment ID Primary Keys - serviceListID = serviceListID + 1; + String name = null; for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); String type = membersObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ value = membersObj.get("name").toString(); @@ -1335,125 +1103,88 @@ public class FirewallConfigPolicy extends Policy { } else { value = membersObj.get("value").toString(); } - + if(value != null){ value = value.replace("\"", ""); } - + if (name != null) { name = name.concat(",").concat(value); } else { name = value; } } - String nameInsert = "'"+name+"'"; - - insertQuery = "INSERT INTO GROUPSERVICELIST (ID, NAME, SERVICELIST) " - + "VALUES("+serviceListID+","+groupName+","+nameInsert+")"; - - //Replace double quote with single quote - insertQuery = insertQuery.replace('"', '\''); - - //Execute the queries to Insert data - st.executeUpdate(insertQuery); - + String nameInsert = "'"+name+"'"; + GroupServiceList groupServiceEntry = new GroupServiceList(); + groupServiceEntry.setGroupName(groupName); + groupServiceEntry.setServiceList(nameInsert); + dbConnection.save(groupServiceEntry); } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table - - //increment ID Primary Keys - protocolID = protocolID + 1; - portID = portID + 1; - serviceGroupID = serviceGroupID + 1; - String type = svcGroupListobj.get("type").toString().replace('"', '\''); String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); String ports = svcGroupListobj.get("ports").toString().replace('"', '\''); - rs = st.executeQuery("SELECT * FROM SERVICEGROUP WHERE NAME = "+ groupName + ";"); - - if (rs.next()) { - st.executeUpdate("DELETE FROM SERVICEGROUP WHERE NAME = "+ groupName + ";"); + List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName); + if(result != null && !result.isEmpty()){ + ServiceList serviceEntry = (ServiceList) result.get(0); + dbConnection.delete(serviceEntry); } - rs.close(); - - String svcGroupSql = "INSERT INTO SERVICEGROUP (ID, NAME, DESCRIPTION, TYPE, TRANSPORTPROTOCOL, APPPROTOCOL, PORTS) " - + "VALUES("+serviceGroupID+","+groupName+","+description+","+type+"," - + transportProtocol+","+"null,"+ports+"); "; - svcGroupSql = svcGroupSql.replace('"', '\''); - st.addBatch(svcGroupSql); - rs = st.executeQuery("SELECT * FROM PROTOCOLLIST WHERE PROTOCOLNAME = " + transportProtocol + ";"); + ServiceList serviceListEntry = new ServiceList(); + serviceListEntry.setServiceName(groupName); + serviceListEntry.setServiceDescription(description); + serviceListEntry.setServiceType(type); + serviceListEntry.setServiceTransProtocol(transportProtocol); + serviceListEntry.setServiceAppProtocol("null"); + serviceListEntry.setServicePorts(ports); + dbConnection.save(serviceListEntry); - String protoSql = null; - if (rs.next()) { - //do nothing - } else { - protoSql = "INSERT INTO PROTOCOLLIST (ID, PROTOCOLNAME, DESCRIPTION) " - + "VALUES("+protocolID+","+transportProtocol+","+transportProtocol+"); "; - protoSql = protoSql.replace('"', '\''); - st.addBatch(protoSql); - + List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); + if(protocolResult == null || protocolResult.isEmpty()){ + ProtocolList protocolEntry = new ProtocolList(); + protocolEntry.setProtocolName(transportProtocol); + protocolEntry.setDescription(transportProtocol); + dbConnection.save(protocolEntry); } - rs.close(); - - rs = st.executeQuery("SELECT * FROM PORTLIST WHERE PORTNAME = " + ports + ";"); - String portSql = null; - if (rs.next()) { - //do nothing - } else { - portSql = "INSERT INTO PORTLIST (ID, PORTNAME, DESCRIPTION) VALUES("+portID+","+ports+","+ports+"); "; - portSql = portSql.replace('"', '\''); - st.addBatch(portSql); + List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports); + if(portResult == null || portResult.isEmpty()){ + PortList portEntry = new PortList(); + portEntry.setPortName(ports); + portEntry.setDescription(ports); + dbConnection.save(portEntry); } - rs.close(); - st.executeBatch(); } } } - + if (path.contains("addressGroups")) { /* * Inserting addressGroup data into the ADDRESSGROUP table */ - int prefixID = 0; - int addressID = 0; - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM PREFIXLIST;"); - if(rs.next()){ - prefixID = rs.getInt("ID"); - } - rs.close(); - - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM ADDRESSGROUP;"); - if(rs.next()){ - addressID = rs.getInt("ID"); - } - rs.close(); - - String insertQuery = null; for(int ai=0; ai < addressGroup.size() ; ai++) { - + /* * Populate ArrayLists with values from the JSON */ //create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(ai); - + //create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\''); - + String description = null; if (addressGroupObj.containsKey("description")){ description = addressGroupObj.get("description").toString().replace('"', '\''); } - + String prefixIP = null; String type = null; for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); type = membersObj.get("type").toString().replace("\"", ""); - + String value = null; if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ value = membersObj.get("name").toString(); @@ -1462,130 +1193,97 @@ public class FirewallConfigPolicy extends Policy { } else { value = membersObj.get("value").toString(); } - + if(value != null){ value = value.replace("\"", ""); } - + if (prefixIP != null) { prefixIP = prefixIP.concat(",").concat(value); } else { prefixIP = value; } } - String prefixList = "'"+prefixIP+"'"; + String prefixList = "'"+prefixIP+"'"; Boolean isAddressGroup = type.contains("REFERENCE"); - - if (isAddressGroup) { - - rs = st.executeQuery("SELECT * FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";"); - - if (rs.next()) { - st.executeUpdate("DELETE FROM ADDRESSGROUP WHERE NAME = "+ addressGroupName + ";"); + + if (isAddressGroup) { + List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); + if(result != null && !result.isEmpty()){ + AddressGroup addressGroupEntry = (AddressGroup) result.get(0); + dbConnection.delete(addressGroupEntry); } - rs.close(); - //increment ID Primary Keys - addressID = addressID + 1; - - insertQuery = "INSERT INTO ADDRESSGROUP (ID, NAME, DESCRIPTION, PREFIXLIST) " - + "VALUES("+addressID+","+addressGroupName+","+description+","+prefixList+")"; - - - + AddressGroup newAddressGroup = new AddressGroup(); + newAddressGroup.setGroupName(addressGroupName); + newAddressGroup.setDescription(description); + newAddressGroup.setServiceList(prefixList); + dbConnection.save(newAddressGroup); } else { - - rs = st.executeQuery("SELECT * FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";"); - - if (rs.next()) { - st.executeUpdate("DELETE FROM PREFIXLIST WHERE PL_NAME = "+ addressGroupName + ";"); + List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); + if(result != null && !result.isEmpty()){ + PrefixList prefixListEntry = (PrefixList) result.get(0); + dbConnection.delete(prefixListEntry); } - rs.close(); - //increment ID Primary Key - prefixID = prefixID + 1; - - insertQuery = "INSERT INTO PREFIXLIST (ID, PL_NAME, PL_VALUE, DESCRIPTION) " - + "VALUES("+prefixID+","+addressGroupName+","+prefixList+","+description+")"; - + PrefixList newPrefixList = new PrefixList(); + newPrefixList.setPrefixListName(addressGroupName); + newPrefixList.setDescription(description); + newPrefixList.setPrefixListValue(prefixList); + dbConnection.save(newPrefixList); } - //Replace double quote with single quote - insertQuery = insertQuery.replace('"', '\''); - - //Execute the queries to Insert data - st.executeUpdate(insertQuery); } } } - + /* * Remove duplicate values from 'lookup' dictionary tables */ //ProtocolList Table String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 " + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;"; - st.addBatch(protoDelete); - + dbConnection.updateQuery(protoDelete); + //PortList Table String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; - st.addBatch(portListDelete); - + dbConnection.updateQuery(portListDelete); + //PrefixList Table String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; - st.addBatch(prefixListDelete); - + dbConnection.updateQuery(prefixListDelete); + //GroupServiceList String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " + "groupservicelist.serviceList = g1.serviceList; "; - st.addBatch(groupServiceDelete); - - st.executeBatch(); - - } catch (ClassNotFoundException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception building Firewall queries"); - System.out.println(e.getMessage()); - return false; - - } catch (SQLException e) { + dbConnection.updateQuery(groupServiceDelete); + }catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries"); - System.out.println(e.getMessage()); return false; - } finally { - try{ - if (con!=null) con.close(); - if (rs!=null) rs.close(); - if (st!=null) st.close(); - } catch (Exception ex){} } return true; - } else { return false; } - -} - + + } + private JsonObject stringToJson(String jsonString) { - JsonObject json = null; if (jsonString != null) { - //Read jsonBody to JsonObject StringReader in = null; - in = new StringReader(jsonString); - + JsonReader jsonReader = Json.createReader(in); json = jsonReader.readObject(); + jsonReader.close(); } - return json; } - - + private JsonNode createPatch(String json, String oldJson) { JsonNode oldJason = null; JsonNode updatedJason = null; @@ -1596,20 +1294,12 @@ public class FirewallConfigPolicy extends Policy { } catch (IOException e) { LOGGER.error("Exception Occured"+e); } - - JsonPatch jsonPatch = JsonDiff.asJsonPatch(oldJason, updatedJason); - JsonNode patchNode = JsonDiff.asJson(oldJason, updatedJason); - System.out.println("Sending Patch:" + jsonPatch); - return patchNode; - - } + return JsonDiff.asJson(oldJason, updatedJason); + } @Override public Object getCorrectPolicyDataObject() { return policyAdapter.getPolicyData(); } -} - - - +}
\ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java index 95172ac74..94f83674b 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java @@ -97,7 +97,7 @@ public class DictionaryImportController { List<String[]> dictSheet = csvReader.readAll(); if(dictionaryName.startsWith("Attribute")){ for(int i = 1; i< dictSheet.size(); i++){ - Attribute attribute = new Attribute("", userId); + Attribute attribute = new Attribute(""); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index dce0dd613..8d253d385 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -86,7 +86,7 @@ public class MicroServiceDictionaryController { - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.msEcompName, XACMLPapServlet.msPolicyName); + MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsEcompName(), XACMLPapServlet.getMsPolicyName()); private MicroServiceModels newModel; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index c21164920..dde2a0d3b 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -162,7 +162,7 @@ public class PolicyCreation extends AbstractPolicyCreation{ } if(highestVersion != 0 && policyVersion != null){ - if(policyData.isEditPolicy){ + if(policyData.isEditPolicy()){ version = highestVersion +1; if(userId ==null){ modifiedBy = "API"; @@ -401,7 +401,7 @@ public class PolicyCreation extends AbstractPolicyCreation{ successMap = newPolicy.savePolicies(); if(successMap.containsKey("success")){ policyDBDaoTransaction.commitTransaction(); - if(policyData.isEditPolicy){ + if(policyData.isEditPolicy()){ commonClassDao.update(policyVersionDao); }else{ commonClassDao.save(policyVersionDao); |