X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=blobdiff_plain;f=ONAP-PAP-REST%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Fpap%2Fxacml%2Frest%2Fcomponents%2FPolicyDBDao.java;h=9f5933850caa90928f08d117643343d0dc43d821;hp=ba8057102a76cada108c535229a4d9a3428227b1;hb=38094965cb1e32186a7305f05d332b6ca29cd970;hpb=0e45b29c2356e74f5185744f661082e6cf00b72e diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java index ba8057102..9f5933850 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java @@ -71,23 +71,6 @@ import org.springframework.stereotype.Component; @Component public class PolicyDBDao { private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); - private List otherServers; - - public List getOtherServers() { - return otherServers; - } - - public void setOtherServers(List otherServers) { - this.otherServers = otherServers; - } - - private static PolicyDBDao currentInstance = null; - private PAPPolicyEngine papEngine; - - public PAPPolicyEngine getPapEngine() { - return papEngine; - } - public static final String JSON_CONFIG = "JSON"; public static final String XML_CONFIG = "XML"; public static final String PROPERTIES_CONFIG = "PROPERTIES"; @@ -103,33 +86,33 @@ public class PolicyDBDao { public static final String PDPENTITY_SELECT = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; public static final String GROUP_NOT_FOUND = "The group could not be found with id "; - public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted"; + public static final String FOUND_IN_DB_NOT_DEL = + " were found in the database that are not deleted"; public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id "; - public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database"; + public static final String DELETED_STATUS_FOUND = + " and deleted status were found in the database"; public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id "; public static final String PDP_ID = "pdpId"; - public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group"; + public static final String QUERY_FAILED_FOR_GROUP = + "Query failed trying to check for existing group"; public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group "; public static final String SCOPE = "scope"; public static final String POLICYDBDAO_VAR = "PolicyDBDao"; public static final String DUP_POLICYID = "Somehow, more than one policy with the id "; public static final String FOUND_IN_DB = " were found in the database"; - - - public static boolean isJunit = false; - - public static void setJunit(boolean isJunit) { - PolicyDBDao.isJunit = isJunit; - } - + private static PolicyDBDao currentInstance = null; + private static boolean isJunit = false; private static SessionFactory sessionfactory; + private List otherServers; + private PAPPolicyEngine papEngine; + /** * Gets the current instance of PolicyDBDao. * * @return The instance of PolicyDBDao or throws exception if the given instance is null. - * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance - * (EntityManagerFactory emf) to get this. + * @throws IllegalStateException if a PolicyDBDao instance is null. Call + * createPolicyDBDaoInstance (EntityManagerFactory emf) to get this. */ public static PolicyDBDao getPolicyDBDaoInstance() { logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); @@ -157,8 +140,8 @@ public class PolicyDBDao { public PolicyDBDao(String init) { // not needed in this release if (!register()) { - PolicyLogger - .error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); + PolicyLogger.error( + "This server's PolicyDBDao instance could not be registered and may not reveive updates"); } otherServers = getRemotePolicyDBDaoList(); @@ -173,16 +156,18 @@ public class PolicyDBDao { // not static because we are going to be using the instance's emf // waitTime in ms to wait for lock, or -1 to wait forever (no) @SuppressWarnings("deprecation") - public void startTransactionSynced(Session session, int waitTime) throws InterruptedException { - logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced(" - + session + "," + waitTime + ") called\n\n"); + public void startTransactionSynced(Session session, int waitTime) { + logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + + "\n startTransactionSynced(" + session + "," + waitTime + ") called\n\n"); DatabaseLockEntity lock = null; session.beginTransaction(); try { if (logger.isDebugEnabled()) { - logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n"); + logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + + "\n\n"); } - lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE); + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, + LockMode.PESSIMISTIC_WRITE); if (logger.isDebugEnabled()) { logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); } @@ -216,7 +201,8 @@ public class PolicyDBDao { try { session.close(); } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e); } } return policyDBDaoEntityList; @@ -236,9 +222,11 @@ public class PolicyDBDao { public PolicyDBDaoTransaction getNewAuditTransaction() { logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); // Use the standard transaction wait time in ms - int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + int auditWaitMs = Integer + .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); // Use the (extended) audit timeout time in ms - int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int auditTimeoutMs = Integer + .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs); } @@ -249,7 +237,8 @@ public class PolicyDBDao { * @param two A String or null to compare */ public static boolean stringEquals(String one, String two) { - logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called"); + logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + + ") called"); if (one == null && two == null) { return true; } @@ -283,13 +272,15 @@ public class PolicyDBDao { urlUserPass[2] = commaSplit[2]; } if (urlUserPass[1] == null || "".equals(urlUserPass[1])) { - String usernamePropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String usernamePropertyValue = + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); if (usernamePropertyValue != null) { urlUserPass[1] = usernamePropertyValue; } } if (urlUserPass[2] == null || "".equals(urlUserPass[2])) { - String passwordPropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + String passwordPropertyValue = + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); if (passwordPropertyValue != null) { urlUserPass[2] = passwordPropertyValue; } @@ -314,7 +305,7 @@ public class PolicyDBDao { Session session = sessionfactory.openSession(); try { startTransactionSynced(session, 1000); - } catch (InterruptedException | IllegalStateException e) { + } catch (IllegalStateException e) { logger.debug("\nPolicyDBDao.register() caught an IllegalStateException: \n" + e + "\n"); DatabaseLockEntity lock; lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1); @@ -341,7 +332,8 @@ public class PolicyDBDao { } } } - logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); + logger.debug( + "\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); PolicyDBDaoEntity foundPolicyDBDaoEntity = null; Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); cr.add(Restrictions.eq("policyDBDaoUrl", url[0])); @@ -356,7 +348,8 @@ public class PolicyDBDao { txt = CryptoUtils.encryptTxt(url[2].getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Could not encrypt PAP password"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "Could not encrypt PAP password"); } if (foundPolicyDBDaoEntity == null) { PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity(); @@ -408,8 +401,8 @@ public class PolicyDBDao { * This method is called during all pushPolicy transactions and makes sure the file system group * is in sync with the database groupentity */ - public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) - throws PAPException, PolicyDBException { + public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, + GroupEntity groupentity) throws PAPException, PolicyDBException { HashMap currentPolicyMap = new HashMap<>(); HashSet newPolicyIdSet = new HashSet<>(); @@ -429,19 +422,23 @@ public class PolicyDBDao { // convert PolicyEntity object to PDPPolicy String name = pdpPolicyId.replace(".xml", ""); name = name.substring(0, name.lastIndexOf('.')); - InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); + InputStream policyStream = + new ByteArrayInputStream(policy.getPolicyData().getBytes()); pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream); - URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); + URI location = + Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId) + .toUri(); StdPDPPolicy newPolicy = null; try { newPolicy = new StdPDPPolicy(pdpPolicyId, true, removeExtensionAndVersionFromPolicyName(pdpPolicyId), location); newPolicySet.add(newPolicy); - logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location); + logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + + ", Location - " + location); } catch (Exception e) { logger.debug(e); - PolicyLogger - .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + PolicyLogger.error( + "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + e.getMessage()); } } @@ -453,20 +450,22 @@ public class PolicyDBDao { Files.delete(Paths.get(currentPolicyMap.get(id).getLocation())); } catch (Exception e) { logger.debug(e); - PolicyLogger - .error("PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. " + PolicyLogger.error( + "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. " + e.getMessage()); } } } - logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); + logger.info( + "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); pdpGroup.setPolicies(newPolicySet); return pdpGroup; } - public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDBException { + public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) + throws PolicyDBException { return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; } @@ -476,7 +475,8 @@ public class PolicyDBDao { * @param originalPolicyName: a policy file name ex: Config_policy.2.xml * @return An array [0]: The policy name, [1]: the policy version, as a string */ - public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException { + public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) + throws PolicyDBException { String policyName = originalPolicyName; String[] nameAndVersion = new String[2]; try { @@ -520,7 +520,8 @@ public class PolicyDBDao { deleteAllGroupTables(); auditGroups(papEngine2); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "auditLocalDatabase() error"); logger.error("Exception Occured" + e); } } @@ -540,7 +541,8 @@ public class PolicyDBDao { if (groupQueryList != null && !groupQueryList.isEmpty()) { GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0); updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup); - logger.info("Group was updated during file system audit: " + updatedGroup.toString()); + logger.info( + "Group was updated during file system audit: " + updatedGroup.toString()); } } catch (PAPException | PolicyDBException e) { logger.error(e); @@ -548,7 +550,8 @@ public class PolicyDBDao { logger.error(e); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists"); + throw new PersistenceException( + "Query failed trying to check if group " + group.getId() + " exists"); } session.getTransaction().commit(); @@ -575,7 +578,8 @@ public class PolicyDBDao { final Criteria configDataQuery = session.createCriteria(cl.getName()); @SuppressWarnings("unchecked") final List configDataResult = configDataQuery.list(); - Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type); + Path webappsPath = Paths + .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type); for (final T configData : configDataResult) { String configName = null; @@ -583,14 +587,16 @@ public class PolicyDBDao { try { if (CONFIG.equalsIgnoreCase(type)) { configName = ((ConfigurationDataEntity) configData).getConfigurationName(); - configBody = (((ConfigurationDataEntity) configData).getConfigBody() != null) - ? ((ConfigurationDataEntity) configData).getConfigBody() - .getBytes(StandardCharsets.UTF_8) - : "".getBytes(); + configBody = + (((ConfigurationDataEntity) configData).getConfigBody() != null) + ? ((ConfigurationDataEntity) configData).getConfigBody() + .getBytes(StandardCharsets.UTF_8) + : "".getBytes(); } else { configName = ((ActionBodyEntity) configData).getActionBodyName(); configBody = (((ActionBodyEntity) configData).getActionBody() != null) - ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8) + ? ((ActionBodyEntity) configData).getActionBody() + .getBytes(StandardCharsets.UTF_8) : "".getBytes(); } Path filePath = Paths.get(webappsPath.toString(), configName); @@ -663,13 +669,15 @@ public class PolicyDBDao { for (PDPPolicy policy : policies) { try { - String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); + String[] stringArray = + getNameScopeAndVersionFromPdpPolicy(policy.getId()); if (stringArray == null) { throw new IllegalArgumentException( "Invalid input - policyID must contain name, scope and version"); } List policyEntityList; - Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope"); + Query getPolicyEntitiesQuery = + session.getNamedQuery("PolicyEntity.findByNameAndScope"); getPolicyEntitiesQuery.setParameter("name", stringArray[0]); getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]); @@ -693,7 +701,8 @@ public class PolicyDBDao { } } catch (Exception e) { session.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "Exception auditGroups outer catch"); session.close(); return; } @@ -715,8 +724,9 @@ public class PolicyDBDao { // config type selection for saving. public String getConfigFile(String inputFilename, String configType) { String filename = inputFilename; - logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename - + ", " + configType + ") called"); + logger.debug( + "getConfigFile(String filename, String scope, String configType) as getConfigFile(" + + filename + ", " + configType + ") called"); filename = FilenameUtils.removeExtension(filename); String id = configType; @@ -797,6 +807,27 @@ public class PolicyDBDao { return false; } + public List getOtherServers() { + return otherServers; + } + + public void setOtherServers(List otherServers) { + this.otherServers = otherServers; + } + + public PAPPolicyEngine getPapEngine() { + return papEngine; + } + + + public static boolean isJunit() { + return isJunit; + } + + public static void setJunit(boolean isJunit) { + PolicyDBDao.isJunit = isJunit; + } + public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() { return new PolicyDBDao().new PolicyDBDaoTestClass(); } @@ -806,7 +837,8 @@ public class PolicyDBDao { return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); } - String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException { + String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) + throws PolicyDBException { return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); }