diff options
author | adheli.tavares <adheli.tavares@est.tech> | 2024-08-29 15:58:06 +0100 |
---|---|---|
committer | adheli.tavares <adheli.tavares@est.tech> | 2024-08-29 15:59:31 +0100 |
commit | f875828ecc091dc505697ac98256ba06aff9a20a (patch) | |
tree | 62f23931de0fa3dce16021bc8badd6822cdd615a /integrity-audit/src | |
parent | 63d23a4aa0f3aeae9d6470b95dfa8f87b2d85aa8 (diff) |
Remove modules not being used
Remove modules common-logging, integrity-audity and
integrity-monitor as they are not being used in any component.
Issue-ID: POLICY-5123
Change-Id: I571f17236a3c8bb9e8e52c99d0298f4098cb5ca9
Signed-off-by: adheli.tavares <adheli.tavares@est.tech>
Diffstat (limited to 'integrity-audit/src')
30 files changed, 0 insertions, 6442 deletions
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java deleted file mode 100644 index 03fbdb57..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java +++ /dev/null @@ -1,771 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Properties; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - -/** - * AuditThread is the main thread for the IntegrityAudit. - * - */ -public class AuditThread extends Thread { - - private static final Logger logger = FlexLogger.getLogger(AuditThread.class); - - /* - * Number of milliseconds that must elapse for audit to be considered complete. It's public for - * access by JUnit test logic. - */ - public static final long AUDIT_COMPLETION_INTERVAL = 30000L; - - /** - * Number of audit cycles before the completion flag is reset. - */ - public static final int AUDIT_RESET_CYCLES = 2; - - /* - * Unless audit has already been run on this entity, number of milliseconds to sleep between - * audit thread iterations. If audit has already been run, we sleep integrityAuditPeriodMillis. - * May be modified by JUnit tests. - */ - private static final long AUDIT_THREAD_SLEEP_INTERVAL_MS = 5000L; - - /* - * String constants. - */ - private static final String AUDIT_THREAD_MESSAGE = "AuditThread.run: resourceName="; - private static final String ENTITY_INDEX_MESSAGE = ", entityIndex="; - private static final String LAST_UPDATED_MESSAGE = ", lastUpdated="; - private static final String PERSISTENCE_MESSAGE = ", persistenceUnit="; - - /* - * DB access class. - */ - private DbDao dbDao; - - /* - * E.g. pdp_xacml - */ - private String nodeType; - - /* - * Persistence unit for which this audit is being run. - */ - private String persistenceUnit; - - /* - * Name of this resource - */ - private String resourceName; - - /* - * E.g. DB_DRIVER, SITE_NAME, NODE_TYPE - */ - private Properties properties; - - /* - * See IntegrityAudit class for usage. - */ - private int integrityAuditPeriodSeconds; - - /* - * The containing IntegrityAudit instance - */ - private IntegrityAudit integrityAudit; - - /* - * Used to create a list that is sorted lexicographically by resourceName. - */ - Comparator<IntegrityAuditEntity> comparator = (r1, r2) -> r1.getResourceName().compareTo(r2.getResourceName()); - - /** - * AuditThread constructor. - * - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param properties the properties - * @param integrityAuditPeriodSeconds the integrity audit period in seconds - * @param integrityAudit the integrity audit - * @throws IntegrityAuditException if an error occurs - */ - public AuditThread(String resourceName, String persistenceUnit, Properties properties, - int integrityAuditPeriodSeconds, IntegrityAudit integrityAudit) throws IntegrityAuditException { - - this.resourceName = resourceName; - this.persistenceUnit = persistenceUnit; - this.properties = properties; - this.integrityAuditPeriodSeconds = integrityAuditPeriodSeconds; - this.integrityAudit = integrityAudit; - - /* - * The DbDao Constructor registers this node in the IntegrityAuditEntity table. Each - * resource (node) inserts its own name, persistenceUnit, DB access properties and other - * pertinent properties in the table. This allows the audit on each node to compare its own - * version of the entities for the persistenceUnit in question with the versions from all - * other nodes of similar type. - */ - dbDao = new DbDao(this.resourceName, this.persistenceUnit, this.properties); - this.nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE).toLowerCase(); - - } - - @Override - public void run() { - - logger.info("AuditThread.run: Entering"); - - try { - // for junit testing - runStarted(); - - /* - * Triggers change in designation, unless no other viable candidate. - */ - runUntilInterrupted(); - - } catch (InterruptedException e) { - handleAuditLoopException(e); - Thread.currentThread().interrupt(); - - } catch (Exception e) { - handleAuditLoopException(e); - } - - dbDao.destroy(); - - logger.info("AuditThread.run: Exiting"); - } - - private void handleAuditLoopException(Exception exception) { - String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + exception.getMessage(); - logger.error(MessageCodes.EXCEPTION_ERROR, exception, msg); - integrityAudit.setThreadInitialized(false); - } - - private void runUntilInterrupted() throws InterruptedException { - var auditCompleted = false; - - var dbAudit = new DbAudit(dbDao); - - IntegrityAuditEntity entityCurrentlyDesignated; - IntegrityAuditEntity thisEntity; - integrityAudit.setThreadInitialized(true); // An exception will set it to false - - var interrupted = false; - - while (!interrupted) { - try { - /* - * It may have been awhile since we last cycled through this loop, so refresh - * the list of IntegrityAuditEntities. - */ - List<IntegrityAuditEntity> integrityAuditEntityList = getIntegrityAuditEntityList(); - - /* - * We could've set entityCurrentlyDesignated as a side effect of - * getIntegrityAuditEntityList(), but then we would've had to make - * entityCurrentlyDesignated a class level attribute. Using this approach, we - * can keep it local to the run() method. - */ - entityCurrentlyDesignated = getEntityCurrentlyDesignated(integrityAuditEntityList); - - /* - * Need to refresh thisEntity each time through loop, because we need a fresh - * version of lastUpdated. - */ - thisEntity = getThisEntity(integrityAuditEntityList); - - /* - * If we haven't done the audit yet, note that we're current and see if we're - * designated. - */ - auditCompleted = doAudit(auditCompleted, dbAudit, entityCurrentlyDesignated, thisEntity, - integrityAuditEntityList); - - /* - * If we've just run audit, sleep per the integrity_audit_period_seconds - * property, otherwise just sleep the normal interval. - */ - sleepAfterAudit(auditCompleted); - - } catch (Exception e) { - if (isInterruptedException(e)) { - String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + "; Stopping."; - logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); - Thread.currentThread().interrupt(); - interrupted = true; - - } else { - String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() - + "; Will try audit again in " + integrityAuditPeriodSeconds + " seconds"; - logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); - // Sleep and try again later - AuditorTime.getInstance().sleep(integrityAuditPeriodSeconds * 1000L); - } - } - } - } - - private boolean doAudit(boolean auditCompleted, DbAudit dbAudit, IntegrityAuditEntity entityCurrentlyDesignated, - IntegrityAuditEntity thisEntity, List<IntegrityAuditEntity> integrityAuditEntityList) - throws IntegrityAuditException { - - if (!auditCompleted) { - dbDao.setLastUpdated(); - - /* - * If no current designation or currently designated node is stale, see if - * we're the next node to be designated. - */ - if (entityCurrentlyDesignated == null || isStale(entityCurrentlyDesignated)) { - IntegrityAuditEntity designationCandidate = - getDesignationCandidate(integrityAuditEntityList); - - /* - * If we're the next node to be designated, run the audit. - */ - if (designationCandidate.getResourceName().equals(this.resourceName)) { - runAudit(dbAudit); - auditCompleted = true; - } else if (logger.isDebugEnabled()) { - logger.debug("AuditThread.run: designationCandidate, " + designationCandidate.getResourceName() - + ", not this entity, " + thisEntity.getResourceName()); - } - - /* - * Application may have been stopped and restarted, in which case we - * might be designated but auditCompleted will have been reset to false, - * so account for this. - */ - } else if (thisEntity.getResourceName().equals(entityCurrentlyDesignated.getResourceName())) { - - if (logger.isDebugEnabled()) { - logger.debug("AuditThread.run: Re-running audit for " + thisEntity.getResourceName()); - } - runAudit(dbAudit); - auditCompleted = true; - - } else if (logger.isDebugEnabled()) { - logger.debug("AuditThread.run: Currently designated node, " - + entityCurrentlyDesignated.getResourceName() + ", not yet stale and not this node"); - } - - - /* - * Audit already completed on this node, so allow the node to go stale until - * twice the AUDIT_COMPLETION_PERIOD has elapsed. This should give plenty of - * time for another node (if another node is out there) to pick up - * designation. - */ - } else { - - auditCompleted = resetAuditCompleted(auditCompleted, thisEntity); - - } - return auditCompleted; - } - - private void sleepAfterAudit(boolean auditCompleted) throws InterruptedException { - if (auditCompleted) { - // for junit testing: indicate that an audit has completed - auditCompleted(); - - if (logger.isDebugEnabled()) { - logger.debug("AuditThread.run: Audit completed; resourceName=" + this.resourceName - + " sleeping " + integrityAuditPeriodSeconds + "s"); - } - AuditorTime.getInstance().sleep(integrityAuditPeriodSeconds * 1000L); - if (logger.isDebugEnabled()) { - logger.debug(AUDIT_THREAD_MESSAGE + this.resourceName + " awaking from " - + integrityAuditPeriodSeconds + "s sleep"); - } - - } else { - - if (logger.isDebugEnabled()) { - logger.debug(AUDIT_THREAD_MESSAGE + this.resourceName + ": Sleeping " - + AuditThread.AUDIT_THREAD_SLEEP_INTERVAL_MS + "ms"); - } - AuditorTime.getInstance().sleep(AuditThread.AUDIT_THREAD_SLEEP_INTERVAL_MS); - if (logger.isDebugEnabled()) { - logger.debug(AUDIT_THREAD_MESSAGE + this.resourceName + ": Awaking from " - + AuditThread.AUDIT_THREAD_SLEEP_INTERVAL_MS + "ms sleep"); - } - - } - } - - /** - * Determines if an exception is an InterruptedException or was caused by an - * InterruptedException. - * - * @param ex exception to be examined - * @return {@code true} if it's an InterruptedException, {@code false} otherwise - */ - private boolean isInterruptedException(Throwable ex) { - while (ex != null) { - if (ex instanceof InterruptedException) { - return true; - } - - ex = ex.getCause(); - } - - return false; - } - - /** - * getDesignationCandidate() Using round robin algorithm, gets next candidate to be designated. - * Assumes list is sorted lexicographically by resourceName. - */ - private IntegrityAuditEntity getDesignationCandidate(List<IntegrityAuditEntity> integrityAuditEntityList) { - - // Note: assumes integrityAuditEntityList is already lexicographically sorted by - // resourceName - - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: Entering, integrityAuditEntityList.size()=" - + integrityAuditEntityList.size()); - } - - IntegrityAuditEntity thisEntity = null; - - var designatedEntityIndex = -1; - var entityIndex = 0; - var priorCandidateIndex = -1; - var subsequentCandidateIndex = -1; - - for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) { - - if (logger.isDebugEnabled()) { - logIntegrityAuditEntity(integrityAuditEntity); - } - - thisEntity = detmEntity(integrityAuditEntity, thisEntity); - - if (integrityAuditEntity.isDesignated()) { - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: Currently designated entity resourceName=" - + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE - + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE - + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex); - } - designatedEntityIndex = entityIndex; - - /* - * Entity not currently designated - */ - } else if (isStale(integrityAuditEntity)) { - /* - * Non-designated entity is stale. - */ - - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: Entity is stale; resourceName=" - + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE - + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE - + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex); - } - - /* - * Entity is current. - */ - } else if (designatedEntityIndex == -1) { - priorCandidateIndex = detmPriorCandidate(entityIndex, integrityAuditEntity, priorCandidateIndex); - - } else { - subsequentCandidateIndex = - detmSubsequentCandidate(entityIndex, integrityAuditEntity, subsequentCandidateIndex); - } - - entityIndex++; - - } // end for loop - - return detmDesignationCandidate(integrityAuditEntityList, thisEntity, priorCandidateIndex, - subsequentCandidateIndex); - } - - private IntegrityAuditEntity detmEntity(IntegrityAuditEntity integrityAuditEntity, - IntegrityAuditEntity thisEntity) { - if (integrityAuditEntity.getResourceName().equals(this.resourceName)) { - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: thisEntity=" + integrityAuditEntity.getResourceName()); - } - thisEntity = integrityAuditEntity; - } - return thisEntity; - } - - private int detmPriorCandidate(int entityIndex, IntegrityAuditEntity integrityAuditEntity, - int priorCandidateIndex) { - if (priorCandidateIndex == -1) { - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: Prior candidate found, resourceName=" - + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE - + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE - + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex); - } - priorCandidateIndex = entityIndex; - } else { - if (logger.isDebugEnabled()) { - logger.debug( - "getDesignationCandidate: Prior entity current but prior candidate already " - + "found; resourceName=" + integrityAuditEntity.getResourceName() - + PERSISTENCE_MESSAGE + integrityAuditEntity.getPersistenceUnit() - + LAST_UPDATED_MESSAGE + integrityAuditEntity.getLastUpdated() - + ENTITY_INDEX_MESSAGE + entityIndex); - } - } - return priorCandidateIndex; - } - - private int detmSubsequentCandidate(int entityIndex, IntegrityAuditEntity integrityAuditEntity, - int subsequentCandidateIndex) { - if (subsequentCandidateIndex == -1) { - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: Subsequent candidate found, resourceName=" - + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE - + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE - + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex); - } - subsequentCandidateIndex = entityIndex; - } else { - if (logger.isDebugEnabled()) { - logger.debug( - "getDesignationCandidate: Subsequent entity current but subsequent candidate " - + "already found; resourceName=" - + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE - + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE - + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE - + entityIndex); - } - } - return subsequentCandidateIndex; - } - - private IntegrityAuditEntity detmDesignationCandidate(List<IntegrityAuditEntity> integrityAuditEntityList, - IntegrityAuditEntity thisEntity, int priorCandidateIndex, int subsequentCandidateIndex) { - IntegrityAuditEntity designationCandidate; - /* - * Per round robin algorithm, if a current entity is found that is lexicographically after - * the currently designated entity, this entity becomes the designation candidate. If no - * current entity is found that is lexicographically after currently designated entity, we - * cycle back to beginning of list and pick the first current entity as the designation - * candidate. - */ - if (subsequentCandidateIndex != -1) { - designationCandidate = integrityAuditEntityList.get(subsequentCandidateIndex); - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: Exiting and returning subsequent designationCandidate=" - + designationCandidate.getResourceName()); - } - } else { - if (priorCandidateIndex != -1) { - designationCandidate = integrityAuditEntityList.get(priorCandidateIndex); - if (logger.isDebugEnabled()) { - logger.debug("getDesignationCandidate: Exiting and returning prior designationCandidate=" - + designationCandidate.getResourceName()); - } - } else if (thisEntity != null) { - logger.debug("getDesignationCandidate: No subsequent or prior candidate found; designating thisEntity, " - + "resourceName=" + thisEntity.getResourceName()); - designationCandidate = thisEntity; - } else { - // this shouldn't happen, but adding it to make sonar happy - logger.debug("getDesignationCandidate: No entities available"); - designationCandidate = null; - } - } - - return designationCandidate; - } - - /** - * getEntityCurrentlyDesignated() Returns entity that is currently designated. - * - * @param integrityAuditEntityList the integrity audit entity list - * @return the currently designated integrity audit entity - */ - private IntegrityAuditEntity getEntityCurrentlyDesignated(List<IntegrityAuditEntity> integrityAuditEntityList) { - - if (logger.isDebugEnabled()) { - logger.debug("getEntityCurrentlyDesignated: Entering, integrityAuditEntityList.size=" - + integrityAuditEntityList.size()); - } - - IntegrityAuditEntity entityCurrentlyDesignated = null; - - for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) { - - if (integrityAuditEntity.isDesignated()) { - if (logger.isDebugEnabled()) { - logger.debug("getEntityCurrentlyDesignated: Currently designated entity resourceName=" - + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE - + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE - + integrityAuditEntity.getLastUpdated()); - } - entityCurrentlyDesignated = integrityAuditEntity; - } - - } // end for loop - - if (logger.isDebugEnabled()) { - if (entityCurrentlyDesignated != null) { - logger.debug("getEntityCurrentlyDesignated: Exiting and returning entityCurrentlyDesignated=" - + entityCurrentlyDesignated.getResourceName()); - } else { - logger.debug("getEntityCurrentlyDesignated: Exiting and returning entityCurrentlyDesignated=" - + entityCurrentlyDesignated); - } - } - return entityCurrentlyDesignated; - - } - - /** - * getIntegrityAuditEnityList gets the list of IntegrityAuditEntity. - * - * @return the list of IntegrityAuditEntity - * @throws DbDaoTransactionException if an error occurs getting the list of IntegrityAuditEntity - */ - private List<IntegrityAuditEntity> getIntegrityAuditEntityList() throws DbDaoTransactionException { - - if (logger.isDebugEnabled()) { - logger.debug("getIntegrityAuditEntityList: Entering"); - } - - /* - * Get all records for this nodeType and persistenceUnit and then sort them - * lexicographically by resourceName. Get index of designated entity, if any. - */ - /* - * Sorted list of entities for a particular nodeType and persistenceUnit. - */ - List<IntegrityAuditEntity> integrityAuditEntityList = - dbDao.getIntegrityAuditEntities(this.persistenceUnit, this.nodeType); - var listSize = integrityAuditEntityList.size(); - if (logger.isDebugEnabled()) { - logger.debug("getIntegrityAuditEntityList: Got " + listSize + " IntegrityAuditEntity records"); - } - Collections.sort(integrityAuditEntityList, comparator); - - if (logger.isDebugEnabled()) { - logger.debug( - "getIntegrityAuditEntityList: Exiting and returning integrityAuditEntityList, size=" + listSize); - } - return integrityAuditEntityList; - - } - - - /** - * Returns the IntegrityAuditEntity for this entity. - * - * @param integrityAuditEntityList the list of IntegrityAuditEntity - * @return the IntegrityAuditEntity for this entity - */ - private IntegrityAuditEntity getThisEntity(List<IntegrityAuditEntity> integrityAuditEntityList) { - - if (logger.isDebugEnabled()) { - logger.debug("getThisEntity: Entering, integrityAuditEntityList.size=" + integrityAuditEntityList.size()); - } - - IntegrityAuditEntity thisEntity = null; - - for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) { - - if (integrityAuditEntity.getResourceName().equals(this.resourceName)) { - if (logger.isDebugEnabled()) { - logger.debug( - "getThisEntity: For this entity, resourceName=" + integrityAuditEntity.getResourceName() - + PERSISTENCE_MESSAGE + integrityAuditEntity.getPersistenceUnit() - + LAST_UPDATED_MESSAGE + integrityAuditEntity.getLastUpdated()); - } - thisEntity = integrityAuditEntity; - } - - } // end for loop - - if (logger.isDebugEnabled()) { - if (thisEntity != null) { - logger.debug("getThisEntity: Exiting and returning thisEntity=" + thisEntity.getResourceName()); - } else { - logger.debug("getThisEntity: Exiting and returning thisEntity=" + thisEntity); - } - } - return thisEntity; - - } - - - /** - * Returns false if the lastUpdated time for the record in question is more than - * auditCompletionIntervalMillis seconds ago. During an audit, lastUpdated is updated every five - * seconds or so, but when an audit finishes, the node doing the audit stops updating - * lastUpdated. - * - * @param integrityAuditEntity the integrityAuditEntity - * @return false if the lastUpdated time for the record in question is more than - * auditCompletionIntervalMillis seconds ago - */ - private boolean isStale(IntegrityAuditEntity integrityAuditEntity) { - - if (logger.isDebugEnabled()) { - logger.debug("isStale: Entering, resourceName=" + integrityAuditEntity.getResourceName() - + PERSISTENCE_MESSAGE + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE - + integrityAuditEntity.getLastUpdated()); - } - - var stale = false; - - var currentTime = AuditorTime.getInstance().getDate(); - var lastUpdated = integrityAuditEntity.getLastUpdated(); - - /* - * If lastUpdated is null, we assume that the audit never ran for that node. - */ - long lastUpdatedTime = 0; - if (lastUpdated != null) { - lastUpdatedTime = lastUpdated.getTime(); - } - long timeDifference = currentTime.getTime() - lastUpdatedTime; - if (timeDifference > AUDIT_COMPLETION_INTERVAL) { - stale = true; - } - - if (logger.isDebugEnabled()) { - logger.debug("isStale: Exiting and returning stale=" + stale + ", timeDifference=" + timeDifference); - } - - return stale; - } - - private void logIntegrityAuditEntity(IntegrityAuditEntity integrityAuditEntity) { - - logger.debug("logIntegrityAuditEntity: id=" + integrityAuditEntity.getId() + ", jdbcDriver=" - + integrityAuditEntity.getJdbcDriver() + ", jdbcPassword=" + integrityAuditEntity.getJdbcPassword() - + ", jdbcUrl=" + integrityAuditEntity.getJdbcUrl() + ", jdbcUser=" + integrityAuditEntity.getJdbcUser() - + ", nodeType=" + integrityAuditEntity.getNodeType() + PERSISTENCE_MESSAGE - + integrityAuditEntity.getPersistenceUnit() + ", resourceName=" + integrityAuditEntity.getResourceName() - + ", site=" + integrityAuditEntity.getSite() + ", createdDate=" + integrityAuditEntity.getCreatedDate() - + LAST_UPDATED_MESSAGE + integrityAuditEntity.getLastUpdated() + ", designated=" - + integrityAuditEntity.isDesignated()); - } - - /* - * If more than (auditCompletionIntervalMillis * 2) milliseconds have elapsed since we last ran - * the audit, reset auditCompleted, so - * - * 1) we'll eventually re-run the audit, if no other node picks up the designation. - * - * or - * - * 2) We'll run the audit when the round robin comes back to us. - */ - private boolean resetAuditCompleted(boolean auditCompleted, IntegrityAuditEntity thisEntity) { - - if (logger.isDebugEnabled()) { - logger.debug("resetAuditCompleted: auditCompleted=" + auditCompleted + "; for thisEntity, resourceName=" - + thisEntity.getResourceName() + PERSISTENCE_MESSAGE + thisEntity.getPersistenceUnit() - + LAST_UPDATED_MESSAGE + thisEntity.getLastUpdated()); - } - - long timeDifference; - - var currentTime = AuditorTime.getInstance().getDate(); - var lastUpdated = thisEntity.getLastUpdated(); - - long lastUpdatedTime = lastUpdated.getTime(); - timeDifference = currentTime.getTime() - lastUpdatedTime; - - if (timeDifference > (AUDIT_COMPLETION_INTERVAL * AUDIT_RESET_CYCLES)) { - if (logger.isDebugEnabled()) { - logger.debug("resetAuditCompleted: Resetting auditCompleted for resourceName=" + this.resourceName); - } - auditCompleted = false; - } else { - if (logger.isDebugEnabled()) { - logger.debug( - "resetAuditCompleted: For resourceName=" + resourceName + ", time since last update is only " - + timeDifference + "; retaining current value for auditCompleted"); - } - } - - if (logger.isDebugEnabled()) { - logger.debug("resetAuditCompleted: Exiting and returning auditCompleted=" + auditCompleted - + ", timeDifference=" + timeDifference); - } - return auditCompleted; - } - - private void runAudit(DbAudit dbAudit) throws IntegrityAuditException { - - if (logger.isDebugEnabled()) { - logger.debug("runAudit: Entering, dbAudit=" + dbAudit + "; notifying other resources that resourceName=" - + this.resourceName + " is current"); - } - - /* - * changeDesignated marks all other nodes as non-designated and this node as designated. - */ - dbDao.changeDesignated(this.resourceName, this.persistenceUnit, this.nodeType); - - if (logger.isDebugEnabled()) { - logger.debug("runAudit: Running audit for persistenceUnit=" + this.persistenceUnit + " on resourceName=" - + this.resourceName); - } - - dbAudit.dbAudit(this.resourceName, this.persistenceUnit, this.nodeType); - - if (logger.isDebugEnabled()) { - logger.debug("runAudit: Exiting"); - } - - } - - /** - * Indicates that the {@link #run()} method has started. This method simply returns, - * and may overridden by junit tests. - * - * @throws InterruptedException can be interrupted - */ - public void runStarted() throws InterruptedException { - // does nothing - } - - /** - * Indicates that an audit has completed. This method simply returns, and may - * overridden by junit tests. - * - * @throws InterruptedException can be interrupted - */ - public void auditCompleted() throws InterruptedException { - // does nothing - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java deleted file mode 100644 index 5bfedaac..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import java.util.function.Supplier; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import org.onap.policy.common.utils.time.CurrentTime; - -/** - * "Current" time used by IntegrityMonitor classes. - */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public class AuditorTime { - - /** - * Instance to be used. - */ - private static final CurrentTime currentTime = new CurrentTime(); - - /** - * Supplies the instance to be used for accessing the current time. This may be - * overridden by junit tests to provide a different time instance for each thread when - * multiple threads are run in parallel. - */ - private static Supplier<CurrentTime> supplier = () -> currentTime; - - /** - * Get instance. - * - * @return the CurrentTime singleton - */ - public static CurrentTime getInstance() { - return supplier.get(); - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java deleted file mode 100644 index 22ffa08e..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java +++ /dev/null @@ -1,503 +0,0 @@ -/*-- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import jakarta.persistence.Table; -import java.io.Serializable; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import org.apache.commons.lang3.SerializationUtils; -import org.apache.commons.lang3.builder.RecursiveToStringStyle; -import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - -/** - * class DbAudit does actual auditing of DB tables. - */ -public class DbAudit { - - private static final Logger logger = FlexLogger.getLogger(DbAudit.class); - - private static final String COMMA_RESOURCE_NAME = ", resourceName="; - - private static final long DB_AUDIT_UPDATE_MS = 5000L; - private static final long DB_AUDIT_SLEEP_MS = 2000L; - - DbDao dbDao = null; - - /** - * Construct an instance with the given DbDao. - * - * @param dbDao the DbDao - */ - public DbAudit(DbDao dbDao) { - - logger.debug("Constructor: Entering"); - - this.dbDao = dbDao; - - logger.debug("Constructor: Exiting"); - } - - /** - * dbAudit actually does the audit. - * - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param nodeType the node type - * @throws IntegrityAuditException if an error occurs - */ - public void dbAudit(String resourceName, String persistenceUnit, String nodeType) throws IntegrityAuditException { - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Entering, resourceName=" + resourceName + ", persistenceUnit=" + persistenceUnit - + ", nodeType=" + nodeType); - } - - // Get all IntegrityAudit entries so we can get the DB access info - List<IntegrityAuditEntity> iaeList = dbDao.getIntegrityAuditEntities(persistenceUnit, nodeType); - if (iaeList == null || iaeList.isEmpty()) { - - String msg = "DbAudit: for node " + resourceName + " Found no IntegrityAuditEntity entries"; - logger.error(MessageCodes.ERROR_AUDIT, msg); - throw new DbAuditException(msg); - - } else if (iaeList.size() == 1) { - - Long iaeId = null; - String iaeRn = null; - String iaeNt = null; - String iaeS = null; - for (IntegrityAuditEntity iae : iaeList) { - iaeId = iae.getId(); - iaeRn = iae.getResourceName(); - iaeNt = iae.getNodeType(); - iaeS = iae.getSite(); - } - String msg = "DbAudit: Found only one IntegrityAuditEntity entry:" + " ID = " + iaeId + " ResourceName = " - + iaeRn + " NodeType = " + iaeNt + " Site = " + iaeS; - logger.warn(msg); - return; - } - - // Obtain all persistence class names for the PU we are auditing - Set<String> classNameSet = dbDao.getPersistenceClassNames(); - if (classNameSet == null || classNameSet.isEmpty()) { - - String msg = "DbAudit: For node " + resourceName + " Found no persistence class names"; - logger.error(MessageCodes.ERROR_AUDIT, msg); - throw new DbAuditException(msg); - - } - - /* - * Retrieve myIae. We are going to compare the local class entries against all other DB - * nodes. Since the audit is run in a round-robin, every instance will be compared against - * every other instance. - */ - var myIae = dbDao.getMyIntegrityAuditEntity(); - - if (myIae == null) { - - String msg = "DbAudit: Found no IntegrityAuditEntity entry for resourceName: " + resourceName - + " persistenceUnit: " + persistenceUnit; - logger.error(MessageCodes.ERROR_AUDIT, msg); - throw new DbAuditException(msg); - - } - /* - * This is the map of mismatched entries indexed by className. For each class name there is - * a list of mismatched entries - */ - Map<String, Set<Object>> misMatchedMap = new HashMap<>(); - - compareList(persistenceUnit, iaeList, myIae, classNameSet, misMatchedMap); - - // If misMatchedMap is not empty, retrieve the entries in each misMatched list and compare - // again - recompareList(resourceName, persistenceUnit, iaeList, myIae, misMatchedMap); - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Exiting"); - } - } - - private void compareList(String persistenceUnit, List<IntegrityAuditEntity> iaeList, IntegrityAuditEntity myIae, - Set<String> classNameSet, Map<String, Set<Object>> misMatchedMap) - throws IntegrityAuditException { - - // We need to keep track of how long the audit is taking - long startTime = AuditorTime.getInstance().getMillis(); - - // Retrieve all instances of the class for each node - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Traversing classNameSet, size=" + classNameSet.size()); - } - for (String clazzName : classNameSet) { - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: clazzName=" + clazzName); - } - - // all instances of the class for myIae - Map<Object, Object> myEntries = dbDao.getAllMyEntries(clazzName); - // get a map of the objects indexed by id. Does not necessarily have any entries - - compareMineWithTheirs(persistenceUnit, iaeList, myIae, misMatchedMap, clazzName, myEntries); - - // Time check - startTime = timeCheck("First", startTime); - } - - // check if misMatchedMap is empty - if (misMatchedMap.isEmpty()) { - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Exiting, misMatchedMap is empty"); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Doing another comparison; misMatchedMap.size()=" + misMatchedMap.size()); - } - } - } - - private void compareMineWithTheirs(String persistenceUnit, List<IntegrityAuditEntity> iaeList, - IntegrityAuditEntity myIae, Map<String, Set<Object>> misMatchedMap, String clazzName, - Map<Object, Object> myEntries) { - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Traversing iaeList, size=" + iaeList.size()); - } - for (IntegrityAuditEntity iae : iaeList) { - if (iae.getId() == myIae.getId()) { - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: My Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName()); - } - continue; // no need to compare with self - } - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName()); - } - - // get a map of the instances for their iae indexed by id - Map<Object, Object> theirEntries = - dbDao.getAllEntries(persistenceUnit, getTheirDaoProperties(iae), clazzName); - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: For persistenceUnit=" + persistenceUnit + ", clazzName=" + clazzName - + ", theirEntries.size()=" + theirEntries.size()); - } - - /* - * Compare myEntries with theirEntries and get back a set of mismatched IDs. - * Collect the IDs for the class where a mismatch occurred. We will check them - * again for all nodes later. - */ - compareMineWithTheirs(myEntries, theirEntries, clazzName, misMatchedMap); - } - } - - private void compareMineWithTheirs(Map<Object, Object> myEntries, Map<Object, Object> theirEntries, - String clazzName, Map<String, Set<Object>> misMatchedMap) { - - Set<Object> misMatchedKeySet = compareEntries(myEntries, theirEntries); - if (misMatchedKeySet.isEmpty()) { - return; - } - - Set<Object> misMatchedEntry = misMatchedMap.get(clazzName); - if (misMatchedEntry == null) { - misMatchedMap.put(clazzName, misMatchedKeySet); - } else { - misMatchedEntry.addAll(misMatchedKeySet); - } - } - - private long timeCheck(String type, long startTime) throws IntegrityAuditException { - if ((AuditorTime.getInstance().getMillis() - startTime) >= DB_AUDIT_UPDATE_MS) { - // update the timestamp - dbDao.setLastUpdated(); - // reset the startTime - return AuditorTime.getInstance().getMillis(); - } else { - // sleep a couple seconds to break up the activity - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: " + type + " comparison; sleeping " + DB_AUDIT_SLEEP_MS + "ms"); - } - sleep(); - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: " + type + " comparison; waking from sleep"); - } - return startTime; - } - } - - /** - * Creates properties for the other db node. - * @param iae target DB node - * @return DAO properties for the given DB node - */ - private Properties getTheirDaoProperties(IntegrityAuditEntity iae) { - var theirProperties = new Properties(); - - theirProperties.put(IntegrityAuditProperties.DB_DRIVER, iae.getJdbcDriver()); - theirProperties.put(IntegrityAuditProperties.DB_URL, iae.getJdbcUrl()); - theirProperties.put(IntegrityAuditProperties.DB_USER, iae.getJdbcUser()); - theirProperties.put(IntegrityAuditProperties.DB_PWD, iae.getJdbcPassword()); - theirProperties.put(IntegrityAuditProperties.SITE_NAME, iae.getSite()); - theirProperties.put(IntegrityAuditProperties.NODE_TYPE, iae.getNodeType()); - - return theirProperties; - } - - private void recompareList(String resourceName, String persistenceUnit, List<IntegrityAuditEntity> iaeList, - IntegrityAuditEntity myIae, Map<String, Set<Object>> misMatchedMap) - throws IntegrityAuditException { - - Set<String> classNameSet; - long startTime; - classNameSet = new HashSet<>(misMatchedMap.keySet()); - // We need to keep track of how long the audit is taking - startTime = AuditorTime.getInstance().getMillis(); - - // Retrieve all instances of the class for each node - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; traversing classNameSet, size=" + classNameSet.size()); - } - - var errorCount = 0; - - for (String clazzName : classNameSet) { - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; clazzName=" + clazzName); - } - - // all instances of the class for myIae - Set<Object> keySet = misMatchedMap.get(clazzName); - Map<Object, Object> myEntries = dbDao.getAllMyEntries(clazzName, keySet); - // get a map of the objects indexed by id - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; traversing iaeList, size=" + iaeList.size()); - } - errorCount += recompareMineWithTheirs(resourceName, persistenceUnit, iaeList, myIae, clazzName, - keySet, myEntries); - // Time check - startTime = timeCheck("Second", startTime); - } - - if (errorCount > 0) { - String msg = " DB Audit: " + errorCount - + " errors found. A large number of errors may indicate DB replication has stopped"; - logger.error(MessageCodes.ERROR_AUDIT, msg); - } - } - - private int recompareMineWithTheirs(String resourceName, String persistenceUnit, List<IntegrityAuditEntity> iaeList, - IntegrityAuditEntity myIae, String clazzName, Set<Object> keySet, Map<Object, Object> myEntries) - throws IntegrityAuditException { - - var errorCount = 0; - for (IntegrityAuditEntity iae : iaeList) { - if (iae.getId() == myIae.getId()) { - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; My Id=" + iae.getId() + COMMA_RESOURCE_NAME - + iae.getResourceName()); - } - continue; // no need to compare with self - } - - if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; Id=" + iae.getId() + COMMA_RESOURCE_NAME - + iae.getResourceName()); - } - - // get a map of the instances for their iae indexed by id - Map<Object, Object> theirEntries = - dbDao.getAllEntries(persistenceUnit, getTheirDaoProperties(iae), clazzName, keySet); - - /* - * Compare myEntries with theirEntries and get back a set of mismatched IDs. - * Collect the IDs for the class where a mismatch occurred. We will now write - * an error log for each. - */ - errorCount += recompareMineWithTheirs(resourceName, clazzName, myEntries, iae, theirEntries); - } - return errorCount; - } - - private int recompareMineWithTheirs(String resourceName, String clazzName, Map<Object, Object> myEntries, - IntegrityAuditEntity iae, Map<Object, Object> theirEntries) throws IntegrityAuditException { - Set<Object> misMatchedKeySet = compareEntries(myEntries, theirEntries); - if (misMatchedKeySet.isEmpty()) { - return 0; - } - - var keyBuilder = new StringBuilder(); - for (Object key : misMatchedKeySet) { - keyBuilder.append(key.toString()); - keyBuilder.append(", "); - } - writeAuditSummaryLog(clazzName, resourceName, iae.getResourceName(), keyBuilder.toString()); - if (logger.isDebugEnabled()) { - for (Object key : misMatchedKeySet) { - writeAuditDebugLog(clazzName, resourceName, iae.getResourceName(), myEntries.get(key), - theirEntries.get(key)); - } - } - return misMatchedKeySet.size(); - } - - /** - * Sleeps a bit. - * - * @throws IntegrityAuditException if interrupted - */ - private void sleep() throws IntegrityAuditException { - try { - AuditorTime.getInstance().sleep(DB_AUDIT_SLEEP_MS); - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IntegrityAuditException(e); - } - } - - /** - * compareEntries() will compare the lists of entries from the DB. - * - * @param myEntries the entries - * @param theirEntries the entries to compare against myEntries - * @return the set of differences - */ - public Set<Object> compareEntries(Map<Object, Object> myEntries, Map<Object, Object> theirEntries) { - /* - * Compare the entries for the same key in each of the hashmaps. The comparison will be done - * by serializing the objects (create a byte array) and then do a byte array comparison. The - * audit will walk the local repository hash map comparing to the remote cluster hashmap and - * then turn it around and walk the remote hashmap and look for any entries that are not - * present in the local cluster hashmap. - * - * If the objects are not identical, the audit will put the object IDs on a list to try - * after completing the audit of the table it is currently working on. - * - */ - HashSet<Object> misMatchedKeySet = new HashSet<>(); - for (Entry<Object, Object> ent : myEntries.entrySet()) { - Object key = ent.getKey(); - byte[] mySerializedEntry = SerializationUtils.serialize((Serializable) ent.getValue()); - byte[] theirSerializedEntry = SerializationUtils.serialize((Serializable) theirEntries.get(key)); - if (!Arrays.equals(mySerializedEntry, theirSerializedEntry)) { - logger.debug("compareEntries: For myEntries.key=" + key + ", entries do not match"); - misMatchedKeySet.add(key); - } else { - logger.debug("compareEntries: For myEntries.key=" + key + ", entries match"); - } - } - // now compare it in the other direction to catch entries in their set that is not in my set - for (Entry<Object, Object> ent : theirEntries.entrySet()) { - Object key = ent.getKey(); - byte[] mySerializedEntry = SerializationUtils.serialize((Serializable) myEntries.get(key)); - byte[] theirSerializedEntry = SerializationUtils.serialize((Serializable) ent.getValue()); - if (!Arrays.equals(mySerializedEntry, theirSerializedEntry)) { - logger.debug("compareEntries: For theirEntries.key=" + key + ", entries do not match"); - misMatchedKeySet.add(key); - } else { - logger.debug("compareEntries: For theirEntries.key=" + key + ", entries match"); - } - } - - // return a Set of the object IDs - logger.debug("compareEntries: misMatchedKeySet.size()=" + misMatchedKeySet.size()); - return misMatchedKeySet; - } - - /** - * writeAuditDebugLog() writes the mismatched entry details to the debug log. - * - * @param clazzName the class name - * @param resourceName1 resource name 1 - * @param resourceName2 resource name 2 - * @param entry1 entry 1 - * @param entry2 entry 2 - * @throws IntegrityAuditException if the given class cannot be found - */ - public void writeAuditDebugLog(String clazzName, String resourceName1, String resourceName2, Object entry1, - Object entry2) throws IntegrityAuditException { - try { - Class<?> entityClass = Class.forName(clazzName); - String tableName = entityClass.getAnnotation(Table.class).name(); - String msg = "\nDB Audit Error: " + "\n Table Name: " + tableName - + "\n Entry 1 (short prefix style): " + resourceName1 + ": " - + new ReflectionToStringBuilder(entry1, ToStringStyle.SHORT_PREFIX_STYLE) - + "\n Entry 2 (short prefix style): " + resourceName2 + ": " - + (entry2 != null - ? new ReflectionToStringBuilder(entry2, ToStringStyle.SHORT_PREFIX_STYLE).toString() - : "null") - + "\n Entry 1 (recursive style): " + resourceName1 + ": " - + new ReflectionToStringBuilder(entry1, new RecursiveToStringStyle()) - + "\n Entry 2 (recursive style): " + resourceName2 + ": " - + (entry2 != null - ? new ReflectionToStringBuilder(entry2, new RecursiveToStringStyle()).toString() - : "null"); - logger.debug(msg); - - } catch (ClassNotFoundException e) { - throw new IntegrityAuditException(e); - } - - } - - /** - * writeAuditSummaryLog() writes a summary of the DB mismatches to the error log. - * - * @param clazzName the name of the class - * @param resourceName1 resource name 1 - * @param resourceName2 resource name 2 - * @param keys the mismatched entry keys - * @throws IntegrityAuditException if the given class cannot be found - */ - public void writeAuditSummaryLog(String clazzName, String resourceName1, String resourceName2, String keys) - throws IntegrityAuditException { - try { - Class<?> entityClass = Class.forName(clazzName); - String tableName = entityClass.getAnnotation(Table.class).name(); - String msg = " DB Audit Error: Table Name: " + tableName + "; Mismatch between nodes: " + resourceName1 - + " and " + resourceName2 + "; Mismatched entries (keys): " + keys; - logger.info(msg); - } catch (ClassNotFoundException e) { - throw new IntegrityAuditException(e); - } - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java deleted file mode 100644 index a539f6bd..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -public class DbAuditException extends IntegrityAuditException { - private static final long serialVersionUID = 1L; - - public DbAuditException() { - super(); - } - - public DbAuditException(String message) { - super(message); - } - - public DbAuditException(Throwable cause) { - super(cause); - } - - public DbAuditException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java deleted file mode 100644 index ad96432d..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java +++ /dev/null @@ -1,722 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.EntityTransaction; -import jakarta.persistence.Persistence; -import jakarta.persistence.Query; -import jakarta.persistence.TypedQuery; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; -import jakarta.persistence.metamodel.ManagedType; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.function.BiConsumer; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - -/** - * class DbDao provides the inteface to the DBs for the purpose of audits. - */ -public class DbDao { - private static final Logger logger = FlexLogger.getLogger(); - - private String resourceName; - private String persistenceUnit; - private String dbDriver; - private String dbUrl; - private String dbUser; - private String siteName; - private String nodeType; - private Properties properties = null; - - private final EntityManagerFactory emf; - - /* - * Supports designation serialization. - */ - private static final Object lock = new Object(); - - /* - * Common strings. - */ - private static final String RESOURCE_MESSAGE = "Resource: "; - private static final String WITH_PERSISTENCE_MESSAGE = " with PersistenceUnit: "; - private static final String DBDAO_MESSAGE = "DbDao: "; - private static final String ENCOUNTERED_MESSAGE = "ecountered a problem in execution: "; - - /* - * DB SELECT String. - */ - private static final String SELECT_STRING = "Select i from IntegrityAuditEntity i " - + "where i.resourceName=:rn and i.persistenceUnit=:pu"; - - /** - * DbDao Constructor. - * - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param properties the properties - * @throws IntegrityAuditException if an error occurs - */ - public DbDao(String resourceName, String persistenceUnit, Properties properties) throws IntegrityAuditException { - this(resourceName, persistenceUnit, properties, null); - } - - /** - * DbDao Constructor. - * - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param properties the properties - * @param altDbUrl may be {@code null} - * @throws IntegrityAuditException if an error occurs - */ - protected DbDao(String resourceName, String persistenceUnit, Properties properties, String altDbUrl) - throws IntegrityAuditException { - logger.debug("DbDao contructor: enter"); - - validateProperties(resourceName, persistenceUnit, properties); - - emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - register(altDbUrl); - - logger.debug("DbDao contructor: exit"); - } - - /** - * Release resources (i.e., the EntityManagerFactory). - */ - public void destroy() { - emf.close(); - } - - /** - * validateProperties will validate the properties. - * - * @param resourceName the rseource name - * @param persistenceUnit the persistence unit - * @param properties the properties - * @throws IntegrityAuditPropertiesException if an error occurs - */ - private void validateProperties(String resourceName, String persistenceUnit, Properties properties) - throws IntegrityAuditPropertiesException { - var badparams = new StringBuilder(); - if (IntegrityAudit.parmsAreBad(resourceName, persistenceUnit, properties, badparams)) { - String msg = "DbDao: Bad parameters: badparams" + badparams; - throw new IntegrityAuditPropertiesException(msg); - } - this.resourceName = resourceName; - this.persistenceUnit = persistenceUnit; - this.dbDriver = properties.getProperty(IntegrityAuditProperties.DB_DRIVER).trim(); - this.dbUrl = properties.getProperty(IntegrityAuditProperties.DB_URL).trim(); - this.dbUser = properties.getProperty(IntegrityAuditProperties.DB_USER).trim(); - this.siteName = properties.getProperty(IntegrityAuditProperties.SITE_NAME).trim(); - this.nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE).trim().toLowerCase(); - this.properties = properties; - logger.debug("DbDao.assignProperties: exit:" + "\nresourceName: " + this.resourceName + "\npersistenceUnit: " - + this.persistenceUnit + "\nproperties: " + this.properties); - } - - /** - * getAllMyEntries gets all the DB entries for a particular class. - * - * @param className the class name - * @return all the DB entries for the given class - */ - public Map<Object, Object> getAllMyEntries(String className) { - logger.debug("getAllMyEntries: Entering, className=" + className); - HashMap<Object, Object> resultMap = new HashMap<>(); - var em = emf.createEntityManager(); - try { - getObjectsFromCriteriaBuilder(className, emf, em, resultMap); - } catch (Exception e) { - logger.error("getAllEntries encountered exception: ", e); - } - em.close(); - logger.debug("getAllMyEntries: Exit, resultMap.keySet()=" + resultMap.keySet()); - return resultMap; - } - - /** - * getAllMyEntries gets all entries for a class. - * - * @param className the name of the class - * @param keySet the keys to get the entries for - * @return the map of requested entries - */ - public Map<Object, Object> getAllMyEntries(String className, Set<Object> keySet) { - logger.debug("getAllMyEntries: Entering, className=" + className + ",\n keySet=" + keySet); - - HashMap<Object, Object> resultMap = new HashMap<>(); - var em = emf.createEntityManager(); - try { - Class<?> clazz = Class.forName(className); - for (Object key : keySet) { - Object entry = em.find(clazz, key); - resultMap.put(key, entry); - } - } catch (Exception e) { - logger.error("getAllMyEntries encountered exception: ", e); - } - em.close(); - - logger.debug("getAllMyEntries: Returning resultMap, size=" + resultMap.size()); - return resultMap; - } - - /** - * getAllEntries gets all entries for a particular persistence unit adn className. - * - * @param persistenceUnit the persistence unit - * @param properties the properties - * @param className the class name - * @return the map of entries - */ - public Map<Object, Object> getAllEntries(String persistenceUnit, Properties properties, String className) { - - logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n className=" + className); - HashMap<Object, Object> resultMap = new HashMap<>(); - - var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - var em = theEmf.createEntityManager(); - - try { - getObjectsFromCriteriaBuilder(className, theEmf, em, resultMap); - } catch (Exception e) { - logger.error("getAllEntries encountered exception:", e); - } - em.close(); - theEmf.close(); - - logger.debug("getAllEntries: Returning resultMap, size=" + resultMap.size()); - - return resultMap; - } - - - /** - * getAllEntries gets all entries for a persistence unit. - * - * @param persistenceUnit the persistence unit - * @param properties the properties - * @param className the class name - * @param keySet the keys - * @return the map of entries - */ - - public Map<Object, Object> getAllEntries(String persistenceUnit, Properties properties, String className, - Set<Object> keySet) { - logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n properties= " + properties - + ",\n className=" + className + ",\n keySet= " + keySet); - var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - var em = theEmf.createEntityManager(); - HashMap<Object, Object> resultMap = new HashMap<>(); - try { - Class<?> clazz = Class.forName(className); - for (Object key : keySet) { - Object entry = em.find(clazz, key); - resultMap.put(key, entry); - } - } catch (Exception e) { - String msg = "getAllEntries encountered exception: " + e; - logger.error(msg, e); - } - em.close(); - theEmf.close(); - logger.debug("getAllEntries: Exit, resultMap, size=" + resultMap.size()); - return resultMap; - } - - /** - * getIntegrityAuditEntities() Get all the IntegrityAuditEntities for a particular persistence - * unit and node type. - * - * @param persistenceUnit the persistence unit - * @param nodeType the node type - * @return the list of IntegrityAuditEntity - * @throws DbDaoTransactionException if an error occurs - */ - @SuppressWarnings("unchecked") - public List<IntegrityAuditEntity> getIntegrityAuditEntities(String persistenceUnit, String nodeType) - throws DbDaoTransactionException { - logger.debug("getIntegrityAuditEntities: Entering, persistenceUnit=" + persistenceUnit + ",\n nodeType= " - + nodeType); - try { - List<IntegrityAuditEntity> iaeList; - try (var em = emf.createEntityManager()) { - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not - // found, create a new entry - var iaequery = em - .createQuery("Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt"); - iaequery.setParameter("pu", persistenceUnit); - iaequery.setParameter("nt", nodeType); - - iaeList = iaequery.getResultList(); - - // commit transaction - et.commit(); - } - logger.debug("getIntegrityAuditEntities: Exit, iaeList=" + iaeList); - return iaeList; - } catch (Exception e) { - String msg = DBDAO_MESSAGE + "getIntegrityAuditEntities() " + ENCOUNTERED_MESSAGE; - logger.error(msg, e); - throw new DbDaoTransactionException(e); - } - - } - - /** - * getMyIntegrityAuditEntity() gets my IntegrityAuditEntity. - * - * @return the IntegrityAuditEntity - * @throws DbDaoTransactionException if an error occurs - */ - public IntegrityAuditEntity getMyIntegrityAuditEntity() throws DbDaoTransactionException { - - return updateIae("getMyIntegrityAuditEntity", this.resourceName, this.persistenceUnit, (em, iae) -> { - - if (iae != null) { - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " exists"); - } else { - // If it does not exist, log an error - logger.error("Attempting to setLastUpdated" + " on an entry that does not exist: resource " - + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit); - } - }); - } - - - /** - * getIntegrityAuditEntity() gets the IntegrityAuditEntity with a particular ID. - * - * @param id the ID - * @return the IntegrityAuditEntity - * @throws DbDaoTransactionException if an error occurs - */ - public IntegrityAuditEntity getIntegrityAuditEntity(long id) throws DbDaoTransactionException { - try { - IntegrityAuditEntity iae; - try (var em = emf.createEntityManager()) { - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - iae = em.find(IntegrityAuditEntity.class, id); - - et.commit(); - } - - return iae; - } catch (Exception e) { - String msg = DBDAO_MESSAGE + "getIntegrityAuditEntity() " + ENCOUNTERED_MESSAGE; - logger.error(msg + e); - throw new DbDaoTransactionException(e); - } - } - - /** - * getPersistenceClassNames() gets all the persistence class names. - * - * @return the persistence class names - */ - public Set<String> getPersistenceClassNames() { - logger.debug("DbDao: getPersistenceClassNames() entry"); - HashSet<String> returnList = new HashSet<>(); - final var mm = emf.getMetamodel(); - logger.debug("\n" + persistenceUnit + " persistence unit classes:"); - for (final ManagedType<?> managedType : mm.getManagedTypes()) { - Class<?> clazz = managedType.getJavaType(); - logger.debug(" " + clazz.getSimpleName()); - returnList.add(clazz.getName()); // the full class name needed to make a query using jpa - } - logger.debug("DbDao: getPersistenceClassNames() exit"); - return returnList; - } - - /** - * Register the IntegrityAudit instance. - * - * @param altDbUrl alternate DB URL to be placed into the record, or {@code null} to use the - * default - */ - private void register(String altDbUrl) throws DbDaoTransactionException { - - updateIae("register", this.resourceName, this.persistenceUnit, (em, iae) -> { - IntegrityAuditEntity iae2 = iae; - - // If it already exists, we just want to update the properties and lastUpdated date - if (iae2 != null) { - // refresh the object from DB in case cached data was returned - em.refresh(iae2); - logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " exists and entry be updated"); - } else { - // If it does not exist, we also must add teh resourceName, persistenceUnit and - // designated values - logger.info("Adding resource " + resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " to IntegrityAuditEntity table"); - iae2 = new IntegrityAuditEntity(); - iae2.setResourceName(this.resourceName); - iae2.setPersistenceUnit(this.persistenceUnit); - iae2.setDesignated(false); - } - - register2(altDbUrl, em, iae2); - }); - - } - - private void register2(String altDbUrl, EntityManager em, IntegrityAuditEntity iae) { - // update/set properties in entry - iae.setSite(this.siteName); - iae.setNodeType(this.nodeType); - iae.setJdbcDriver(this.dbDriver); - iae.setJdbcPassword(properties.getProperty(IntegrityAuditProperties.DB_PWD).trim()); - iae.setJdbcUrl(altDbUrl == null ? this.dbUrl : altDbUrl); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - } - - public void setDesignated(boolean designated) throws DbDaoTransactionException { - setDesignated(this.resourceName, this.persistenceUnit, designated); - } - - /** - * Set designated. - * - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param desig true if is designated - * @throws DbDaoTransactionException if an error occurs - */ - public void setDesignated(String resourceName, String persistenceUnit, boolean desig) - throws DbDaoTransactionException { - logger.debug("setDesignated: enter, resourceName: " + resourceName + ", persistenceUnit: " + persistenceUnit - + ", designated: " + desig); - - updateIae("setDesignated", resourceName, persistenceUnit, (em, iae) -> { - - if (iae != null) { - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info(RESOURCE_MESSAGE + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit - + " exists and designated be updated"); - iae.setDesignated(desig); - - em.persist(iae); - // flush to the DB - em.flush(); - } else { - // If it does not exist, log an error - logger.error("Attempting to setDesignated(" + desig + ") on an entry that does not exist:" - + " resource " + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit); - } - }); - - } - - /** - * Queries for an audit entity and then updates it using an "updater" function. - * - * @param methodName name of the method that invoked this - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param updater function to update the entity; the argument will be the entity to be - * updated, or {@code null} if the entity is not found - * @return the entity that was found, or {@code null} if the entity is not found - * @throws DbDaoTransactionException if an error occurs - */ - private IntegrityAuditEntity updateIae(String methodName, String resourceName, String persistenceUnit, - BiConsumer<EntityManager, IntegrityAuditEntity> updater) - throws DbDaoTransactionException { - try { - - IntegrityAuditEntity iae; - try (var em = emf.createEntityManager()) { - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not - // found, create a new entry - TypedQuery<IntegrityAuditEntity> iaequery = em.createQuery(SELECT_STRING, IntegrityAuditEntity.class); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", persistenceUnit); - - List<IntegrityAuditEntity> iaeList = iaequery.getResultList(); - - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = iaeList.get(0); - - } else { - // If it does not exist - iae = null; - } - - updater.accept(em, iae); - - // close the transaction - et.commit(); - } - - return iae; - - } catch (Exception e) { - String msg = DBDAO_MESSAGE + methodName + "() " + ENCOUNTERED_MESSAGE; - logger.error(msg + e); - throw new DbDaoTransactionException(e); - } - - } - - /** - * Set last updated. - * - * @throws DbDaoTransactionException if an error occurs - */ - public void setLastUpdated() throws DbDaoTransactionException { - logger.debug("setLastUpdated: enter, resourceName: " + this.resourceName + ", persistenceUnit: " - + this.persistenceUnit); - - updateIae("setLastUpdated", this.resourceName, this.persistenceUnit, (em, iae) -> { - - if (iae != null) { - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit - + " exists and lastUpdated be updated"); - iae.setLastUpdated(AuditorTime.getInstance().getDate()); - - em.persist(iae); - // flush to the DB - em.flush(); - } else { - // If it does not exist, log an error - logger.error("Attempting to setLastUpdated" + " on an entry that does not exist:" + " resource " - + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit); - } - }); - } - - /** - * Normally this method should only be used in a JUnit test environment. Manually deletes all - * PDP records in droolspdpentity table. - */ - public int deleteAllIntegrityAuditEntities() throws DbDaoTransactionException { - - try { - - if (!IntegrityAudit.isUnitTesting()) { - String msg = DBDAO_MESSAGE + "deleteAllIntegrityAuditEntities() " - + "should only be invoked during JUnit testing"; - logger.error(msg); - throw new DbDaoTransactionException(msg); - } - - int returnCode; - try (var em = emf.createEntityManager()) { - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not - // found, create a new entry - var iaequery = em.createQuery("Delete from IntegrityAuditEntity"); - - returnCode = iaequery.executeUpdate(); - - // commit transaction - et.commit(); - } - - logger.info("deleteAllIntegrityAuditEntities: returnCode=" + returnCode); - - return returnCode; - - } catch (Exception e) { - String msg = DBDAO_MESSAGE + "deleteAllIntegrityAuditEntities() " + "encountered a problem in execution: "; - logger.error(msg + e); - throw new DbDaoTransactionException(e); - } - - } - - /** - * Changes designation to specified resourceName - * - * <p>static lock object in conjunction with synchronized keyword ensures that designation - * changes are done serially within a resource. I.e. static lock ensures that multiple - * instantiations of DbDao don't interleave changeDesignated() invocations and potentially - * produce simultaneous designations. - * - * <p>Optimistic locking (the default, versus pessimistic) is sufficient to avoid simultaneous - * designations from interleaved changeDesignated() invocations from different resources - * (entities), because it prevents "dirty" and "non-repeatable" reads. - * - * <p>See www.objectdb.com/api/java/jpa/LockModeType - * - * <p>and - * - * <p>stackoverflow.com/questions/2120248/how-to-synchronize-a-static- - * variable-among-threads-running-different-instances-o - */ - public void changeDesignated(String resourceName, String persistenceUnit, String nodeType) - throws DbDaoTransactionException { - - if (logger.isDebugEnabled()) { - logger.debug("changeDesignated: Entering, resourceName=" + resourceName + ", persistenceUnit=" - + persistenceUnit + ", nodeType=" + nodeType); - } - - long startTime = AuditorTime.getInstance().getMillis(); - - synchronized (lock) { - try (var em = emf.createEntityManager()) { - try { - em.getTransaction().begin(); - - /* - * Define query - */ - var query = em.createQuery( - "Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt"); - query.setParameter("pu", persistenceUnit); - query.setParameter("nt", nodeType); - - /* - * Execute query using pessimistic write lock. This ensures that if anyone else is - * currently reading the records we'll throw a LockTimeoutException. - */ - setDesignatedEntity(resourceName, query); - - if (logger.isDebugEnabled()) { - logger.debug("changeDesignated: Committing designation to resourceName=" + resourceName); - } - em.getTransaction().commit(); - - /* - * If we get a LockTimeoutException, no harm done really. We'll probably be - * successful on the next attempt. The odds of another DbDao instance on this entity - * or another entity attempting a simultaneous IntegrityAuditEntity table - * read/update are pretty slim (we're only in this method for two or three - * milliseconds) - */ - } catch (Exception e) { - String errorMsg; - try { - em.getTransaction().rollback(); - errorMsg = "DbDao: changeDesignated() caught Exception, message=" + e.getMessage(); - } catch (Exception rollbackException) { - errorMsg = "DbDao: changeDesignated() caught Exception, message=" - + e.getMessage() + ". Error rolling back transaction."; - } - logger.error(errorMsg + e); - throw new DbDaoTransactionException(errorMsg, e); - } - } - - } // end synchronized block - - if (logger.isDebugEnabled()) { - logger.debug("changeDesignated: Exiting; time expended=" - + (AuditorTime.getInstance().getMillis() - startTime) + "ms"); - } - - } - - private void setDesignatedEntity(String resourceName, Query query) { - for (Object o : query.getResultList()) { - if (!(o instanceof IntegrityAuditEntity integrityAuditEntity)) { - continue; - } - - if (integrityAuditEntity.getResourceName().equals(resourceName)) { - if (logger.isDebugEnabled()) { - logger.debug("changeDesignated: Designating resourceName=" - + integrityAuditEntity.getResourceName()); - } - integrityAuditEntity.setDesignated(true); - } else { - if (logger.isDebugEnabled()) { - logger.debug("changeDesignated: Removing designation from resourceName=" - + integrityAuditEntity.getResourceName()); - } - integrityAuditEntity.setDesignated(false); - } - } - } - - /** - * Collects all objects from a criteria builder based on className. - * - * @param className type of objects for resultMap - * @param emf the entity manager factory to be used - * @param em entity manager to be used - * @param resultMap the result map for objects queried - * @throws ClassNotFoundException if class for criteria builder doesn't exist - */ - private void getObjectsFromCriteriaBuilder(String className, EntityManagerFactory emf, EntityManager em, - HashMap<Object, Object> resultMap) - throws ClassNotFoundException { - var cb = em.getCriteriaBuilder(); - CriteriaQuery<Object> cq = cb.createQuery(); - Root<?> rootEntry = cq.from(Class.forName(className)); - CriteriaQuery<Object> all = cq.select(rootEntry); - TypedQuery<Object> allQuery = em.createQuery(all); - List<Object> objectList = allQuery.getResultList(); - // Now create the map - - var util = emf.getPersistenceUnitUtil(); - for (Object o : objectList) { - Object key = util.getIdentifier(o); - resultMap.put(key, o); - } - } - -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java deleted file mode 100644 index dc1c6f14..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -public class DbDaoTransactionException extends IntegrityAuditException { - private static final long serialVersionUID = 1L; - - public DbDaoTransactionException() { - super(); - } - - public DbDaoTransactionException(String message) { - super(message); - } - - public DbDaoTransactionException(Throwable cause) { - super(cause); - } - - public DbDaoTransactionException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java deleted file mode 100644 index 66ab307c..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java +++ /dev/null @@ -1,287 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import java.util.Properties; -import lombok.Getter; -import lombok.Setter; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.ia.IntegrityAuditProperties.NodeTypeEnum; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - -/** - * class IntegrityAudit Audits all persisted entities for all resource clusters for all sites and - * logs any anomalies. - */ -public class IntegrityAudit { - - private static final Logger logger = FlexLogger.getLogger(IntegrityAudit.class); - - @Getter - @Setter - private static boolean unitTesting; - - @Getter - private boolean threadInitialized = false; - - AuditThread auditThread = null; - - private String persistenceUnit; - private Properties properties; - private String resourceName; - - - /* - * This is the audit period in milliseconds. For example, if it had a value of 3600000, the - * audit can only run once per hour. If it has a value of 6000, it can run once per minute. - * - * Values: integrityAuditPeriodSeconds < 0 (negative number) indicates the audit is off - * integrityAuditPeriodSeconds == 0 indicates the audit is to run continuously - * integrityAuditPeriodSeconds > 0 indicates the audit is to run at most once during the - * indicated period - * - */ - @Getter - private int integrityAuditPeriodSeconds; - - /** - * IntegrityAudit constructor. - * - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param properties the properties - * @throws IntegrityAuditException if an error occurs - */ - public IntegrityAudit(String resourceName, String persistenceUnit, Properties properties) - throws IntegrityAuditException { - - logger.info("Constructor: Entering and checking for nulls"); - var parmList = new StringBuilder(); - if (parmsAreBad(resourceName, persistenceUnit, properties, parmList)) { - logger.error("Constructor: Parms contain nulls; cannot run audit for resourceName=" + resourceName - + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList); - throw new IntegrityAuditException("Constructor: Parms contain nulls; cannot run audit for resourceName=" - + resourceName + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList); - } - - this.persistenceUnit = persistenceUnit; - this.properties = properties; - this.resourceName = resourceName; - - // IntegrityAuditProperties.AUDIT_PERIOD_SECONDS and - // IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS are allowed to be null - if (properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS) != null) { - this.integrityAuditPeriodSeconds = - Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim()); - } else { - // If it is null, set it to the default value - this.integrityAuditPeriodSeconds = IntegrityAuditProperties.DEFAULT_AUDIT_PERIOD_SECONDS; - } - logger.info("Constructor: Exiting"); - - } - - /** - * Determine if the nodeType conforms to the required node types. - */ - public static boolean isNodeTypeEnum(String nt) { - for (NodeTypeEnum n : NodeTypeEnum.values()) { - if (n.toString().equalsIgnoreCase(nt)) { - return true; - } - } - return false; - } - - - /** - * Makes sure we don't try to run the audit with bad parameters. - */ - public static boolean parmsAreBad(String resourceName, String persistenceUnit, Properties properties, - StringBuilder badparams) { - - boolean parmsAreBad = checkEmpty(badparams, "resourceName", resourceName); - parmsAreBad = checkEmpty(badparams, "persistenceUnit", persistenceUnit) || parmsAreBad; - - if (properties == null || properties.isEmpty()) { - badparams.append("properties "); - parmsAreBad = true; - } else { - parmsAreBad = checkProperties(properties, badparams) || parmsAreBad; - } // End else - logger.debug("parmsAreBad: exit:" + "\nresourceName: " + resourceName + "\npersistenceUnit: " + persistenceUnit - + "\nproperties: " + properties); - - return parmsAreBad; - } - - private static boolean checkEmpty(StringBuilder builder, String name, String value) { - if (StringUtils.isEmpty(value)) { - builder.append(name); - builder.append(' '); - return true; - - } else { - return false; - } - } - - private static boolean checkProperties(Properties properties, StringBuilder badparams) { - boolean parmsAreBad = - checkEmpty(badparams, "dbDriver", properties.getProperty(IntegrityAuditProperties.DB_DRIVER)); - parmsAreBad = checkEmpty(badparams, "dbUrl", properties.getProperty(IntegrityAuditProperties.DB_URL)) - || parmsAreBad; - parmsAreBad = checkEmpty(badparams, "dbUser", properties.getProperty(IntegrityAuditProperties.DB_USER)) - || parmsAreBad; - - // dbPwd may be empty - checkEmpty(badparams, "dbPwd", properties.getProperty(IntegrityAuditProperties.DB_PWD)); - - parmsAreBad = checkEmpty(badparams, "siteName", properties.getProperty(IntegrityAuditProperties.SITE_NAME)) - || parmsAreBad; - parmsAreBad = checkNodeType(properties, badparams) || parmsAreBad; - - return checkAuditPeriod(properties, badparams) || parmsAreBad; - } - - private static boolean checkNodeType(Properties properties, StringBuilder badparams) { - String nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE); - if (nodeType == null || nodeType.isEmpty()) { - badparams.append("nodeType "); - return true; - } else { - nodeType = nodeType.trim(); - if (!isNodeTypeEnum(nodeType)) { - badparams.append("nodeType must be one of["); - for (NodeTypeEnum n : NodeTypeEnum.values()) { - badparams.append(n.toString()); - badparams.append(' '); - } - badparams.append("] "); - return true; - } - } - return false; - } - - private static boolean checkAuditPeriod(Properties properties, StringBuilder badparams) { - // IntegrityAuditProperties.AUDIT_PERIOD_SECONDS and - // IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS are allowed to be null - if (properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS) != null) { - try { - Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim()); - } catch (NumberFormatException nfe) { - badparams.append(", auditPeriodSeconds=" - + properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim()); - return true; - } - } - return false; - } - - /** - * Starts the audit thread. - * - * @throws IntegrityAuditException if an error occurs - */ - public void startAuditThread() throws IntegrityAuditException { - logger.info("startAuditThread: Entering"); - - if (integrityAuditPeriodSeconds >= 0) { - this.auditThread = makeAuditThread(this.resourceName, this.persistenceUnit, - this.properties, integrityAuditPeriodSeconds); - logger.info("startAuditThread: Audit started and will run every " + integrityAuditPeriodSeconds - + " seconds"); - this.auditThread.start(); - - } else { - logger.info("startAuditThread: Suppressing integrity audit, integrityAuditPeriodSeconds=" - + integrityAuditPeriodSeconds); - } - - logger.info("startAuditThread: Exiting"); - } - - /** - * Stops the audit thread. - */ - public void stopAuditThread() { - - logger.info("stopAuditThread: Entering"); - - if (this.auditThread != null) { - this.auditThread.interrupt(); - } else { - logger.info("stopAuditThread: auditThread never instantiated; no need to interrupt"); - } - - logger.info("stopAuditThread: Exiting"); - } - - public void setThreadInitialized(boolean isThreadInitialized) { - logger.info("setThreadInitialized: Setting isThreadInitialized=" + isThreadInitialized); - this.threadInitialized = isThreadInitialized; - } - - /** - * Waits a bit for the AuditThread to complete. Used by JUnit tests. - * - * @param twaitms wait time, in milliseconds - * @return {@code true} if the thread stopped within the given time, {@code false} otherwise - * @throws InterruptedException if the thread is interrupted - */ - protected boolean joinAuditThread(long twaitms) throws InterruptedException { - if (this.auditThread == null) { - return true; - - } else { - this.auditThread.join(twaitms); - return !this.auditThread.isAlive(); - } - } - - /** - * Return if audit thread. - * - * @return {@code true} if an audit thread exists, {@code false} otherwise - */ - protected boolean haveAuditThread() { - return (this.auditThread != null); - } - - /** - * Creates an audit thread. May be overridden by junit tests. - * - * @param resourceName2 the resource name - * @param persistenceUnit2 the persistence unit - * @param properties2 properties - * @param integrityAuditPeriodSeconds2 - * - * @return a new audit thread - * @throws IntegrityAuditException audit exception - */ - protected AuditThread makeAuditThread(String resourceName2, String persistenceUnit2, Properties properties2, - int integrityAuditPeriodSeconds2) throws IntegrityAuditException { - - return new AuditThread(resourceName2, persistenceUnit2, properties2, integrityAuditPeriodSeconds2, this); - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditException.java deleted file mode 100644 index 81e8b90c..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditException.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -public class IntegrityAuditException extends Exception { - private static final long serialVersionUID = 1L; - - public IntegrityAuditException() { - super(); - } - - public IntegrityAuditException(String message) { - super(message); - } - - public IntegrityAuditException(Throwable cause) { - super(cause); - } - - public IntegrityAuditException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java deleted file mode 100644 index cd80f56f..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import lombok.AccessLevel; -import lombok.NoArgsConstructor; - -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public class IntegrityAuditProperties { - - public static final int DEFAULT_AUDIT_PERIOD_SECONDS = -1; // Audit does not run - - public static final String DB_DRIVER = "jakarta.persistence.jdbc.driver"; - public static final String DB_URL = "jakarta.persistence.jdbc.url"; - public static final String DB_USER = "jakarta.persistence.jdbc.user"; - public static final String DB_PWD = "jakarta.persistence.jdbc.password"; //NOSONAR - public static final String AUDIT_PERIOD_SECONDS = "integrity_audit_period_seconds"; - - - public static final String SITE_NAME = "site_name"; - public static final String NODE_TYPE = "node_type"; - - public enum NodeTypeEnum { - PDP_XACML, PDP_DROOLS, PAP, PAP_ADMIN, LOGPARSER, BRMS_GATEWAY, ASTRA_GATEWAY, ELK_SERVER, PYPDP - - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java deleted file mode 100644 index d3c92fa5..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -public class IntegrityAuditPropertiesException extends IntegrityAuditException { - private static final long serialVersionUID = 1L; - - public IntegrityAuditPropertiesException() { - super(); - } - - public IntegrityAuditPropertiesException(String message) { - super(message); - } - - public IntegrityAuditPropertiesException(Throwable cause) { - super(cause); - } - - public IntegrityAuditPropertiesException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java deleted file mode 100644 index 64ec7fd0..00000000 --- a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia.jpa; - -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.NamedQuery; -import jakarta.persistence.PrePersist; -import jakarta.persistence.PreUpdate; -import jakarta.persistence.Table; -import jakarta.persistence.Temporal; -import jakarta.persistence.TemporalType; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.Serial; -import java.io.Serializable; -import java.util.Date; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.onap.policy.common.ia.AuditorTime; - -@Entity -@Table(name = "IntegrityAuditEntity") -@NamedQuery(name = " IntegrityAuditEntity.findAll", query = "SELECT e FROM IntegrityAuditEntity e ") -@NamedQuery(name = "IntegrityAuditEntity.deleteAll", query = "DELETE FROM IntegrityAuditEntity WHERE 1=1") -@NoArgsConstructor -@Getter -@Setter -public class IntegrityAuditEntity implements Serializable { - - @Serial - private static final long serialVersionUID = 1L; - - @Getter - @Setter - private static boolean unitTesting; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - @Setter(AccessLevel.PRIVATE) - private long id; - - @Column(name = "persistenceUnit", nullable = false) - private String persistenceUnit; - - @Column(name = "site", nullable = true) - private String site; - - @Column(name = "nodeType", nullable = true) - private String nodeType; - - @Column(name = "resourceName", nullable = false, unique = true) - private String resourceName; - - @Column(name = "designated", nullable = true) - private boolean designated = false; - - @Column(name = "jdbcDriver", nullable = false) - private String jdbcDriver; - - @Column(name = "jdbcUrl", nullable = false) - private String jdbcUrl; - - @Column(name = "jdbcUser", nullable = false) - private String jdbcUser; - - @Column(name = "jdbcPassword", nullable = false) - private String jdbcPassword; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "createdDate", updatable = true) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "lastUpdated") - private Date lastUpdated; - - /** - * Pre persist. - */ - @PrePersist - public void prePersist() { - var date = AuditorTime.getInstance().getDate(); - this.createdDate = date; - this.lastUpdated = date; - } - - @PreUpdate - public void preUpdate() { - this.lastUpdated = AuditorTime.getInstance().getDate(); - } - - private void writeObject(ObjectOutputStream out) throws IOException { - if (isUnitTesting()) { - /* - * Note: other fields may be added here, as long as the created-date and last-updated - * date are not included. - */ - out.writeObject(jdbcUrl); - - } else { - out.defaultWriteObject(); - } - } -} diff --git a/integrity-audit/src/main/resources/META-INF/persistence.xml b/integrity-audit/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 1d72eeba..00000000 --- a/integrity-audit/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,47 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - ============LICENSE_START======================================================= - Integrity Audit - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - Modifications Copyright (C) 2023-2024 Nordix Foundation. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - --> - -<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd"> - <persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL"> - <!-- Limited use for generating the DB and schema files for iatest DB - uses hibernate --> - <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> - <class>org.onap.policy.common.ia.jpa.IntegrityAuditEntity</class> - <class>org.onap.policy.common.ia.jpa.IaTestEntity</class> - <shared-cache-mode>NONE</shared-cache-mode> - <properties> - <property name="jakarta.persistence.schema-generation.database.action" value="create"/> - <property name="hibernate.show_sql" value="false"/> - </properties> - </persistence-unit> - - <persistence-unit name="integrityAuditPU" transaction-type="RESOURCE_LOCAL"> - <!-- For operational use --> - <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> - <class>org.onap.policy.common.ia.jpa.IntegrityAuditEntity</class> - <shared-cache-mode>NONE</shared-cache-mode> - <properties> - <property name="hibernate.show_sql" value="false"/> - </properties> - </persistence-unit> -</persistence> diff --git a/integrity-audit/src/main/resources/log4j.properties b/integrity-audit/src/main/resources/log4j.properties deleted file mode 100644 index 65b9e55e..00000000 --- a/integrity-audit/src/main/resources/log4j.properties +++ /dev/null @@ -1,48 +0,0 @@ -### -# ============LICENSE_START======================================================= -# Integrity Audit -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= -### - -# -# Use this properties for debugging and development. -# -# -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=INFO, FILE - -# A1 is set to be a DailyRollingFileAppender. -log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender - -# Set the name of the file -log4j.appender.FILE.File=IntegrityMonitor.log - -# Set the immediate flush to true (default) -log4j.appender.FILE.ImmediateFlush=true - -# Set the threshold to debug mode -log4j.appender.FILE.Threshold=debug - -# Set the append to false, should not overwrite -log4j.appender.FILE.Append=true - -# Set the DatePattern -log4j.appender.FILE.DatePattern='.'yyyy-MM-dd - -# A1 uses PatternLayout. -log4j.appender.FILE.layout=org.apache.log4j.PatternLayout -log4j.appender.FILE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java deleted file mode 100644 index 1d47f7d0..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java +++ /dev/null @@ -1,254 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2024 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.common.utils.test.log.logback.ExtractAppender; - -/* - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - */ -class AuditPeriodTest extends IntegrityAuditTestBase { - - private static Logger logger = FlexLogger.getLogger(AuditPeriodTest.class); - - @BeforeAll - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + AuditPeriodTest.class.getSimpleName()); - } - - @AfterAll - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } - - /** - * Set up for test case. - */ - @Override - @BeforeEach - public void setUp() { - logger.info("setUp: Entering"); - - super.setUp(); - - logger.info("setUp: Exiting"); - - } - - /** - * Tear down after test cases. - */ - @Override - @AfterEach - public void tearDown() { - logger.info("tearDown: Entering"); - - super.tearDown(); - - logger.info("tearDown: Exiting"); - } - - /* - * Verifies (via log parsing) that when a negative audit period is specified, the audit is - * suppressed. - */ - @Test - void testNegativeAuditPeriod() throws Exception { - - logger.info("testNegativeAuditPeriod: Entering"); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "-1"); - - ExtractAppender logA = watch(debugLogger, "Suppressing integrity audit, integrityAuditPeriodSeconds=([^,]*)"); - - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) audit to immediately terminate. - */ - waitThread(integrityAudit); - - verifyItemsInLog(logA, "-1"); - - logger.info("testNegativeAuditPeriod: Exiting"); - - } - - /* - * Verifies (via log parsing) that when an audit period of zero is specified, the audit runs - * continuously, generating a number of sleep/wake sequences in a short period of time (e.g. - * 100ms). - */ - @Test - void testZeroAuditPeriod() throws Exception { - - logger.info("testZeroAuditPeriod: Entering"); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "0"); - - final ExtractAppender logA = watch(debugLogger, "[Aa]waking from (0s) sleep"); - - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Wait for - * - * 1) audit to generate a bunch of sleep wake sequences. - */ - String[] awakings = new String[10]; - for (int x = 0; x < awakings.length; ++x) { - awakings[x] = "0s"; - runAudit(integrityAudit); - } - - // run a couple more audits - runAudit(integrityAudit); - runAudit(integrityAudit); - - /* - * We should get at least 10 sleep/wake sequences. - */ - - verifyItemsInLog(logA, awakings); - - logger.info("testZeroAuditPeriod: Exiting"); - - } - - /** - * Verifies that when different audit periods are specified, there is an appropriate interval - * between the audits. - */ - @Test - void testLongAuditPeriod() throws Exception { - - logger.info("testLongAuditPeriod: Entering"); - - testAuditPeriod(100); - testAuditPeriod(200); - - logger.info("testLongAuditPeriod: Exiting"); - } - - /** - * Verifies that audits actually take as long as expected, even with multiple auditors running - * simultaneously. - * - * @param periodSec audit period, in seconds - * @throws Exception if an error occurs - * @throws InterruptedException if the thread is interrupted - */ - private void testAuditPeriod(long periodSec) throws Exception { - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, String.valueOf(periodSec)); - - /* - * Start several auditors. - */ - MyIntegrityAudit[] ia = new MyIntegrityAudit[3]; - for (int x = 0; x < ia.length; ++x) { - ia[x] = makeAuditor("pdp" + x, A_SEQ_PU); - } - - /* - * Run an audit on all of them. - */ - runAudit(ia); - - /* - * Now run again and ensure it waited long enough between runs. - */ - long tmin = minAuditTime(ia); - assertTrue(tmin >= periodSec + AuditThread.AUDIT_COMPLETION_INTERVAL * AuditThread.AUDIT_RESET_CYCLES); - - /* - * Now run again and ensure it waited long enough between runs. - */ - tmin = minAuditTime(ia); - assertTrue(tmin >= periodSec + AuditThread.AUDIT_COMPLETION_INTERVAL * AuditThread.AUDIT_RESET_CYCLES); - } - - /** - * Runs simultaneous audits on several auditors. - * - * @param auditors the auditors - * @return the minimum time, in milliseconds, elapsed for any given auditor - * @throws InterruptedException if the thread is interrupted - */ - private long minAuditTime(MyIntegrityAudit... auditors) throws InterruptedException { - List<Thread> threads = new ArrayList<>(auditors.length); - AtomicLong tmin = new AtomicLong(Long.MAX_VALUE); - - // create the threads - for (MyIntegrityAudit p : auditors) { - Thread auditThread = new Thread() { - - @Override - public void run() { - try { - long tbegin = p.getTimeInMillis(); - runAudit(p); - long elapsed = p.getTimeInMillis() - tbegin; - - synchronized (tmin) { - tmin.set(Math.min(tmin.get(), elapsed)); - } - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - }; - - auditThread.setDaemon(true); - threads.add(auditThread); - } - - // start the threads - for (Thread t : threads) { - t.start(); - } - - // wait for them to complete - for (Thread t : threads) { - t.join(); - } - - return tmin.get(); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditorTimeTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditorTimeTest.java deleted file mode 100644 index 9899ca25..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditorTimeTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2024 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.junit.jupiter.api.Test; -import org.onap.policy.common.utils.time.CurrentTime; - -/** - * Tests the AuditorTime class. - */ -class AuditorTimeTest { - - @Test - void testGetInstance() { - CurrentTime inst = AuditorTime.getInstance(); - assertNotNull(inst); - - assertEquals(inst, AuditorTime.getInstance()); - } - -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java deleted file mode 100644 index c9837e03..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java +++ /dev/null @@ -1,551 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2024 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.policy.common.ia.jpa.IaTestEntity; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -import org.onap.policy.common.ia.jpa.PersonSample; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - -/* - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - */ -class DbAuditCompareEntriesTest extends IntegrityAuditTestBase { - private static final String ZAPHOD = "Zaphod"; - - private static Logger logger = FlexLogger.getLogger(DbAuditCompareEntriesTest.class); - - private DbDao dbDao; - private static String resourceName = "pdp1"; - - @BeforeAll - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase - .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditCompareEntriesTest.class.getSimpleName()); - } - - @AfterAll - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } - - /** - * Set up for test cases. - */ - @Override - @BeforeEach - public void setUp() { - - logger.info("setUp: Entering"); - - super.setUp(); - - truncateTables(makeProperties()); - - logger.info("setUp: Exiting"); - } - - /** - * Clean up DB after each test. - */ - @Override - @AfterEach - public void tearDown() { - logger.info("tearDown: Entering"); - - dbDao.destroy(); - - super.tearDown(); - - logger.info("tearDown: Exiting"); - } - - /* - * Tests that a comparison between hashsets is successful if the entries match - */ - // @Ignore - @Test - void testSuccessfulComparison() throws Exception { - logger.info("testSuccessfulComparison: Entering"); - - dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties()); - final DbAudit dbAudit = new DbAudit(dbDao); - - String className = null; - // There is only one entry IntegrityAuditEntity, but we will check - // anyway - Set<String> classNameSet = dbDao.getPersistenceClassNames(); - for (String c : classNameSet) { - if ("org.onap.policy.common.ia.jpa.IntegrityAuditEntity".equals(c)) { - className = c; - } - } - final String resourceName1 = resourceName; - final String resourceName2 = resourceName; - - final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - Date date = new Date(); - - /* - * Two entries with the same field values - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(DB_DRIVER); - entry1.setJdbcPassword(DB_PASS); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(DB_USER); - entry1.setLastUpdated(date); - entry1.setNodeType(NODE_TYPE); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(SITE_NAME); - - entry2.setDesignated(false); - entry2.setJdbcDriver(DB_DRIVER); - entry2.setJdbcPassword(DB_PASS); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(DB_USER); - entry2.setLastUpdated(date); - entry2.setNodeType(NODE_TYPE); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(SITE_NAME); - - dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); - - HashMap<Object, Object> myEntries = new HashMap<>(); - HashMap<Object, Object> theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there are no mismatches returned - */ - assertTrue(result.isEmpty()); - - logger.info("testSuccessfulComparison: Exit"); - } - - /* - * Tests that an error is detected if an entry in one hashset doesn't match the other - */ - // @Ignore - @Test - void testComparisonError() throws Exception { - logger.info("testComparisonError: Entering"); - - dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties()); - final DbAudit dbAudit = new DbAudit(dbDao); - - final String resourceName1 = resourceName; - final String resourceName2 = resourceName; - - final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - Date date = new Date(); - - /* - * Create two entries with different designated values - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(DB_DRIVER); - entry1.setJdbcPassword(DB_PASS); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(DB_USER); - entry1.setLastUpdated(date); - entry1.setNodeType(NODE_TYPE); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(SITE_NAME); - - entry2.setDesignated(true); - entry2.setJdbcDriver(DB_DRIVER); - entry2.setJdbcPassword(DB_PASS); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(DB_USER); - entry2.setLastUpdated(date); - entry2.setNodeType(NODE_TYPE); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(SITE_NAME); - - HashMap<Object, Object> myEntries = new HashMap<>(); - HashMap<Object, Object> theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there was one mismatch - */ - assertEquals(1, result.size()); - - logger.info("testComparisonError: Exit"); - } - - /* - * Tests that a mismatch/miss entry is detected if there are missing entries in one or both of - * the hashsets - */ - // @Ignore - @Test - void testCompareMissingEntries() throws Exception { - logger.info("testCompareMissingEntries: Entering"); - - dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties()); - final DbAudit dbAudit = new DbAudit(dbDao); - - final String resourceName1 = resourceName; - final String resourceName2 = resourceName; - - final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - final IntegrityAuditEntity entry3 = new IntegrityAuditEntity(); - final IntegrityAuditEntity entry4 = new IntegrityAuditEntity(); - - Date date = new Date(); - - /* - * 4 entries, one mismatch, two miss entries - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(DB_DRIVER); - entry1.setJdbcPassword(DB_PASS); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(DB_USER); - entry1.setLastUpdated(date); - entry1.setNodeType(NODE_TYPE); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(SITE_NAME); - - entry2.setDesignated(true); - entry2.setJdbcDriver(DB_DRIVER); - entry2.setJdbcPassword(DB_PASS); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(DB_USER); - entry2.setLastUpdated(date); - entry2.setNodeType(NODE_TYPE); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(SITE_NAME); - - entry3.setDesignated(false); - entry3.setJdbcDriver(DB_DRIVER); - entry3.setJdbcPassword(DB_PASS); - entry3.setJdbcUrl(dbUrl); - entry3.setJdbcUser(DB_USER); - entry3.setLastUpdated(date); - entry3.setNodeType(NODE_TYPE); - entry3.setPersistenceUnit(A_SEQ_PU); - entry3.setResourceName(resourceName2); - entry3.setSite("SiteB"); - - entry4.setDesignated(false); - entry4.setJdbcDriver(DB_DRIVER); - entry4.setJdbcPassword(DB_PASS); - entry4.setJdbcUrl(dbUrl); - entry4.setJdbcUser(DB_USER); - entry4.setLastUpdated(date); - entry4.setNodeType(NODE_TYPE); - entry4.setPersistenceUnit(A_SEQ_PU); - entry4.setResourceName(resourceName2); - entry4.setSite("SiteB"); - - HashMap<Object, Object> myEntries = new HashMap<>(); - HashMap<Object, Object> theirEntries = new HashMap<>(); - - myEntries.put("0", entry1); - myEntries.put("1", entry3); - theirEntries.put("0", entry2); - theirEntries.put("2", entry4); - - Set<Object> mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert 3 mismatches/missing entries were found - */ - assertEquals(3, mismatchResult.size()); - - logger.info("testCompareMissingEntries: Exit"); - } - - /* - * Tests that comparison algorithm works for each entity in the hashsets - */ - // @Ignore - @Test - void testCompareAllHashEntities() throws Exception { - logger.info("testCompareAllHashEntities: Entering"); - - dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties()); - DbAudit dbAudit = new DbAudit(dbDao); - - Set<String> classNameSet = dbDao.getPersistenceClassNames(); - for (String className : classNameSet) { - if ("org.onap.policy.common.ia.jpa.IntegrityAuditEntity".equals(className)) { - final String resourceName1 = resourceName; - final String resourceName2 = resourceName; - - final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - Date date = new Date(); - - /* - * Two entries with the same field values - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(DB_DRIVER); - entry1.setJdbcPassword(DB_PASS); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(DB_USER); - entry1.setLastUpdated(date); - entry1.setNodeType(NODE_TYPE); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(SITE_NAME); - - entry2.setDesignated(false); - entry2.setJdbcDriver(DB_DRIVER); - entry2.setJdbcPassword(DB_PASS); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(DB_USER); - entry2.setLastUpdated(date); - entry2.setNodeType(NODE_TYPE); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(SITE_NAME); - - HashMap<Object, Object> myEntries = new HashMap<>(); - HashMap<Object, Object> theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - /* - * Assert there was no mismatches - */ - assertTrue(dbAudit.compareEntries(myEntries, theirEntries).isEmpty()); - } else if ("org.onap.policy.common.ia.jpa.IaTestEntity".equals(className)) { - final IaTestEntity iate = new IaTestEntity(); - final IaTestEntity iate2 = new IaTestEntity(); - final IaTestEntity iate3 = new IaTestEntity(); - final IaTestEntity iate4 = new IaTestEntity(); - - Date date = new Date(); - - /* - * Four entries, 2 mismatches - */ - iate.setCreatedBy("Ford"); - iate.setModifiedBy("Ford"); - iate.setModifiedDate(date); - - iate2.setCreatedBy("Ford"); - iate2.setModifiedBy(ZAPHOD); - iate2.setModifiedDate(date); - - iate3.setCreatedBy(ZAPHOD); - iate3.setModifiedBy("Ford"); - iate3.setModifiedDate(date); - - iate4.setCreatedBy("Ford"); - iate4.setModifiedBy("Ford"); - iate4.setModifiedDate(date); - - HashMap<Object, Object> myEntries = new HashMap<>(); - HashMap<Object, Object> theirEntries = new HashMap<>(); - - myEntries.put("0", iate); - myEntries.put("1", iate2); - theirEntries.put("0", iate3); - theirEntries.put("1", iate4); - - - /* - * Assert that there is 2 mismatches - */ - assertEquals(2, dbAudit.compareEntries(myEntries, theirEntries).size()); - } - } - - logger.info("testCompareAllHashEntities: Exit"); - } - - /* - * Tests that comparison algorithm works for each entity in the database - */ - @Test - void testCompareAllDbEntities() throws Exception { - logger.info("testCompareAllDbEntities: Entering"); - - logger.info("Setting up DB"); - - IntegrityAudit.setUnitTesting(true); - - Properties properties = makeProperties(); - - Properties properties2 = makeProperties(); - properties2.put(IntegrityAuditProperties.DB_URL, - "jdbc:h2:mem:" + DbAuditCompareEntriesTest.class.getSimpleName() + "2"); - - // Clean up the two DBs - truncateTables(properties); - truncateTables(properties2); - - // Add entries into DB1 - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - new DbDao("pdp2", A_SEQ_PU, properties).destroy(); - DbAudit dbAudit = new DbAudit(dbDao); - - // Add entries into DB2 - DbDao dbDao3 = new DbDao(resourceName, A_SEQ_PU, properties2); - new DbDao("pdp2", A_SEQ_PU, properties2).destroy(); - - // Pull all entries and compare - Set<String> classNameSet = dbDao.getPersistenceClassNames(); - Map<Object, Object> myEntries; - Map<Object, Object> theirEntries; - Set<Object> mismatchResult = new HashSet<>(); - for (String className : classNameSet) { - logger.info("classNameSet entry = " + className); - myEntries = dbDao.getAllEntries(A_SEQ_PU, properties, className); - theirEntries = dbDao3.getAllEntries(A_SEQ_PU, properties2, className); - mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - if (className.contains("IntegrityAuditEntity")) { - break; - } - } - - dbDao3.destroy(); - - // Assert that there is 2 mismatches between IntegrityAuditEntity tables - assertEquals(2, mismatchResult.size()); - - logger.info("testCompareAllDbEntities: Exit"); - } - - /** - * Truncate the tables. - * - * @param properties the properties - */ - private void truncateTables(Properties properties) { - truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity"); - truncateTable(properties, A_SEQ_PU, "IaTestEntity"); - } - - /* - * Tests that differences in embedded classes are still caught - */ - // @Ignore - @Test - void testEmbeddedClass() throws Exception { - logger.info("testEmbeddedClasses: Entering"); - - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - final DbAudit dbAudit = new DbAudit(dbDao); - - String className = null; - // There is only one entry IntegrityAuditEntity, but we will check - // anyway - Set<String> classNameSet = dbDao.getPersistenceClassNames(); - for (String classNameInClassNameSet : classNameSet) { - if ("org.onap.policy.common.ia.jpa.IaTestEntity".equals(classNameInClassNameSet)) { - className = classNameInClassNameSet; - } - } - - final IaTestEntity iate = new IaTestEntity(); - final IaTestEntity iate2 = new IaTestEntity(); - - final Date date = new Date(); - - PersonSample person = new PersonSample("Ford", "Prefect", 21); - PersonSample person2 = new PersonSample(ZAPHOD, "Beeblebrox", 25); - - /* - * Silly tests to bump coverage stats, not sure why they are counting PersonSample to begin - * with. Will have to look into that at some point. - */ - assertNotEquals(person.getAge(), person2.getAge()); - assertNotEquals(person.getFirstName(), person2.getFirstName()); - assertNotEquals(person.getLasttName(), person2.getLasttName()); - PersonSample personTest = new PersonSample(null, null, 0); - personTest.setAge(person.getAge()); - personTest.setFirstName(person.getFirstName()); - personTest.setLastName(person.getLasttName()); - /* - * Two entries, 1 mismatch - */ - iate.setCreatedBy("Ford"); - iate.setModifiedBy(ZAPHOD); - iate.setModifiedDate(date); - iate.setPersonTest(person); - - iate2.setCreatedBy("Ford"); - iate2.setModifiedBy(ZAPHOD); - iate2.setModifiedDate(date); - iate2.setPersonTest(person2); - - dbAudit.writeAuditDebugLog(className, "resource1", "resource2", iate, iate2); - - HashMap<Object, Object> myEntries = new HashMap<>(); - HashMap<Object, Object> theirEntries = new HashMap<>(); - - myEntries.put("0", iate); - theirEntries.put("0", iate2); - - Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there are no mismatches returned - */ - assertTrue(!result.isEmpty()); - - logger.info("testEmbeddedClasses: Exit"); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java deleted file mode 100644 index 507587b7..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023-2024 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import com.google.re2j.Pattern; -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.Persistence; -import java.util.List; -import java.util.Properties; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.common.utils.test.log.logback.ExtractAppender; - -/* - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - * - * If any have been ignored (@Ignore) they will not run at the same time - * as others. You should run them as JUnits by themselves. - */ -class DbAuditTest extends IntegrityAuditTestBase { - - private static Logger logger = FlexLogger.getLogger(DbAuditTest.class); - - private static final Pattern COMMA_PAT = Pattern.compile(","); - private static final String RESOURCE_NAME = "pdp1"; - - private EntityManagerFactory emf2; - private EntityManager em2; - private DbDao dbDao; - - @BeforeAll - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditTest.class.getSimpleName()); - IntegrityAuditEntity.setUnitTesting(true); - } - - @AfterAll - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - IntegrityAuditEntity.setUnitTesting(false); - } - - /** - * Set up for test cases. - */ - @Override - @BeforeEach - public void setUp() { - logger.info("setUp: Entering"); - - super.setUp(); - - dbDao = null; - emf2 = null; - em2 = null; - - logger.info("setUp: Exiting"); - } - - /** - * Tear down after test cases. - */ - @Override - @AfterEach - public void tearDown() { - logger.info("tearDown: Entering"); - - if (dbDao != null) { - dbDao.destroy(); - } - - if (em2 != null) { - em2.close(); - } - - if (emf2 != null) { - emf2.close(); - } - - super.tearDown(); - - logger.info("tearDown: Exiting"); - } - - private void createDb(Properties properties) { - if (emf2 != null) { - throw new IllegalStateException("DB2 has already been created"); - } - - // open the DB and ensure it stays open until the test completes - emf2 = Persistence.createEntityManagerFactory(A_SEQ_PU, properties); - em2 = emf2.createEntityManager(); - - truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity"); - } - - /** - * Tests printing an error to the log in the event where there are no entities saved in the database. - */ - @Test - void testNoEntities() throws Exception { - Properties properties = makeProperties(); - - logger.info("noEntitiesTest: Entering"); - - dbDao = new DbDao(RESOURCE_NAME, A_SEQ_PU, properties); - dbDao.deleteAllIntegrityAuditEntities(); - - assertThatThrownBy(() -> { - DbAudit dbAudit = new DbAudit(dbDao); - dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE); - }).isInstanceOf(DbAuditException.class); - - logger.info("noEntitiesTest: Exit"); - } - - /** - * Tests the detection of only one entry in the database. - */ - @Test - void testOneEntity() throws Exception { - Properties properties = makeProperties(); - - logger.info("oneEntityTest: Entering"); - - final ExtractAppender log = watch(debugLogger, "DbAudit: Found only (one) IntegrityAuditEntity entry:"); - - // Add one entry in the database - dbDao = new DbDao(RESOURCE_NAME, A_SEQ_PU, properties); - DbAudit dbAudit = new DbAudit(dbDao); - dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE); - - List<IntegrityAuditEntity> iaeList = dbDao.getIntegrityAuditEntities(A_SEQ_PU, NODE_TYPE); - logger.info("List size: " + iaeList.size()); - - verifyItemsInLog(log, "one"); - - logger.info("oneEntityTest: Exit"); - } - - /** - * Tests reporting mismatches and missing entries using the error log. - */ - @Test - void testMismatch() throws Exception { - logger.info("mismatchTest: Entering"); - - // use new URLs so we get a completely new DB - String dbUrl = DbAuditTest.dbUrl + "_mismatchTest"; - String dbUrl2 = dbUrl + "2"; - - Properties properties = makeProperties(); - properties.put(IntegrityAuditProperties.DB_URL, dbUrl); - - // Properties for DB2 - Properties properties2 = makeProperties(); - properties2.put(IntegrityAuditProperties.DB_URL, dbUrl2); - - /* - * We must drop and re-create DB1 so that it's sequence generator is in step with the sequence generator for - * DB2. - */ - recreateDb1(properties); - - // create/open DB2 - createDb(properties2); - - final ExtractAppender dbglog = watch(debugLogger, "Mismatched entries [(]keys[)]:(.*)"); - final ExtractAppender errlog = watch(errorLogger, "DB Audit: ([0-9])"); - - /* - * Create entries in DB1 & DB2 for the resource of interest - */ - dbDao = new DbDao(RESOURCE_NAME, A_SEQ_PU, properties); - - new DbDao(RESOURCE_NAME, A_SEQ_PU, properties2).destroy(); - - /* - * Entries in DB1, pointing to DB2, except for pdp3 - */ - new DbDao("pdp2", A_SEQ_PU, properties, dbUrl2).destroy(); - new DbDao("pdp1", A_SEQ_PU, properties, dbUrl2).destroy(); - new DbDao("pdp3", A_SEQ_PU, properties).destroy(); // mismatched URL - new DbDao("pdp4", A_SEQ_PU, properties, dbUrl2).destroy(); - - /* - * Identical entries in DB2, all pointing to DB2, including pdp3, but leaving out pdp4 - */ - new DbDao("pdp2", A_SEQ_PU, properties2).destroy(); - new DbDao("pdp1", A_SEQ_PU, properties2).destroy(); - new DbDao("pdp3", A_SEQ_PU, properties2).destroy(); - - /* - * Run the DB Audit, once it finds a mismatch and sleeps, update DB1 to have the same entry as DB2 it can be - * confirmed that the mismatch is resolved - */ - DbAudit dbAudit = new DbAudit(dbDao); - dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE); - - // update pdp3 entry in DB1 to point to DB2 - new DbDao("pdp3", A_SEQ_PU, properties, dbUrl2).destroy(); - - /* - * Run the audit again and correct the mismatch, the result should be one entry in the mismatchKeySet because of - * the missing entry from the beginning of the test - */ - dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE); - - assertFalse(dbglog.getExtracted().isEmpty()); - - String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1); - int mismatchEntries = COMMA_PAT.split(mismatchIndex.trim()).length; - logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" + " mismatachEntries = " - + mismatchEntries); - - // Assert there is only one entry index - assertEquals(1, mismatchEntries); - - // Now check the entry in the error.log - assertFalse(errlog.getExtracted().isEmpty()); - - String mismatchNum = errlog.getExtracted().get(errlog.getExtracted().size() - 1); - - logger.info("mismatchTest: mismatchNum found: '" + mismatchNum + "'"); - - // Assert that there are a total of 3 mismatches - 1 between each - // comparison node. - assertEquals("3", mismatchNum); - - logger.info("mismatchTest: Exit"); - } - - /** - * Re-creates DB1, using the specified properties. - * - * @param properties the properties - */ - private void recreateDb1(Properties properties) { - em.close(); - emf.close(); - - createDb(properties); - - em = em2; - emf = emf2; - - em2 = null; - emf2 = null; - } - -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java deleted file mode 100644 index da6f0bd5..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java +++ /dev/null @@ -1,452 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023-2024 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import jakarta.persistence.PersistenceUnitUtil; -import jakarta.persistence.Query; -import jakarta.persistence.TypedQuery; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -import org.onap.policy.common.utils.jpa.EntityTransCloser; -import org.onap.policy.common.utils.time.TestTime; - -/* - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - */ -class DbDaoTest extends IntegrityAuditTestBase { - private static final String SELECT_ENTITIES = - "Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"; - private static final String SITE_B = "SiteB"; - private static final String ENTITY_CLASS_NAME = "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"; - - private static final String resourceName = "pdp0"; - - private DbDao dbDao; - - @BeforeAll - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbDaoTest.class.getSimpleName()); - } - - @AfterAll - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } - - @Override - @BeforeEach - public void setUp() { - super.setUp(); - dbDao = null; - } - - /** - * Tear down after test cases. - */ - @Override - @AfterEach - public void tearDown() { - if (dbDao != null) { - dbDao.destroy(); - } - - super.tearDown(); - } - - /* Tests registering a new IntegrityAuditEntity object in the DB */ - @Test - void testNewRegistration() throws Exception { - Properties properties = makeProperties(); - - try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - - // Find the proper entry in the database - Query iaequery = em.createQuery(SELECT_ENTITIES); - iaequery.setParameter("rn", DbDaoTest.resourceName); - iaequery.setParameter("pu", DbDaoTest.A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - - // Assert that the IntegrityAuditEntity object was found - assertNotNull(iaeList); - - // flush to the DB - em.flush(); - et.commit(); - } - } - - /* - * Tests updating an IntegrityAuditEntity if it has already been registered - */ - @Test - void testUpdateRegistration() throws Exception { - Properties properties = makeProperties(); - - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - - // Change site_name in properties to test that an update was made to - // an existing entry in the table - properties.put(IntegrityAuditProperties.SITE_NAME, SITE_B); - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - - try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - // Find the proper entry in the database - Query iaequery = em.createQuery(SELECT_ENTITIES); - iaequery.setParameter("rn", DbDaoTest.resourceName); - iaequery.setParameter("pu", DbDaoTest.A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - - em.refresh(iae); - em.persist(iae); - - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - // Assert that the site_name for the existing entry was updated - assertEquals(SITE_B, iae.getSite()); - } - } - } - - /* Tests obtaining all Integrity Audit Entities from a table */ - @Test - void testGetIntegrityAuditEntities() throws Exception { - Properties properties = makeProperties(); - - // Add some entries to the DB - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - new DbDao("pdp1", A_SEQ_PU, properties).destroy(); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_drools"); - new DbDao("pdp2", A_SEQ_PU, properties).destroy(); - - List<IntegrityAuditEntity> entities; - // Obtain entries based on persistenceUnit and nodeType - entities = dbDao.getIntegrityAuditEntities(A_SEQ_PU, "pdp_xacml"); - assertEquals(2, entities.size()); - } - - /* Tests retrieving a DbDao instance's IntegrityAuditEntity */ - @Test - void testGetMyIntegrityAuditEntity() throws Exception { - Properties properties = makeProperties(); - - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - IntegrityAuditEntity iae = dbDao.getMyIntegrityAuditEntity(); - assertEquals(A_SEQ_PU, iae.getPersistenceUnit()); - } - - /* Tests obtaining an IntegrityAuditEntity by ID */ - @Test - void testGetIntegrityAuditEntity() throws Exception { - Properties properties = makeProperties(); - - // Obtain an entry from the database based on ID - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - - // Find the proper database entry - Query iaequery = em.createQuery(SELECT_ENTITIES); - iaequery.setParameter("rn", DbDaoTest.resourceName); - iaequery.setParameter("pu", DbDaoTest.A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - - // refresh the object from DB in case cached data was returned - em.refresh(iae); - - // Obtain ID for an IntegrityAuditEntity - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - Object iaeId = util.getIdentifier(iae); - - // Obtain the same IntegrityAuditEntity based on ID - IntegrityAuditEntity iaeDuplicate = dbDao.getIntegrityAuditEntity((long) iaeId); - Object duplicateId = util.getIdentifier(iaeDuplicate); - - // Assert that the proper entry was retrieved based on ID - assertEquals((long) iaeId, (long) duplicateId); - } - } - - /* Tests setting an IntegrityAuditEntity as the designated node */ - @Test - void testSetDesignated() throws Exception { - Properties properties = makeProperties(); - - try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - // Create an entry and set it's designated field to true - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - dbDao.setDesignated(resourceName, A_SEQ_PU, true); - - // Find the proper entry in the database - Query iaequery = em.createQuery(SELECT_ENTITIES); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - em.refresh(iae); - - // Check if the node is designated - boolean result = iae.isDesignated(); - - // Assert that it is designated - assertTrue(result); - } - - // flush to the DB - em.flush(); - - // close the transaction - et.commit(); - } - } - - /* Tests that the lastUpdated column in the database is updated properly */ - @Test - void testSetLastUpdated() throws Exception { - Properties properties = makeProperties(); - - try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - TestTime testTime = getTestTime(); - - // Create an entry - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - - // Find the proper entry in the database - Query iaequery = em.createQuery(SELECT_ENTITIES); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(iae); - - // Obtain old update value and set new update value - final Date oldDate = iae.getLastUpdated(); - - // ensure dates are different by sleeping for a bit - testTime.sleep(1); - - iae.setSite(SITE_B); - iae.setLastUpdated(testTime.getDate()); - final Date newDate = iae.getLastUpdated(); - - em.persist(iae); - // flush to the DB - em.flush(); - // close the transaction - et.commit(); - - // Assert that the old and new update times are different - assertNotEquals(oldDate, newDate); - } - } - } - - /* Tests that all the entries from a class can be retrieved */ - @Test - void testGetAllMyEntriesString() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - new DbDao("pdp1", A_SEQ_PU, properties).destroy(); - new DbDao("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain a hash with the persisted objects - Map<Object, Object> entries = dbDao.getAllMyEntries(ENTITY_CLASS_NAME); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests retrieving all entities in a Persistence Unit using the class name and a hashset of IDs - */ - @Test - void testGetAllMyEntriesStringHashSet() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - new DbDao("pdp1", A_SEQ_PU, properties).destroy(); - new DbDao("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain all entity keys - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery<Object> cq = cb.createQuery(); - Root<?> rootEntry = cq.from(Class.forName(ENTITY_CLASS_NAME)); - CriteriaQuery<Object> all = cq.select(rootEntry); - TypedQuery<Object> allQuery = em.createQuery(all); - List<Object> objectList = allQuery.getResultList(); - HashSet<Object> resultSet = new HashSet<>(); - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - for (Object o : objectList) { - Object key = util.getIdentifier(o); - resultSet.add(key); - } - - // Obtain a hash with the persisted objects - Map<Object, Object> entries = - dbDao.getAllMyEntries(ENTITY_CLASS_NAME, resultSet); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests retrieving all entities in a Persistence Unit using the persistence unit, properties, - * and class name - */ - @Test - void testGetAllEntriesStringPropertiesString() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - new DbDao("pdp1", A_SEQ_PU, properties).destroy(); - new DbDao("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain a hash with the persisted objects - Map<Object, Object> entries = dbDao.getAllEntries("integrityAuditPU", properties, - ENTITY_CLASS_NAME); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests retrieving all entities in a Persistence Unit using the persistence unit, properties, - * class name, and a hashset of IDs - */ - @Test - void testGetAllEntriesStringPropertiesStringHashSet() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - new DbDao("pdp1", A_SEQ_PU, properties).destroy(); - new DbDao("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain all entity keys - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery<Object> cq = cb.createQuery(); - Root<?> rootEntry = cq.from(Class.forName(ENTITY_CLASS_NAME)); - CriteriaQuery<Object> all = cq.select(rootEntry); - TypedQuery<Object> allQuery = em.createQuery(all); - List<Object> objectList = allQuery.getResultList(); - HashSet<Object> resultSet = new HashSet<>(); - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - for (Object o : objectList) { - Object key = util.getIdentifier(o); - resultSet.add(key); - } - - // Obtain a hash with the persisted objects - Map<Object, Object> entries = dbDao.getAllEntries("integrityAuditPU", properties, - ENTITY_CLASS_NAME, resultSet); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests getting all the entries from a class based on persistenceUnit, properties, and - * className - */ - @Test - void testGetAllEntries() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - new DbDao("pdp1", A_SEQ_PU, properties).destroy(); - new DbDao("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain a hash with the persisted objects - Map<Object, Object> entries = - dbDao.getAllEntries(A_SEQ_PU, properties, ENTITY_CLASS_NAME); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /** - * Tests obtaining all class names of persisted classes. - */ - void testGetPersistenceClassNames() throws Exception { - Properties properties = makeProperties(); - - dbDao = new DbDao(resourceName, A_SEQ_PU, properties); - - // Retrieve persistence class names - Set<String> result = dbDao.getPersistenceClassNames(); - assertEquals(1, result.size()); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java deleted file mode 100644 index d35260dd..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2024 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.File; -import java.io.IOException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; -import org.onap.policy.common.utils.resources.TextFileUtils; -import org.slf4j.Logger; -import org.slf4j.MDC; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * Test the default logging pattern. - * - */ -class DefaultLoggingPatternTest { - // XLogger for this class - private static final XLogger XLOGGER = XLoggerFactory.getXLogger(DefaultLoggingPatternTest.class); - - // Logger for this class - private static final Logger LOGGER = XLoggerFactory.getXLogger(DefaultLoggingPatternTest.class); - - /** - * Delete logging file after test. - */ - @AfterAll - public static void deleteLogFile() { - new File("testingLogs/common-modules/integrity-audit/logging-pattern-test.log").deleteOnExit(); - } - - /** - * Test XLogger output. - * - * @throws IOException on errors - */ - @Test - void testDefaultLoggingPatternXLogger() throws IOException { - testDefaultLoggingPattern(XLOGGER, "xlogger"); - } - - /** - * Test Logger output. - * - * @throws IOException on errors - */ - @Test - void testDefaultLoggingPatternLogger() throws IOException { - testDefaultLoggingPattern(LOGGER, "logger"); - } - - /** - * Test Logger output. - * - * @throws IOException on errors - */ - void testDefaultLoggingPattern(final Logger logger, final String loggerString) throws IOException { - MDC.put("requestId", "TheRequestId"); - MDC.put("serviceInstanceId", "TheServiceInstanceId"); - MDC.put("serverName", "TheServerName"); - MDC.put("serviceName", "TheServiceName"); - MDC.put("instanceUuid", "TheInstanceUuid"); - MDC.put("severity", "TheSeverity"); - MDC.put("serverIpAddress", "TheServerIpAddress"); - MDC.put("server", "TheServer"); - MDC.put("clientIpAddress", "TheClientIpAddress"); - - logger.info("This is a test logging string for {}", loggerString); - - // Jump past the date, and the actual and expected logged strings should be the same - String actualLoggedString = - TextFileUtils.getTextFileAsString("testingLogs/common-modules/integrity-audit/logging-pattern-test.log") - .substring(23); - String expectedLoggedString = TextFileUtils - .getTextFileAsString("src/test/resources/" + loggerString + "-test.expectedlog").substring(23).trim(); - - assertThat(actualLoggedString).contains(expectedLoggedString); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java deleted file mode 100644 index 988d875d..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Monitor - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2024 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; -import org.onap.policy.common.utils.test.ExceptionsTester; - -/** - * Tests various Exception subclasses. - */ -class ExceptionsTest extends ExceptionsTester { - - @Test - void testDbAuditException() { - assertEquals(4, test(DbAuditException.class)); - } - - @Test - void testDbDaoTransactionException() { - assertEquals(4, test(DbDaoTransactionException.class)); - } - - @Test - void testIntegrityAuditException() { - assertEquals(4, test(IntegrityAuditException.class)); - } - - @Test - void testIntegrityAuditPropertiesException() { - assertEquals(4, test(IntegrityAuditPropertiesException.class)); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java deleted file mode 100644 index 499d29a0..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java +++ /dev/null @@ -1,593 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2024 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.common.utils.test.log.logback.ExtractAppender; - -/** - * All JUnits are designed to run in the local development environment where they have write - * privileges and can execute time-sensitive tasks. - * - * <p>Many of the test verification steps are performed by scanning for items written to the log - * file. Rather than actually scan the log file, an {@link ExtractAppender} is used to monitor - * events that are logged and extract relevant items. In order to attach the appender to the debug - * log, it assumes that the debug log is a <i>logback</i> Logger configured per EELF. - * - * <p>These tests use a temporary, in-memory DB, which is dropped once the tests complete. - */ -class IntegrityAuditDesignationTest extends IntegrityAuditTestBase { - - private static Logger logger = FlexLogger.getLogger(IntegrityAuditDesignationTest.class); - - /** - * Matches specified PDPs in the debug log. A regular expression matching the desired PDPs - * should be appended, followed by a right parenthesis. For example: - * - * <pre> - * <code>new ExtractAppender(START_AUDIT_RE_PREFIX + "pdp[124])") - * </code> - * </pre> - */ - private static final String START_AUDIT_RE_PREFIX = "Running audit for persistenceUnit=\\w+ on resourceName=("; - - @BeforeAll - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase - .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + IntegrityAuditDesignationTest.class.getSimpleName()); - } - - @AfterAll - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } - - /** - * Set up before test cases. - */ - @Override - @BeforeEach - public void setUp() { - logger.info("setUp: Entering"); - - super.setUp(); - - logger.info("setUp: Exiting"); - } - - /** - * Tear down after test cases. - */ - @Override - @AfterEach - public void tearDown() { - logger.info("tearDown: Entering"); - - super.tearDown(); - - logger.info("tearDown: Exiting"); - - } - - /* - * Tests designation logic when only one functioning resource is in play. Designation should - * stay with single resource. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testOneResource() throws Exception { - - logger.info("testOneResource: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Wait for - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that no other node is available for designation - * - * 3) pdp1 to run audit again - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit); - - logger.info("testOneResource: Stopping audit thread"); - integrityAudit.stopAuditThread(); - - verifyItemsInLog(logA, "pdp1"); - - /* - * Test fix for ONAPD2TD-783: Audit fails to run when application is restarted. - */ - integrityAudit.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that no other node is available for designation - * - * 3) pdp1 to run audit again - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1"); - - logger.info("testOneResource: Exiting"); - - } - - /* - * Tests designation logic when two functioning resources are in play. Designation should - * alternate between resources. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testTwoResources() throws Exception { - - logger.info("testTwoResources: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 - * - * 3) pdp2 to run audit - * - * 4) Logic to detect that pdp2 is stale and designate pdp1 - * - * 5) pdp1 to run audit - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp1"); - - logger.info("testTwoResources: Exiting"); - - } - - /* - * Tests designation logic when two functioning resources are in play, each with different PUs. - * Audits for persistenceUnit and PU_B should run simultaneously. Designation should not - * alternate. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testTwoResourcesDifferentPus() throws Exception { - - logger.info("testTwoResourcesDifferentPus: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1)"); - final ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2)"); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 and pdp2 to run audit simultaneously - * - * 2) Logic to detect that no other node is available for designation for either pdp1 or - * pdp2 - * - * 3) pdp1 and pdp2 to again run audit simultaneously - */ - runAudit(integrityAudit, integrityAudit2); - waitStaleAndRun(integrityAudit, integrityAudit2); - - verifyItemsInLog(logA, "pdp1", "pdp1"); - verifyItemsInLog(logB, "pdp2", "pdp2"); - - logger.info("testTwoResourcesDifferentPus: Exiting"); - - } - - /* - * Tests designation logic when two resources are in play but one of them is dead/hung. - * Designation should move to second resource but then get restored back to original resource - * when it's discovered that second resource is dead. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testTwoResourcesOneDead() throws Exception { - - logger.info("testTwoResourcesOneDead: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Populate DB for pdp2, which will simulate it having registered but then having died. - */ - new DbDao("pdp2", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that other node, pdp2, is not available for designation - * - * 3) pdp1 to run audit again - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp1"); - - logger.info("testTwoResourcesOneDead: Exiting"); - - } - - /* - * Tests designation logic when three functioning resources are in play. Designation should - * round robin among resources. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testThreeResources() throws Exception { - - logger.info("testThreeResources: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Start audit for pdp3. - */ - MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 - * - * 3) pdp2 to run audit - * - * 4) Logic to detect that pdp2 is stale and designate pdp3 - * - * 5) pdp3 to run audit - * - * 6) Logic to detect that pdp3 is stale and designate pdp1 - * - * 7) pdp1 to run audit - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit3); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1"); - - logger.info("testThreeResources: Exiting"); - - } - - /* - * Tests designation logic when four functioning resources are in play, two with one PU, two - * with another. Audits for persistenceUnit and PU_B should run simultaneously. Designation - * should alternate between resources for each of the two persistence units. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testFourResourcesDifferentPus() throws Exception { - - logger.info("testFourResourcesDifferentPus: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1|pdp3)"); - final ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2|pdp4)"); - - /* - * Start audit for "pdp1", testPU. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2, integrityAuditPU. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU); - - /* - * Start audit for pdp3, testPU. - */ - MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - /* - * Start audit for pdp4, integrityAuditPU. - */ - MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", B_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 and pdp2 to run audit simultaneously - * - * 2) Logic to detect that pdp1 and pdp2 are stale and designate pdp3 (one's counterpart) - * and pdp4 (two's counterpart) - * - * 3) pdp3 and pdp4 to run audit simultaneously - * - * 4) Logic to detect that pdp3 and pdp4 are stale and designate pdp1 (three's counterpart) - * and pdp2 (four's counterpart) - * - * 5) pdp1 and pdp2 to run audit simultaneously - */ - runAudit(integrityAudit, integrityAudit2); - waitStaleAndRun(integrityAudit3, integrityAudit4); - waitStaleAndRun(integrityAudit, integrityAudit2); - - /* - * These sequences may be intermingled, so we extract and compare one sequence at a time. - */ - - // only care about pdp1 & pdp3 in this sequence - verifyItemsInLog(logA, "pdp1", "pdp3", "pdp1"); - - // only care about pdp2 & pdp4 in this sequence - verifyItemsInLog(logB, "pdp2", "pdp4", "pdp2"); - - logger.info("testFourResourcesDifferentPus: Exiting"); - - } - - /* - * Tests designation logic when four resources are in play but one is not functioning. - * Designation should round robin among functioning resources only. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testFourResourcesOneDead() throws Exception { - - logger.info("testFourResourcesOneDead: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Populate DB for pdp3, which will simulate it having registered but then having died. - */ - new DbDao("pdp3", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Start audit for pdp4. - */ - MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", A_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 - * - * 3) pdp2 to run audit - * - * 4) Logic to detect that pdp2 is stale and designate pdp4 - * - * 5) pdp4 to run audit - * - * 6) Logic to detect that pdp4 is stale and designate pdp1 - * - * 7) pdp1 to run audit - * - * 8) Logic to detect that pdp1 is stale and designate pdp2 - * - * 7) pdp2 to run audit - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit4); - waitStaleAndRun(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit4); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp4", "pdp1", "pdp2", "pdp4"); - - logger.info("testFourResourcesOneDead: Exiting"); - - } - - /* - * Tests designation logic when four resources are in play but only one is functioning. - * Designation should remain with sole functioning resource. - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testFourResourcesThreeDead() throws Exception { - - logger.info("testFourResourcesThreeDead: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Populate DB for "pdp1", which will simulate it having registered but then having died. - */ - new DbDao("pdp1", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Populate DB for pdp2, which will simulate it having registered but then having died. - */ - new DbDao("pdp2", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Start audit for pdp3. - */ - MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - /* - * Populate DB for pdp4, which will simulate it having registered but then having died. - */ - new DbDao("pdp4", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Sleep long enough to allow - * - * 1) pdp3 to discover that all other designation candidates are stale - * - * 1) pdp3 to run audit - * - * 2) Logic to detect that no other nodes are available for designation - * - * 3) pdp3 to run audit again - */ - runAudit(integrityAudit3); - waitStaleAndRun(integrityAudit3); - - verifyItemsInLog(logA, "pdp3", "pdp3"); - - logger.info("testFourResourcesThreeDead: Exiting"); - - } - - /* - * Tests designation logic when the designated node dies and is no longer current - * - * Note: console.log must be examined to ascertain whether or not this test was successful. - */ - @Test - void testDesignatedNodeDead() throws Exception { - logger.info("testDesignatedNodeDead: Entering"); - - final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Instantiate audit object for pdp1. - */ - final MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - final MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Instantiate audit object for pdp3. - */ - final MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - // Start audit on pdp1 - logger.info("testDesignatedNodeDead: Start audit on pdp1"); - runAudit(integrityAudit); - - // Start the auditing threads on other nodes. - logger.info("testDesignatedNodeDead: Start audit on pdp2"); - runAudit(integrityAudit2); - - // Kill audit on pdp1 - logger.info("testDesignatedNodeDead: Kill audit on pdp1"); - integrityAudit.stopAuditThread(); - - // Wait long enough for pdp1 to get stale and pdp2 to take over - waitStaleAndRun(integrityAudit2); - - // Start audit thread on pdp1 again. - logger.info("testDesignatedNodeDead: Start audit thread on pdp1 again."); - integrityAudit.startAuditThread(); - - // Wait long enough for pdp2 to complete its audit and get stale, at - // which point pdp3 should take over - logger.info( - "testDesignatedNodeDead: Wait long enough for pdp2 to complete its audit and get stale, at which point" - + " pdp3 should take over"); - waitStaleAndRun(integrityAudit3); - - // Kill audit on pdp3 - logger.info("testDesignatedNodeDead: Killing audit on pdp3"); - integrityAudit3.stopAuditThread(); - - // Wait long enough for pdp3 to get stale and pdp1 to take over - logger.info("testDesignatedNodeDead: Wait long enough for pdp3 to get stale and pdp1 to take over"); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1"); - - logger.info("testDesignatedNodeDead: Exiting"); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java deleted file mode 100644 index bd0aad55..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2024 Nordix Foundation - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Properties; -import org.junit.jupiter.api.Test; - -class IntegrityAuditTest { - private static final String PROPERTIES = "properties"; - private static final String RESOURCE_NAME = "resourceName"; - private static final String SOMETHING = "something"; - - /** - * Test if we can access the updated bad params outside of the parmsAreBad method. - */ - @Test - void testParmsAreBad() { - // Try with 2 null params - StringBuilder badParams = new StringBuilder(); - IntegrityAudit.parmsAreBad(null, SOMETHING, null, badParams); - - assertNotEquals("", badParams.toString()); - assertTrue(badParams.toString().contains(RESOURCE_NAME)); - assertTrue(badParams.toString().contains(PROPERTIES)); - - // Try with 1 null params - badParams = new StringBuilder(); - Properties props = new Properties(); - props.put(IntegrityAuditProperties.DB_DRIVER, "test_db_driver"); - IntegrityAudit.parmsAreBad(null, SOMETHING, props, badParams); - - assertNotEquals("", badParams.toString()); - assertTrue(badParams.toString().contains(RESOURCE_NAME)); - assertFalse(badParams.toString().contains(PROPERTIES)); - - // Try with 0 null params - badParams = new StringBuilder(); - IntegrityAudit.parmsAreBad("someting", SOMETHING, props, badParams); - assertNotEquals("", badParams.toString()); - assertFalse(badParams.toString().contains(RESOURCE_NAME)); - assertFalse(badParams.toString().contains(PROPERTIES)); - - // Try with invalid node type - props.put(IntegrityAuditProperties.NODE_TYPE, "bogus"); - badParams = new StringBuilder(); - IntegrityAudit.parmsAreBad("someting", SOMETHING, props, badParams); - assertNotEquals("", badParams.toString()); - assertTrue(badParams.toString().contains("nodeType")); - - } - -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java deleted file mode 100644 index e0c22a1e..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java +++ /dev/null @@ -1,658 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023-2024 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.EntityTransaction; -import jakarta.persistence.Persistence; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; -import org.onap.policy.common.utils.jpa.EntityMgrCloser; -import org.onap.policy.common.utils.jpa.EntityMgrFactoryCloser; -import org.onap.policy.common.utils.jpa.EntityTransCloser; -import org.onap.policy.common.utils.test.log.logback.ExtractAppender; -import org.onap.policy.common.utils.time.CurrentTime; -import org.onap.policy.common.utils.time.TestTime; -import org.slf4j.LoggerFactory; -import org.springframework.test.util.ReflectionTestUtils; - -/** - * All JUnits are designed to run in the local development environment where they have write - * privileges and can execute time-sensitive tasks. - * - * <p>Many of the test verification steps are performed by scanning for items written to the log - * file. Rather than actually scan the log file, an {@link ExtractAppender} is used to monitor - * events that are logged and extract relevant items. In order to attach the appender to the debug - * log, it assumes that the debug log is a <i>logback</i> Logger configured per EELF. - * - * <p>These tests use a temporary, in-memory DB, which is dropped once the tests complete. - */ -class IntegrityAuditTestBase { - - /** - * Root of the debug logger, as defined in the logback-test.xml. - */ - protected static final Logger debugLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.debug"); - - /** - * Root of the error logger, as defined in the logback-test.xml. - */ - protected static final Logger errorLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.error"); - - /** - * Directory containing the log files. - */ - private static final String LOG_DIR = "testingLogs/common-modules/integrity-audit"; - - - /** - * Name of the field within the AuditorTime class that supplies the time. - */ - public static final String TIME_SUPPLY_FIELD = "supplier"; - - - /** - * Max time, in milliseconds, to wait for a semaphore. - */ - protected static final long WAIT_MS = 5000L; - - /** - * Number of seconds in an audit period. - */ - public static final int AUDIT_PERIOD_SEC = 5; - - public static final String DEFAULT_DB_URL_PREFIX = "jdbc:h2:mem:"; - - protected static final String DB_DRIVER = "org.h2.Driver"; - protected static final String DB_USER = "testu"; - protected static final String DB_PASS = "testp"; - protected static final String SITE_NAME = "SiteA"; - protected static final String NODE_TYPE = "pdp_xacml"; - - // will be defined by the test *Classes* - protected static String dbUrl; - - /** - * Persistence unit for PDP sequence A. - */ - protected static final String A_SEQ_PU = "testPU"; - - /** - * Persistence unit for PDP sequence B. - */ - protected static final String B_SEQ_PU = "integrityAuditPU"; - - /** - * Matches the start of an audit for arbitrary PDPs in the debug log. - */ - protected static final String START_AUDIT_RE = "Running audit for persistenceUnit=\\w+ on resourceName=([^,]*)"; - - /** - * Properties to be used in all tests. - */ - protected static Properties properties; - - /** - * Entity manager factory pointing to the in-memory DB for A_SEQ_PU. - */ - protected static EntityManagerFactory emf; - - /** - * Entity manager factory pointing to the in-memory DB associated with emf. - */ - protected static EntityManager em; - - /** - * Current time used by given test. - */ - private static ThreadLocal<TestTime> testTime = ThreadLocal.withInitial(() -> null); - - /** - * Supplies the test time so that each thread maintains its own notion of "current" - * time. - */ - private static Supplier<TestTime> timeSupplier = () -> testTime.get(); - - /** - * Saved debug logger level, to be restored once all tests complete. - */ - private static Level savedDebugLevel; - - /** - * Saved error logger level, to be restored once all tests complete. - */ - private static Level savedErrorLevel; - - /** - * Saved time, to be restored once all tests complete. - */ - private static Supplier<CurrentTime> savedTime; - - /** - * List of auditors whose threads must be stopped when a given test case ends. - */ - private List<MyIntegrityAudit> auditors; - - /** - * List of appenders that must be removed from loggers when a given test case ends. - */ - private List<LogApp> appenders; - - /** - * Saves current configuration information and then sets new values. - * - * @param dbUrl the URL to the DB - * @throws IOException if an IO error occurs - */ - @SuppressWarnings("unchecked") - protected static void setUpBeforeClass(String dbUrl) throws IOException { - - // truncate the logs - new FileOutputStream(LOG_DIR + "/audit.log").close(); - new FileOutputStream(LOG_DIR + "/debug.log").close(); - new FileOutputStream(LOG_DIR + "/error.log").close(); - new FileOutputStream(LOG_DIR + "/metrics.log").close(); - - IntegrityAuditTestBase.dbUrl = dbUrl; - - // save data that we have to restore at the end of the test - savedTime = (Supplier<CurrentTime>) ReflectionTestUtils.getField(AuditorTime.class, TIME_SUPPLY_FIELD); - savedDebugLevel = debugLogger.getLevel(); - savedErrorLevel = errorLogger.getLevel(); - - IntegrityAudit.setUnitTesting(true); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, dbUrl); - properties.put(IntegrityAuditProperties.DB_USER, DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, DB_PASS); - properties.put(IntegrityAuditProperties.SITE_NAME, SITE_NAME); - properties.put(IntegrityAuditProperties.NODE_TYPE, NODE_TYPE); - - emf = Persistence.createEntityManagerFactory(A_SEQ_PU, makeProperties()); - - // keep this open so the in-memory DB stays around until all tests are - // done - em = emf.createEntityManager(); - - ReflectionTestUtils.setField(AuditorTime.class, TIME_SUPPLY_FIELD, timeSupplier); - debugLogger.setLevel(Level.DEBUG); - errorLogger.setLevel(Level.ERROR); - } - - /** - * Restores the configuration to what it was before the test. - */ - protected static void tearDownAfterClass() { - - IntegrityAudit.setUnitTesting(false); - - ReflectionTestUtils.setField(AuditorTime.class, TIME_SUPPLY_FIELD, savedTime); - debugLogger.setLevel(savedDebugLevel); - errorLogger.setLevel(savedErrorLevel); - - // this should result in the in-memory DB being deleted - em.close(); - emf.close(); - } - - /** - * Sets up for a test, which includes deleting all records from the IntegrityAuditEntity table. - */ - protected void setUp() { - auditors = new LinkedList<>(); - appenders = new LinkedList<>(); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, String.valueOf(AUDIT_PERIOD_SEC)); - - TestTime time = new TestTime(); - testTime.set(time); - - // Clean up the DB - try (EntityTransCloser etc = new EntityTransCloser(em.getTransaction())) { - EntityTransaction et = etc.getTransaction(); - - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - } - } - - /** - * Cleans up after a test, removing any ExtractAppenders from the logger and stopping any - * AuditThreads. - */ - protected void tearDown() { - for (LogApp p : appenders) { - p.detach(); - } - - for (MyIntegrityAudit p : auditors) { - p.stopAuditThread(); - } - } - - /** - * Get the test time. - * - * @return the {@link TestTime} in use by this thread - */ - public static TestTime getTestTime() { - return testTime.get(); - } - - /** - * Truncate the table. - * - * @param properties the properties - * @param persistenceUnit the persistence unit - * @param tableName the name of the table - */ - void truncateTable(Properties properties, String persistenceUnit, String tableName) { - - try (EntityMgrFactoryCloser emfc = - new EntityMgrFactoryCloser(Persistence.createEntityManagerFactory(persistenceUnit, properties)); - EntityMgrCloser emc = new EntityMgrCloser(emfc.getFactory().createEntityManager()); - EntityTransCloser etc = new EntityTransCloser(emc.getManager().getTransaction())) { - - EntityManager entmgr = emc.getManager(); - EntityTransaction entrans = etc.getTransaction(); - - // Clean up the DB - entmgr.createQuery("Delete from " + tableName).executeUpdate(); - - // commit transaction - entrans.commit(); - } - } - - /** - * Verifies that items appear within the log, in order. A given item may appear more than once. - * In addition, the log may contain extra items; those are ignored. - * - * @param app where data has been logged - * @param items items that should be matched by the items extracted from the log, in order - * @throws IOException if an IO error occurs - * @throws AssertionError if the desired items were not all found - */ - protected void verifyItemsInLog(ExtractAppender app, String... items) throws IOException { - - Iterator<String> it = new ArrayList<>(Arrays.asList(items)).iterator(); - if (!it.hasNext()) { - return; - } - - String expected = it.next(); - String last = null; - - for (String extractedText : app.getExtracted()) { - if (extractedText.equals(expected)) { - if (!it.hasNext()) { - // matched all of the items - return; - } - - last = expected; - expected = it.next(); - - } else if (!extractedText.equals(last)) { - List<String> remaining = getRemaining(expected, it); - fail("missing items " + remaining + ", but was: " + extractedText); - } - } - - List<String> remaining = getRemaining(expected, it); - assertTrue(remaining.isEmpty(), "missing items " + remaining); - } - - /** - * Gets the remaining items from an iterator. - * - * @param current the current item, to be included within the list - * @param it iterator from which to get the remaining items - * @return a list of the remaining items - */ - private LinkedList<String> getRemaining(String current, Iterator<String> it) { - LinkedList<String> remaining = new LinkedList<>(); - remaining.add(current); - - while (it.hasNext()) { - remaining.add(it.next()); - } - return remaining; - } - - /** - * Waits for a thread to stop. If the thread doesn't complete in the allotted time, then it - * interrupts it and waits again. - * - * @param auditor the thread for which to wait - * @return {@code true} if the thread stopped, {@code false} otherwise - */ - public boolean waitThread(MyIntegrityAudit auditor) { - if (auditor != null) { - try { - auditor.interrupt(); - - if (!auditor.joinAuditThread(WAIT_MS)) { - errorLogger.error("failed to stop audit thread"); - return false; - } - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - - return true; - } - - /** - * Makes a new auditor. - * - * @param resourceName2 the name of the resource - * @param persistenceUnit2 the persistence unit - * @return a new auditor - * @throws Exception if an error occurs - */ - protected MyIntegrityAudit makeAuditor(String resourceName2, String persistenceUnit2) throws Exception { - // each auditor gets its own notion of time - TestTime time = new TestTime(); - - // use the auditor-specific time while this thread constructs things - testTime.set(time); - - return new MyIntegrityAudit(resourceName2, persistenceUnit2, makeProperties(), time); - } - - /** - * Watches for patterns in a logger by attaching a ExtractAppender to it. - * - * @param logger the logger to watch - * @param regex regular expression used to extract relevant text - * @return a new appender - */ - protected ExtractAppender watch(Logger logger, String regex) { - ExtractAppender app = new ExtractAppender(regex); - appenders.add(new LogApp(logger, app)); - - return app; - } - - /** - * Makes a new Property set that's a clone of {@link #properties}. - * - * @return a new Property set containing all of a copy of all of the {@link #properties} - */ - protected static Properties makeProperties() { - Properties props = new Properties(); - props.putAll(properties); - return props; - } - - /** - * Waits for data to become stale and then runs an audit on several auditors in parallel. - * - * @param auditors the auditors - * @throws InterruptedException if a thread is interrupted - */ - protected void waitStaleAndRun(MyIntegrityAudit... auditors) throws InterruptedException { - waitStale(); - runAudit(auditors); - } - - /** - * Runs an audit on several auditors in parallel. - * - * @param auditors the auditors - * @throws InterruptedException if a thread is interrupted - */ - protected void runAudit(MyIntegrityAudit... auditors) throws InterruptedException { - - // start an audit cycle on each auditor - List<Semaphore> semaphores = new ArrayList<>(auditors.length); - for (MyIntegrityAudit p : auditors) { - semaphores.add(p.startAudit()); - } - - // wait for each auditor to complete its cycle - for (Semaphore sem : semaphores) { - waitSem(sem); - } - } - - /** - * Waits for a semaphore to be released. - * - * @param sem the semaphore for which to wait - * @throws InterruptedException if the thread is interrupted - * @throws AssertionError if the semaphore did not reach zero in the allotted time - */ - protected void waitSem(Semaphore sem) throws InterruptedException { - assertTrue(sem.tryAcquire(WAIT_MS, TimeUnit.MILLISECONDS)); - } - - /** - * Sleep a bit so that the currently designated pdp becomes stale. - * - * @throws InterruptedException if the thread is interrupted - */ - protected void waitStale() throws InterruptedException { - // waits for ALL auditors to become stale, as each has its own timer - for (MyIntegrityAudit auditor : auditors) { - auditor.sleep(AuditThread.AUDIT_COMPLETION_INTERVAL * AuditThread.AUDIT_RESET_CYCLES + 1); - } - } - - /** - * Tracks which appender has been added to a logger. - */ - private static class LogApp { - private final Logger logger; - private final ExtractAppender appender; - - public LogApp(Logger logger, ExtractAppender appender) { - this.logger = logger; - this.appender = appender; - - logger.addAppender(appender); - - appender.start(); - } - - void detach() { - logger.detachAppender(appender); - } - } - - /** - * Manages audits by inserting semaphores into a queue for the AuditThread to count. - */ - protected class MyIntegrityAudit extends IntegrityAudit { - - private final TestTime myTime; - - /** - * Semaphore on which the audit thread should wait. - */ - private Semaphore auditSem = null; - - /** - * Semaphore on which the junit management thread should wait. - */ - private Semaphore junitSem = null; - - /** - * Constructs an auditor and starts the AuditThread. - * - * @param resourceName the resource name - * @param persistenceUnit the persistence unit - * @param properties the properties - * @param time the time - * @throws Exception if an error occurs - */ - public MyIntegrityAudit(String resourceName, String persistenceUnit, - Properties properties, TestTime time) throws Exception { - super(resourceName, persistenceUnit, properties); - - myTime = time; - testTime.set(myTime); - - auditors.add(this); - - startAuditThread(); - } - - /** - * Get time in milliseconds. - * - * @return the "current" time for the auditor - */ - public long getTimeInMillis() { - return myTime.getMillis(); - } - - /** - * Sleeps for a period of time. - * - * @param sleepMs time to sleep - * @throws InterruptedException can be interrupted - */ - void sleep(long sleepMs) throws InterruptedException { - myTime.sleep(sleepMs); - } - - /** - * Interrupts the AuditThread. - */ - void interrupt() { - super.stopAuditThread(); - } - - /** - * Triggers an audit by releasing the audit thread's semaphore. - * - * @return the semaphore on which to wait - * @throws InterruptedException if the thread is interrupted - */ - public Semaphore startAudit() throws InterruptedException { - auditSem.release(); - return junitSem; - } - - /** - * Starts a new AuditThread. Creates a new pair of semaphores and associates them - * with the thread. - */ - @Override - public final void startAuditThread() throws IntegrityAuditException { - if (auditSem != null) { - // release a bunch of semaphores, in case a thread is still running - auditSem.release(1000); - } - - auditSem = new Semaphore(0); - junitSem = new Semaphore(0); - - super.startAuditThread(); - - if (haveAuditThread()) { - // tell the thread it can run - auditSem.release(); - - // wait for the thread to start - try { - waitSem(junitSem); - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IntegrityAuditException(e); - } - } - } - - /** - * Stops the AuditThread and waits for it to stop. - * - * @throws AssertionError if the thread is still running - */ - @Override - public void stopAuditThread() { - super.stopAuditThread(); - - assertTrue(waitThread(this)); - } - - @Override - protected AuditThread makeAuditThread(String resourceName2, String persistenceUnit2, Properties properties2, - int integrityAuditPeriodSeconds2) throws IntegrityAuditException { - - // make sure we're still using the auditor's time while we construct things - testTime.set(myTime); - - return new AuditThread(resourceName2, persistenceUnit2, properties2, integrityAuditPeriodSeconds2, this) { - - private Semaphore auditSem = MyIntegrityAudit.this.auditSem; - private Semaphore junitSem = MyIntegrityAudit.this.junitSem; - - @Override - public void run() { - // make sure our thread uses this auditor's time - testTime.set(myTime); - super.run(); - } - - @Override - public void runStarted() throws InterruptedException { - auditSem.acquire(); - - junitSem.release(); - auditSem.acquire(); - } - - @Override - public void auditCompleted() throws InterruptedException { - junitSem.release(); - auditSem.acquire(); - } - - }; - } - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java deleted file mode 100644 index 8a34909a..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia.jpa; - -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.NamedQueries; -import jakarta.persistence.NamedQuery; -import jakarta.persistence.PrePersist; -import jakarta.persistence.PreUpdate; -import jakarta.persistence.Table; -import jakarta.persistence.Temporal; -import jakarta.persistence.TemporalType; -import java.io.Serializable; -import java.util.Date; - -@Entity -@Table(name = "IaTestEntity") -@NamedQueries({@NamedQuery(name = " IaTestEntity.findAll", query = "SELECT e FROM IaTestEntity e "), - @NamedQuery(name = "IaTestEntity.deleteAll", query = "DELETE FROM IaTestEntity WHERE 1=1")}) - -public class IaTestEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "ImTestId") - private long imTestId; - - @Column(name = "created_by", nullable = false, length = 255) - private String createdBy = "guest"; - - @Column(name = "person", nullable = false, length = 255) - private PersonSample person; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "created_date", updatable = false) - private Date createdDate; - - @Column(name = "modified_by", nullable = false, length = 255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "modified_date", nullable = false) - private Date modifiedDate; - - public IaTestEntity() { - super(); - } - - /** - * PrePersist call back method. - */ - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - /** - * The the Im test Id. - * - * @return the Id - */ - public long getImTestId() { - return imTestId; - } - - /** - * Get the createdBy. - * - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * Set the createdBy. - * - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * Get the modifiedBy. - * - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * Set the ModifiedBy. - * - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * Get the ModifiedDate. - * - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * Set the ModifiedDate. - * - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - /** - * Get the CreatedDate. - * - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * Set the person. - * - * @param person the person to set - */ - public void setPersonTest(PersonSample person) { - this.person = person; - } - - /** - * Get the person. - * - * @return the person - */ - public PersonSample getPersonTest() { - return person; - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java deleted file mode 100644 index 47fa843b..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Integrity Audit - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.ia.jpa; - -import java.io.Serializable; - -public class PersonSample implements Serializable { - - private static final long serialVersionUID = 1L; - private String firstName; - private String lastName; - private int age; - - /** - * Create an instance. - * - * @param first first name - * @param last last name - * @param age age - */ - public PersonSample(String first, String last, int age) { - this.firstName = first; - this.lastName = last; - this.age = age; - } - - public String getFirstName() { - return this.firstName; - } - - public void setFirstName(String name) { - this.firstName = name; - } - - public String getLasttName() { - return this.lastName; - } - - public void setLastName(String name) { - this.lastName = name; - } - - public int getAge() { - return this.age; - } - - public void setAge(int age) { - this.age = age; - } - -} diff --git a/integrity-audit/src/test/resources/log4j.properties b/integrity-audit/src/test/resources/log4j.properties deleted file mode 100644 index 3defb164..00000000 --- a/integrity-audit/src/test/resources/log4j.properties +++ /dev/null @@ -1,54 +0,0 @@ -### -# ============LICENSE_START======================================================= -# Integrity Audit -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= -### - -# -# Use this properties for debugging and development. -# -# -# For debug output, set root logger level to DEBUG and output to FILE and CONSOLE -log4j.rootLogger=DEBUG, FILE, CONSOLE -#log4j.rootLogger=INFO, FILE, CONSOLE - -# A1 is set to be a DailyRollingFileAppender. -log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender - -# Set the name of the file -log4j.appender.FILE.File=IntegrityAudit.log - -# Set the immediate flush to true (default) -log4j.appender.FILE.ImmediateFlush=true - -# Set the threshold to debug mode -log4j.appender.FILE.Threshold=debug - -# Set the append to false, should not overwrite -log4j.appender.FILE.Append=true - -# Set the DatePattern -log4j.appender.FILE.DatePattern='.'yyyy-MM-dd - -# A1 uses PatternLayout. -log4j.appender.FILE.layout=org.apache.log4j.PatternLayout -log4j.appender.FILE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n - -# for Developments and Debugging -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n diff --git a/integrity-audit/src/test/resources/logback-test.xml b/integrity-audit/src/test/resources/logback-test.xml deleted file mode 100644 index e3867e79..00000000 --- a/integrity-audit/src/test/resources/logback-test.xml +++ /dev/null @@ -1,258 +0,0 @@ -<!-- - ============LICENSE_START======================================================= - Integrity Audit - ================================================================================ - Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - --> - -<!-- Controls the output of logs for JUnit tests --> - -<configuration - scan="false" - debug="true"> - <!--<jmxConfigurator /> --> - <!-- directory path for all other type logs --> - <property - name="logDir" - value="testingLogs" /> - - <!-- directory path for debugging type logs --> - <property - name="debugDir" - value="testingLogs" /> - - <!-- specify the component name - <ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> - <property - name="componentName" - value="common-modules"></property> - <property - name="subComponentName" - value="integrity-audit"></property> - - <!-- log file names --> - <property - name="errorLogName" - value="error" /> - <property - name="metricsLogName" - value="metrics" /> - <property - name="auditLogName" - value="audit" /> - <property - name="debugLogName" - value="debug" /> - - <property - name="defaultPatternTimestamp" - value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}" /> - - <property - name="defaultPatternTarget" - value="%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}" /> - - - <property - name="defaultPatternDetails" - value="%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}" /> - - <property - name="defaultPattern" - value="${defaultPatternTimestamp}|${defaultPatternTarget}|%p|${defaultPatternDetails}|%c||%msg%n" /> - - <property - name="logDirectory" - value="${logDir}/${componentName}/${subComponentName}" /> - <property - name="debugLogDirectory" - value="${debugDir}/${componentName}/${subComponentName}" /> - <!-- - <property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" /> - <property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" /> - --> - <!-- example from old log4j.properties: ${catalina.base}/logs/pdp-rest.log --> - <!-- Example evaluator filter applied against console appender --> - <appender - name="STDOUT" - class="ch.qos.logback.core.ConsoleAppender"> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - <!-- ============================================================================ --> - <!-- EELF Appenders --> - <!-- ============================================================================ --> - - <!-- The EELFAppender is used to record events to the general application - log --> - - - - - <!-- EELF Audit Appender. This appender is used to record audit engine - related logging events. The audit logger and appender are specializations - of the EELF application root logger and appender. This can be used to segregate - Policy engine events from other components, or it can be eliminated to record - these events as part of the application root log. --> - - <appender - name="EELFAudit" - class="ch.qos.logback.core.FileAppender"> - <file>${logDirectory}/${auditLogName}.log</file> - <param - name="Append" - value="false" /> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - <appender - name="asyncEELFAudit" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFAudit" /> - </appender> - - <appender - name="EELFMetrics" - class="ch.qos.logback.core.FileAppender"> - <file>${logDirectory}/${metricsLogName}.log</file> - <param - name="Append" - value="false" /> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - - <appender - name="asyncEELFMetrics" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFMetrics" /> - </appender> - - <appender - name="EELFError" - class="ch.qos.logback.core.FileAppender"> - <file>${logDirectory}/${errorLogName}.log</file> - <param - name="Append" - value="false" /> - <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> - <level>ERROR</level> - </filter> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - <appender - name="asyncEELFError" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFError" /> - </appender> - - <appender - name="EELFDebug" - class="ch.qos.logback.core.FileAppender"> - <file>${debugLogDirectory}/${debugLogName}.log</file> - <param - name="Append" - value="false" /> - <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> - <level>DEBUG</level> - </filter> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - <appender - name="asyncEELFDebug" - class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>256</queueSize> - <appender-ref ref="EELFDebug" /> - <includeCallerData>true</includeCallerData> - </appender> - - <!-- Appender for log testing --> - <appender - name="LoggingPatternTestAppender" - class="ch.qos.logback.core.FileAppender"> - <file>${logDirectory}/logging-pattern-test.log</file> - <param - name="Append" - value="false" /> - <encoder> - <pattern>${defaultPattern}</pattern> - </encoder> - </appender> - - - <!-- ============================================================================ --> - <!-- EELF loggers --> - <!-- ============================================================================ --> - - <logger - name="com.att.eelf.audit" - level="info" - additivity="false"> - <appender-ref ref="asyncEELFAudit" /> - </logger> - - <logger - name="com.att.eelf.metrics" - level="info" - additivity="false"> - <appender-ref ref="asyncEELFMetrics" /> - </logger> - - <logger - name="com.att.eelf.error" - level="error" - additivity="false"> - <appender-ref ref="asyncEELFError" /> - </logger> - - <!-- <logger name="com.att.eelf.debug" level="info" additivity="false"> --> - <logger - name="com.att.eelf.debug" - level="debug" - additivity="false"> - <appender-ref ref="asyncEELFDebug" /> - </logger> - - - <!-- <root level="INFO"> --> - <root level="DEBUG"> - <appender-ref ref="asyncEELFDebug" /> - <appender-ref ref="asyncEELFError" /> - </root> - - <!-- Logger for default pattern test --> - <logger - name="org.onap.policy.common.ia.DefaultLoggingPatternTest" - level="trace" - additivity="false"> - <appender-ref ref="LoggingPatternTestAppender" /> - </logger> - -</configuration> diff --git a/integrity-audit/src/test/resources/logger-test.expectedlog b/integrity-audit/src/test/resources/logger-test.expectedlog deleted file mode 100644 index 69df8f96..00000000 --- a/integrity-audit/src/test/resources/logger-test.expectedlog +++ /dev/null @@ -1 +0,0 @@ -2019-12-05T13:24:14.110Z|TheRequestId|TheServiceInstanceId|main|TheServerName|TheServiceName|TheInstanceUuid|INFO|TheSeverity|TheServerIpAddress|TheServer|TheClientIpAddress|org.onap.policy.common.ia.DefaultLoggingPatternTest||This is a test logging string for logger diff --git a/integrity-audit/src/test/resources/policyLogger.properties b/integrity-audit/src/test/resources/policyLogger.properties deleted file mode 100644 index 42cf1cfd..00000000 --- a/integrity-audit/src/test/resources/policyLogger.properties +++ /dev/null @@ -1,45 +0,0 @@ -### -# ============LICENSE_START======================================================= -# Integrity Audit -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer -# gets executed to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to -# disable all -debugLogger.level=DEBUG -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/integrity-audit/src/test/resources/xlogger-test.expectedlog b/integrity-audit/src/test/resources/xlogger-test.expectedlog deleted file mode 100644 index a9ad4992..00000000 --- a/integrity-audit/src/test/resources/xlogger-test.expectedlog +++ /dev/null @@ -1 +0,0 @@ -2019-12-05T13:24:14.110Z|TheRequestId|TheServiceInstanceId|main|TheServerName|TheServiceName|TheInstanceUuid|INFO|TheSeverity|TheServerIpAddress|TheServer|TheClientIpAddress|org.onap.policy.common.ia.DefaultLoggingPatternTest||This is a test logging string for xlogger |