diff options
26 files changed, 3105 insertions, 3544 deletions
diff --git a/integrity-audit/pom.xml b/integrity-audit/pom.xml index d261340f..413ee1dd 100644 --- a/integrity-audit/pom.xml +++ b/integrity-audit/pom.xml @@ -2,7 +2,7 @@ ============LICENSE_START======================================================= ONAP Policy Engine - Common Modules ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + 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. @@ -49,6 +49,12 @@ </dependency> <dependency> <groupId>org.onap.policy.common</groupId> + <artifactId>utils</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> <artifactId>utils-test</artifactId> <version>${project.version}</version> <scope>test</scope> 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 index 78ff4d3a..7af82132 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -25,6 +25,9 @@ import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Properties; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -59,9 +62,15 @@ public class AuditThread extends Thread { /* * 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. + * we sleep integrityAuditPeriodMillis. May be modified by JUnit tests. */ - private static final long AUDIT_THREAD_SLEEP_INTERVAL = 5000; + private static long auditThreadSleepIntervalMillis = 5000; + + /* + * Number of milliseconds that must elapse for audit to be considered + * complete. May be modified by JUnit tests. + */ + private static long auditCompletionIntervalMillis = AUDIT_COMPLETION_INTERVAL; /* * DB access class. @@ -91,7 +100,7 @@ public class AuditThread extends Thread { /* * See IntegrityAudit class for usage. */ - private int integrityAuditPeriodMillis; + private long integrityAuditPeriodMillis; /* * The containing IntegrityAudit instance @@ -99,6 +108,18 @@ public class AuditThread extends Thread { private IntegrityAudit integrityAudit; /** + * A latch is taken from this queue before starting an audit. May be + * {@code null}. Used by JUnit tests. + */ + private BlockingQueue<CountDownLatch> auditLatchQueue; + + /** + * Latch to be decremented when the next audit completes. May be + * {@code null}. Used by JUnit tests to wait for an audit to complete. + */ + private CountDownLatch auditCompletionLatch = null; + + /** * AuditThread constructor * @param resourceName * @param persistenceUnit @@ -110,11 +131,31 @@ public class AuditThread extends Thread { public AuditThread(String resourceName, String persistenceUnit, Properties properties, int integrityAuditPeriodSeconds, IntegrityAudit integrityAudit) throws Exception { + + this(resourceName, persistenceUnit, properties, TimeUnit.SECONDS.toMillis(integrityAuditPeriodSeconds), + integrityAudit, null); + } + + /** + * AuditThread constructor + * @param resourceName + * @param persistenceUnit + * @param properties + * @param integrityAuditMillis + * @param integrityAudit + * @param queue + * @throws Exception + */ + public AuditThread(String resourceName, String persistenceUnit, + Properties properties, long integrityAuditMillis, IntegrityAudit integrityAudit, + BlockingQueue<CountDownLatch> queue) + throws Exception { this.resourceName = resourceName; this.persistenceUnit = persistenceUnit; this.properties = properties; - this.integrityAuditPeriodMillis = integrityAuditPeriodSeconds * 1000; + this.integrityAuditPeriodMillis = integrityAuditMillis; this.integrityAudit = integrityAudit; + this.auditLatchQueue = queue; /* * The DbDAO Constructor registers this node in the IntegrityAuditEntity @@ -135,7 +176,16 @@ public class AuditThread extends Thread { logger.info("AuditThread.run: Entering"); - try { + try { + /* + * For JUnit testing: wait for the first latch, decrement it to + * indicate that the thread has started, and then wait for the + * next latch, before we actually start doing anything. These + * simply return if there is no latch queue defined. + */ + getNextLatch(); + decrementLatch(); + getNextLatch(); /* * Triggers change in designation, unless no other viable candidate. @@ -151,7 +201,6 @@ public class AuditThread extends Thread { while (true) { try{ - /* * It may have been awhile since we last cycled through this * loop, so refresh the list of IntegrityAuditEntities. @@ -249,6 +298,11 @@ public class AuditThread extends Thread { * the normal interval. */ if (auditCompleted) { + // indicate that an audit has completed + decrementLatch(); + + // don't start the next audit cycle until a latch has been provided + getNextLatch(); if (logger.isDebugEnabled()) { logger.debug("AuditThread.run: Audit completed; resourceName=" @@ -268,25 +322,32 @@ public class AuditThread extends Thread { if (logger.isDebugEnabled()) { logger.debug("AuditThread.run: resourceName=" + this.resourceName + ": Sleeping " - + AuditThread.AUDIT_THREAD_SLEEP_INTERVAL + + AuditThread.auditThreadSleepIntervalMillis + "ms"); } - Thread.sleep(AuditThread.AUDIT_THREAD_SLEEP_INTERVAL); + Thread.sleep(AuditThread.auditThreadSleepIntervalMillis); if (logger.isDebugEnabled()) { logger.debug("AuditThread.run: resourceName=" + this.resourceName + ": Awaking from " - + AuditThread.AUDIT_THREAD_SLEEP_INTERVAL + + AuditThread.auditThreadSleepIntervalMillis + "ms sleep"); } } + } catch (Exception e){ + if(isInterruptedException(e)) { + String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + + "; Stopping."; + logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); + break; + } + String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + "; Will try audit again in " + (integrityAuditPeriodMillis/1000) + " seconds"; logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); // Sleep and try again later Thread.sleep(integrityAuditPeriodMillis); - continue; } } @@ -296,10 +357,53 @@ public class AuditThread extends Thread { logger.error(MessageCodes.EXCEPTION_ERROR, e, msg); integrityAudit.setThreadInitialized(false); } + + dbDAO.destroy(); logger.info("AuditThread.run: Exiting"); } + /** + * Gets the next audit-completion latch from the queue. Blocks, if the + * queue is empty. + * @throws InterruptedException + */ + private void getNextLatch() throws InterruptedException { + BlockingQueue<CountDownLatch> queue = this.auditLatchQueue; + if(queue != null) { + this.auditCompletionLatch = queue.take(); + } + } + + /** + * Decrements the current audit-completion latch, if any. + */ + private void decrementLatch() { + CountDownLatch latch = this.auditCompletionLatch; + if(latch != null) { + this.auditCompletionLatch = null; + latch.countDown(); + } + } + + /** + * 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; + } + /* * Used to create a list that is sorted lexicographically by resourceName. */ @@ -617,7 +721,7 @@ public class AuditThread extends Thread { /** * Returns false if the lastUpdated time for the record in question is more - * than AUDIT_COMPLETION_INTERVAL seconds ago. During an audit, lastUpdated is updated every five + * 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 @@ -647,7 +751,7 @@ public class AuditThread extends Thread { lastUpdatedTime = lastUpdated.getTime(); } long timeDifference = currentTime.getTime() - lastUpdatedTime; - if (timeDifference > AUDIT_COMPLETION_INTERVAL) { + if (timeDifference > auditCompletionIntervalMillis) { stale = true; } @@ -678,7 +782,7 @@ public class AuditThread extends Thread { } /* - * If more than (AUDIT_COMPLETION_INTERVAL * 2) milliseconds have elapsed + * 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 @@ -707,7 +811,7 @@ public class AuditThread extends Thread { long lastUpdatedTime = lastUpdated.getTime(); timeDifference = currentTime.getTime() - lastUpdatedTime; - if (timeDifference > (AUDIT_COMPLETION_INTERVAL * 2)) { + if (timeDifference > (auditCompletionIntervalMillis * 2)) { if (logger.isDebugEnabled()) { logger.debug("resetAuditCompleted: Resetting auditCompleted for resourceName=" + this.resourceName); @@ -750,7 +854,7 @@ public class AuditThread extends Thread { + this.resourceName); } if (IntegrityAudit.isUnitTesting()) { - dbAudit.dbAuditSimulate(this.resourceName, this.persistenceUnit); + dbAudit.dbAuditSimulate(this.resourceName, this.persistenceUnit, AuditThread.AUDIT_SIMULATION_ITERATIONS, AuditThread.auditThreadSleepIntervalMillis); } else { dbAudit.dbAudit(this.resourceName, this.persistenceUnit, this.nodeType); @@ -762,4 +866,38 @@ public class AuditThread extends Thread { } + /** + * Adjusts the thread-sleep-interval to be used when an audit has + * <i>not</i> been completed. Used by JUnit tests. + * @param auditThreadSleepIntervalMillis + */ + protected static void setAuditThreadSleepIntervalMillis(long auditThreadSleepIntervalMillis) { + AuditThread.auditThreadSleepIntervalMillis = auditThreadSleepIntervalMillis; + } + + /** + * Gets the current thread-sleep-interval to be used when an audit has + * <i>not</i> been completed. Used by JUnit tests. + * @return the current sleep interval, in milli-seconds + */ + protected static long getAuditThreadSleepIntervalMillis() { + return auditThreadSleepIntervalMillis; + } + + /** + * Adjusts the audit-completion-interval. Used by JUnit tests. + * @param auditThreadSleepIntervalMillis + */ + protected static void setAuditCompletionIntervalMillis(long auditThreadSleepIntervalMillis) { + AuditThread.auditCompletionIntervalMillis = auditThreadSleepIntervalMillis; + } + + /** + * Gets the audit-completion-interval. Used by JUnit tests. + * @return the current audit-completion interval, in milli-seconds + */ + protected static long getAuditCompletionIntervalMillis() { + return auditCompletionIntervalMillis; + } + } 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 index 21bf5c8d..00b79917 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -53,6 +53,9 @@ public class DbAudit { private static final Logger logger = FlexLogger.getLogger(DbAudit.class); + private static long dbAuditUpdateMillis = 5000l; + private static long dbAuditSleepMillis = 2000l; + DbDAO dbDAO = null; public DbAudit(DbDAO dbDAO) { @@ -212,7 +215,7 @@ public class DbAudit { } } //end for (IntegrityAuditEntity iae : iaeList) //Time check - if((System.currentTimeMillis() - startTime) >= 5000){ //5 seconds + if((System.currentTimeMillis() - startTime) >= dbAuditUpdateMillis){ //update the timestamp dbDAO.setLastUpdated(); //reset the startTime @@ -220,9 +223,9 @@ public class DbAudit { }else{ //sleep a couple seconds to break up the activity if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Sleeping 2 seconds"); + logger.debug("dbAudit: Sleeping " + dbAuditSleepMillis + "ms"); } - Thread.sleep(2000); + Thread.sleep(dbAuditSleepMillis); if (logger.isDebugEnabled()) { logger.debug("dbAudit: Waking from sleep"); } @@ -315,7 +318,7 @@ public class DbAudit { } } //Time check - if((System.currentTimeMillis() - startTime) >= 5000){ //5 seconds + if((System.currentTimeMillis() - startTime) >= dbAuditUpdateMillis){ //update the timestamp dbDAO.setLastUpdated(); //reset the startTime @@ -323,9 +326,9 @@ public class DbAudit { }else{ //sleep a couple seconds to break up the activity if (logger.isDebugEnabled()) { - logger.debug("dbAudit: Second comparison; sleeping 2 seconds"); + logger.debug("dbAudit: Second comparison; sleeping " + dbAuditSleepMillis + "ms"); } - Thread.sleep(2000); + Thread.sleep(dbAuditSleepMillis); if (logger.isDebugEnabled()) { logger.debug("dbAudit: Second comparison; waking from sleep"); } @@ -347,22 +350,23 @@ public class DbAudit { /** * dbAuditSimulate simulates the DB audit * @param resourceName - * @param persistenceUnit + * @param persistenceUnit + * @param simulationIterations + * @param simulationIntervalMs * @param nodeType - * @throws InterruptedException - * @throws DbDaoTransactionException + * @throws DbAuditException */ - public void dbAuditSimulate(String resourceName, String persistenceUnit) throws DbAuditException { + public void dbAuditSimulate(String resourceName, String persistenceUnit, long simulationIterations, long simulationIntervalMs) throws DbAuditException { try { logger.info("dbAuditSimulate: Starting audit simulation for resourceName=" + resourceName + ", persistenceUnit=" + persistenceUnit); - for (int i = 0; i < AuditThread.AUDIT_SIMULATION_ITERATIONS; i++) { + for (int i = 0; i < simulationIterations; i++) { dbDAO.setLastUpdated(); logger.info("dbAuditSimulate: i=" + i + ", sleeping " - + AuditThread.AUDIT_SIMULATION_SLEEP_INTERVAL + "ms"); - Thread.sleep(AuditThread.AUDIT_SIMULATION_SLEEP_INTERVAL); + + simulationIntervalMs + "ms"); + Thread.sleep(simulationIntervalMs); } logger.info("dbAuditSimulate: Finished audit simulation for resourceName=" @@ -465,8 +469,36 @@ public class DbAudit { logger.info(msg); } + /** + * Gets the audit-update time. + * @return the audit-update time, in milliseconds + */ + protected static long getDbAuditUpdateMillis() { + return dbAuditUpdateMillis; + } + + /** + * Sets the audit-update time. + * @param dbAuditUpdateMillis the new audit update time, in milliseconds + */ + protected static void setDbAuditUpdateMillis(long dbAuditUpdateMillis) { + DbAudit.dbAuditUpdateMillis = dbAuditUpdateMillis; + } + /** + * Gets the audit-sleep time. + * @return the audit-sleep time, in milliseconds + */ + protected static long getDbAuditSleepMillis() { + return dbAuditSleepMillis; + } - + /** + * Sets the audit-sleep time. + * @param dbAuditSleepMillis the new audit sleep time, in milliseconds + */ + protected static void setDbAuditSleepMillis(long dbAuditSleepMillis) { + DbAudit.dbAuditSleepMillis = dbAuditSleepMillis; + } } 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 index b30c7730..f34b24d5 100644 --- 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 @@ -69,27 +69,49 @@ public class DbDAO { */ private static final Object lock = new Object(); - /** * DbDAO Constructor - * @param resourceName - * @param persistenceUnit - * @param properties - * @throws Exception - */ + * + * @param resourceName + * @param persistenceUnit + * @param properties + * @throws Exception + */ public DbDAO(String resourceName, String persistenceUnit, Properties properties) throws Exception { + this(resourceName, persistenceUnit, properties, null); + } + + /** + * DbDAO Constructor + * + * @param resourceName + * @param persistenceUnit + * @param properties + * @param lastUpdateDate may be {@code null} + * @param altDbUrl may be {@code null} + * @throws Exception + */ + protected DbDAO(String resourceName, String persistenceUnit, Properties properties, String altDbUrl) + throws Exception { logger.debug("DbDAO contructor: enter"); - + validateProperties(resourceName, persistenceUnit, properties); - + emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - register(); - + + 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 * @param persistenceUnit @@ -207,6 +229,7 @@ public class DbDAO { logger.error("getAllEntries encountered exception:", e); } em.close(); + theEmf.close(); logger.debug("getAllEntries: Returning resultMap, size=" + resultMap.size()); @@ -240,6 +263,7 @@ public class DbDAO { logger.error(msg, e); } em.close(); + theEmf.close(); logger.debug("getAllEntries: Exit, resultMap, size=" + resultMap.size()); return resultMap; } @@ -282,7 +306,7 @@ public class DbDAO { } } - + /** * getMyIntegrityAuditEntity() gets my IntegrityAuditEntity * @return @@ -382,8 +406,10 @@ public class DbDAO { /** * 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() throws DbDaoTransactionException { + private void register(String altDbUrl) throws DbDaoTransactionException { try{ EntityManager em = emf.createEntityManager(); @@ -421,10 +447,9 @@ public class DbDAO { //update/set properties in entry iae.setSite(this.siteName); iae.setNodeType(this.nodeType); - iae.setLastUpdated(new Date()); iae.setJdbcDriver(this.dbDriver); iae.setJdbcPassword(properties.getProperty(IntegrityAuditProperties.DB_PWD).trim()); - iae.setJdbcUrl(dbUrl); + iae.setJdbcUrl(altDbUrl == null ? this.dbUrl : altDbUrl); iae.setJdbcUser(dbUser); em.persist(iae); 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 index 4f7a15af..f1dbfec0 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -21,10 +21,11 @@ package org.onap.policy.common.ia; import java.util.Properties; - +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; import org.onap.policy.common.ia.IntegrityAuditProperties.NodeTypeEnum; -import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; /** @@ -46,16 +47,16 @@ public class IntegrityAudit { /* - * This is the audit period in seconds. For example, if it had a value of 3600, the audit - * can only run once per hour. If it has a value of 60, it can run once per minute. + * 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 - * integrityAuditPeriodSecconds == 0 indicates the audit is to run continuously - * integrityAuditPeriodSeconds > 0 indicates the audit is to run at most once during the indicated period + * integrityAuditPeriodMillis < 0 (negative number) indicates the audit is off + * integrityAuditPeriodMillis == 0 indicates the audit is to run continuously + * integrityAuditPeriodMillis > 0 indicates the audit is to run at most once during the indicated period * */ - private int integrityAuditPeriodSeconds; + private int integrityAuditPeriodMillis; /** * IntegrityAudit constructor @@ -84,10 +85,12 @@ public class IntegrityAudit { this.resourceName = resourceName; if(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS) != null){ //It is allowed to be null - this.integrityAuditPeriodSeconds= Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim()); + this.integrityAuditPeriodMillis= 1000 * Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim()); + } else if(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS) != null){ //It is allowed to be null + this.integrityAuditPeriodMillis= Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS).trim()); } else{ //If it is null, set it to the default value - this.integrityAuditPeriodSeconds = IntegrityAuditProperties.DEFAULT_AUDIT_PERIOD_SECONDS; + this.integrityAuditPeriodMillis = 1000 * IntegrityAuditProperties.DEFAULT_AUDIT_PERIOD_SECONDS; } logger.info("Constructor: Exiting"); @@ -97,7 +100,7 @@ public class IntegrityAudit { * Used during JUnit testing by AuditPeriodTest.java */ public int getIntegrityAuditPeriodSeconds() { - return integrityAuditPeriodSeconds; + return (integrityAuditPeriodMillis / 1000); } /** @@ -190,6 +193,15 @@ public class IntegrityAudit { parmsAreBad = true; } } + else if(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS) != null){ //It is allowed to be null + try{ + Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS).trim()); + }catch(NumberFormatException nfe){ + badparams.append(", auditPeriodMilliSeconds=" + + properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS).trim()); + parmsAreBad = true; + } + } } // End else logger.debug("parmsAreBad: exit:" + "\nresourceName: " + resourceName @@ -203,22 +215,36 @@ public class IntegrityAudit { * @throws Exception */ public void startAuditThread() throws Exception { + startAuditThread(null); + } + /** + * Starts the audit thread + * @param queue + * @return {@code true} if the thread was started, {@code false} otherwise + * @throws Exception + */ + protected boolean startAuditThread(BlockingQueue<CountDownLatch> queue) throws Exception { logger.info("startAuditThread: Entering"); - if (integrityAuditPeriodSeconds >= 0) { + boolean success = false; + + if (integrityAuditPeriodMillis >= 0) { this.auditThread = new AuditThread(this.resourceName, this.persistenceUnit, this.properties, - integrityAuditPeriodSeconds, this); + integrityAuditPeriodMillis, this, queue); logger.info("startAuditThread: Audit started and will run every " - + integrityAuditPeriodSeconds + " seconds"); + + integrityAuditPeriodMillis/1000 + " seconds"); this.auditThread.start(); + success = true; } else { logger.info("startAuditThread: Suppressing integrity audit, integrityAuditPeriodSeconds=" - + integrityAuditPeriodSeconds); + + integrityAuditPeriodMillis/1000); } logger.info("startAuditThread: Exiting"); + + return success; } /** * Stops the audit thread @@ -252,4 +278,23 @@ public class IntegrityAudit { public static void setUnitTesting(boolean isUnitTesting) { IntegrityAudit.isUnitTesting = isUnitTesting; } + + /** + * 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 + */ + protected boolean joinAuditThread(long twaitms) throws InterruptedException { + if(this.auditThread == null) { + return true; + + } else { + this.auditThread.join(twaitms); + return ! this.auditThread.isAlive(); + } + } } 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 index 49b26fcb..b8db3ac2 100644 --- 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -29,6 +29,7 @@ public class IntegrityAuditProperties { public static final String DB_USER = "javax.persistence.jdbc.user"; public static final String DB_PWD = "javax.persistence.jdbc.password"; public static final String AUDIT_PERIOD_SECONDS = "integrity_audit_period_seconds"; + public static final String AUDIT_PERIOD_MILLISECONDS = "integrity_audit_period_milliseconds"; public static final String SITE_NAME = "site_name"; 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 index fb8823f5..da69f2de 100644 --- 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 @@ -1,8 +1,8 @@ -/*- +/* * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -20,6 +20,8 @@ package org.onap.policy.common.ia.jpa; +import java.io.IOException; +import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; @@ -105,9 +107,7 @@ public class IntegrityAuditEntity implements Serializable { @PreUpdate public void preUpdate() { - if (!isUnitTesting()) { - this.lastUpdated = new Date(); - } + this.lastUpdated = new Date(); } public long getId() { @@ -209,4 +209,17 @@ public class IntegrityAuditEntity implements Serializable { public static void setUnitTesting(boolean isUnitTesting) { IntegrityAuditEntity.isUnitTesting = isUnitTesting; } + + 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 index 9e4880fa..2f435618 100644 --- a/integrity-audit/src/main/resources/META-INF/persistence.xml +++ b/integrity-audit/src/main/resources/META-INF/persistence.xml @@ -24,13 +24,10 @@ <!-- Limited use for generating the DB and schema files for iatest DB - uses eclipselink --> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <class>org.onap.policy.common.ia.jpa.IntegrityAuditEntity</class> - <class>org.onap.policy.common.ia.test.jpa.IaTestEntity</class> + <class>org.onap.policy.common.ia.jpa.IaTestEntity</class> <shared-cache-mode>NONE</shared-cache-mode> <properties> <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/> - <property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/> - <property name="javax.persistence.schema-generation.scripts.create-target" value="./sql/generatedCreateIA.ddl"/> - <property name="javax.persistence.schema-generation.scripts.drop-target" value="./sql/generatedDropIA.ddl"/> </properties> </persistence-unit> 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 new file mode 100644 index 00000000..b627977b --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java @@ -0,0 +1,260 @@ +/*- + * ============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; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.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. + */ +public class AuditPeriodTest extends IntegrityAuditTestBase { + + private static Logger logger = FlexLogger.getLogger(AuditPeriodTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + AuditPeriodTest.class.getSimpleName()); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } + + @Before + public void setUp() { + logger.info("setUp: Entering"); + + super.setUp(); + + logger.info("setUp: Exiting"); + + } + + @After + 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 + public 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 + public void testZeroAuditPeriod() throws Exception { + + logger.info("testZeroAuditPeriod: Entering"); + + properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "0"); + + ExtractAppender logA = watch(debugLogger, "[Aa]waking from (0ms) 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] = "0ms"; + 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 + public 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 periodms + * audit period, in milliseconds + * @throws Exception + * @throws InterruptedException + */ + private void testAuditPeriod(long periodms) throws Exception, InterruptedException { + + properties.put(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS, String.valueOf(periodms)); + + /* + * 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 >= periodms + AUDIT_SIMULATION_MS); + + /* + * Now run again and ensure it waited long enough between runs. + */ + tmin = minAuditTime(ia); + assertTrue(tmin >= periodms + AUDIT_SIMULATION_MS); + } + + /** + * Runs simultaneous audits on several auditors. + * + * @param auditors + * @return the minimum time, in milliseconds, elapsed for any given auditor + * @throws InterruptedException + */ + private long minAuditTime(MyIntegrityAudit... auditors) throws InterruptedException { + List<Thread> threads = new ArrayList<>(auditors.length); + AtomicLong tfirst = new AtomicLong(Long.MAX_VALUE); + long tbeg = System.currentTimeMillis(); + + // create the threads + for (MyIntegrityAudit p : auditors) { + Thread t = new Thread() { + + @Override + public void run() { + try { + runAudit(p); + setMinTime(tfirst); + + } catch (InterruptedException e) { + ; + } + } + }; + + t.setDaemon(true); + threads.add(t); + } + + // start the threads + for (Thread t : threads) { + t.start(); + } + + // wait for them to complete + for (Thread t : threads) { + t.join(); + } + + return (tfirst.get() - tbeg); + } + + /** + * Sets a value to the minimum between the current value and the current + * time. + * + * @param tmin + * current minimum value/value to be set + */ + private static void setMinTime(AtomicLong tmin) { + long tcur = System.currentTimeMillis(); + long t; + while ((t = tmin.get()) > tcur) { + tmin.compareAndSet(t, tcur); + } + } +} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditCompareEntriesTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java index 76f54019..3a48b20c 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditCompareEntriesTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -18,11 +18,12 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.ia.test; +package org.onap.policy.common.ia; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; -import java.io.FileOutputStream; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -30,22 +31,15 @@ import java.util.Map; import java.util.Properties; import java.util.Set; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; - import org.junit.After; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; -import org.onap.policy.common.ia.DbAudit; -import org.onap.policy.common.ia.DbDAO; -import org.onap.policy.common.ia.IntegrityAudit; -import org.onap.policy.common.ia.IntegrityAuditProperties; +import org.onap.policy.common.ia.jpa.IaTestEntity; import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -import org.onap.policy.common.ia.test.jpa.IaTestEntity; -import org.onap.policy.common.ia.test.jpa.PersonSample; +import org.onap.policy.common.ia.jpa.PersonSample; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -53,53 +47,34 @@ 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. - * - * If any have been ignored (@Ignore) they will not run at the same time - * as others. You should run them as JUnits by themselves. */ -public class DbAuditCompareEntriesTest { +public class DbAuditCompareEntriesTest extends IntegrityAuditTestBase { private static Logger logger = FlexLogger.getLogger(DbAuditCompareEntriesTest.class); + private DbDAO dbDAO; - private static String persistenceUnit; - private static Properties properties; - private static String resourceName; - private String dbDriver; - private String dbUrl; - private String dbUser; - private String dbPwd; - private String siteName; - private String nodeType; - private static final String TEST_LOG = "./testingLogs/common-modules/integrity-audit/debug.log"; - + private static String resourceName = "pdp1"; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase + .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditCompareEntriesTest.class.getSimpleName()); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } + @Before - public void setUp() throws Exception { - System.out.println("setUp: Clearing IntegrityAudit.log"); - //FileOutputStream fstream = new FileOutputStream("IntegrityAudit.log"); - FileOutputStream fstream = new FileOutputStream(TEST_LOG); - fstream.close(); + public void setUp() { logger.info("setUp: Entering"); - IntegrityAudit.setUnitTesting(true); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - dbDriver = TestUtils.DEFAULT_DB_DRIVER; - dbUrl = TestUtils.DEFAULT_DB_URL; - dbUser = TestUtils.DEFAULT_DB_USER; - dbPwd = TestUtils.DEFAULT_DB_PWD; - siteName = "SiteA"; - nodeType = "pdp_xacml"; - persistenceUnit = "testPU"; - resourceName = "pdp1"; - + super.setUp(); + + truncateTables(makeProperties()); + logger.info("setUp: Exiting"); } @@ -107,39 +82,44 @@ public class DbAuditCompareEntriesTest { * Clean up DB after each test. */ @After - public void tearDown() throws Exception { + 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 + * Tests that a comparison between hashsets is successful if the entries + * match */ - //@Ignore + // @Ignore @Test public void testSuccessfulComparison() throws Exception { logger.info("testSuccessfulComparison: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + + dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); DbAudit dbAudit = new DbAudit(dbDAO); - + String className = null; - //There is only one entry IntegrityAuditEntity, but we will check anyway + // There is only one entry IntegrityAuditEntity, but we will check + // anyway Set<String> classNameSet = dbDAO.getPersistenceClassNames(); - for(String c : classNameSet){ - if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){ + for (String c : classNameSet) { + if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { className = c; } } String resourceName1 = resourceName; String resourceName2 = resourceName; - + IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); Date date = new Date(); - + /* * Two entries with the same field values */ @@ -150,10 +130,10 @@ public class DbAuditCompareEntriesTest { entry1.setJdbcUser(dbUser); entry1.setLastUpdated(date); entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); + entry1.setPersistenceUnit(A_SEQ_PU); entry1.setResourceName(resourceName1); entry1.setSite(siteName); - + entry2.setDesignated(false); entry2.setJdbcDriver(dbDriver); entry2.setJdbcPassword(dbPwd); @@ -161,47 +141,47 @@ public class DbAuditCompareEntriesTest { entry2.setJdbcUser(dbUser); entry2.setLastUpdated(date); entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); + entry2.setPersistenceUnit(A_SEQ_PU); entry2.setResourceName(resourceName2); entry2.setSite(siteName); - + dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); - + HashMap<Object, Object> myEntries = new HashMap<Object, Object>(); HashMap<Object, Object> theirEntries = new HashMap<Object, Object>(); - + 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 + * Tests that an error is detected if an entry in one hashset doesn't match + * the other */ - //@Ignore + // @Ignore @Test public void testComparisonError() throws Exception { logger.info("testComparisonError: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + + dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); DbAudit dbAudit = new DbAudit(dbDAO); - + String resourceName1 = resourceName; String resourceName2 = resourceName; - + IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); Date date = new Date(); - + /* * Create two entries with different designated values */ @@ -212,10 +192,10 @@ public class DbAuditCompareEntriesTest { entry1.setJdbcUser(dbUser); entry1.setLastUpdated(date); entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); + entry1.setPersistenceUnit(A_SEQ_PU); entry1.setResourceName(resourceName1); entry1.setSite(siteName); - + entry2.setDesignated(true); entry2.setJdbcDriver(dbDriver); entry2.setJdbcPassword(dbPwd); @@ -223,48 +203,48 @@ public class DbAuditCompareEntriesTest { entry2.setJdbcUser(dbUser); entry2.setLastUpdated(date); entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); + entry2.setPersistenceUnit(A_SEQ_PU); entry2.setResourceName(resourceName2); entry2.setSite(siteName); - + HashMap<Object, Object> myEntries = new HashMap<Object, Object>(); HashMap<Object, Object> theirEntries = new HashMap<Object, Object>(); - + 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 + * Tests that a mismatch/miss entry is detected if there are missing entries + * in one or both of the hashsets */ - //@Ignore + // @Ignore @Test public void testCompareMissingEntries() throws Exception { logger.info("testCompareMissingEntries: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + + dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); DbAudit dbAudit = new DbAudit(dbDAO); - + String resourceName1 = resourceName; String resourceName2 = resourceName; - + IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); IntegrityAuditEntity entry3 = new IntegrityAuditEntity(); IntegrityAuditEntity entry4 = new IntegrityAuditEntity(); - + Date date = new Date(); - + /* * 4 entries, one mismatch, two miss entries */ @@ -275,10 +255,10 @@ public class DbAuditCompareEntriesTest { entry1.setJdbcUser(dbUser); entry1.setLastUpdated(date); entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); + entry1.setPersistenceUnit(A_SEQ_PU); entry1.setResourceName(resourceName1); entry1.setSite(siteName); - + entry2.setDesignated(true); entry2.setJdbcDriver(dbDriver); entry2.setJdbcPassword(dbPwd); @@ -286,10 +266,10 @@ public class DbAuditCompareEntriesTest { entry2.setJdbcUser(dbUser); entry2.setLastUpdated(date); entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); + entry2.setPersistenceUnit(A_SEQ_PU); entry2.setResourceName(resourceName2); entry2.setSite(siteName); - + entry3.setDesignated(false); entry3.setJdbcDriver(dbDriver); entry3.setJdbcPassword(dbPwd); @@ -297,10 +277,10 @@ public class DbAuditCompareEntriesTest { entry3.setJdbcUser(dbUser); entry3.setLastUpdated(date); entry3.setNodeType(nodeType); - entry3.setPersistenceUnit(persistenceUnit); + entry3.setPersistenceUnit(A_SEQ_PU); entry3.setResourceName(resourceName2); entry3.setSite("SiteB"); - + entry4.setDesignated(false); entry4.setJdbcDriver(dbDriver); entry4.setJdbcPassword(dbPwd); @@ -308,50 +288,50 @@ public class DbAuditCompareEntriesTest { entry4.setJdbcUser(dbUser); entry4.setLastUpdated(date); entry4.setNodeType(nodeType); - entry4.setPersistenceUnit(persistenceUnit); + entry4.setPersistenceUnit(A_SEQ_PU); entry4.setResourceName(resourceName2); entry4.setSite("SiteB"); HashMap<Object, Object> myEntries = new HashMap<Object, Object>(); HashMap<Object, Object> theirEntries = new HashMap<Object, Object>(); - + 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 + * Tests that comparison algorithm works for each entity in the hashsets */ - //@Ignore + // @Ignore @Test public void testCompareAllHashEntities() throws Exception { logger.info("testCompareAllHashEntities: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + + dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); DbAudit dbAudit = new DbAudit(dbDAO); - + Set<String> classNameSet = dbDAO.getPersistenceClassNames(); Set<Object> mismatchResult = new HashSet<Object>(); - for(String c : classNameSet) { - if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){ + for (String c : classNameSet) { + if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { String resourceName1 = resourceName; String resourceName2 = resourceName; - + IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); Date date = new Date(); - + /* * Two entries with the same field values */ @@ -362,10 +342,10 @@ public class DbAuditCompareEntriesTest { entry1.setJdbcUser(dbUser); entry1.setLastUpdated(date); entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); + entry1.setPersistenceUnit(A_SEQ_PU); entry1.setResourceName(resourceName1); entry1.setSite(siteName); - + entry2.setDesignated(false); entry2.setJdbcDriver(dbDriver); entry2.setJdbcPassword(dbPwd); @@ -373,72 +353,71 @@ public class DbAuditCompareEntriesTest { entry2.setJdbcUser(dbUser); entry2.setLastUpdated(date); entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); + entry2.setPersistenceUnit(A_SEQ_PU); entry2.setResourceName(resourceName2); entry2.setSite(siteName); - + HashMap<Object, Object> myEntries = new HashMap<Object, Object>(); HashMap<Object, Object> theirEntries = new HashMap<Object, Object>(); - + myEntries.put("pdp1", entry1); theirEntries.put("pdp1", entry2); - + mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - + /* * Assert there was no mismatches */ assertTrue(mismatchResult.isEmpty()); - } - else if (c.equals("org.onap.policy.common.ia.test.jpa.IaTestEntity")) { + } else if (c.equals("org.onap.policy.common.ia.jpa.IaTestEntity")) { IaTestEntity iate = new IaTestEntity(); IaTestEntity iate2 = new IaTestEntity(); IaTestEntity iate3 = new IaTestEntity(); 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<Object, Object>(); HashMap<Object, Object> theirEntries = new HashMap<Object, Object>(); - + myEntries.put("0", iate); myEntries.put("1", iate2); theirEntries.put("0", iate3); theirEntries.put("1", iate4); - + mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - + /* * Assert that there is 2 mismatches */ assertEquals(2, mismatchResult.size()); } } - + logger.info("testCompareAllHashEntities: Exit"); } - + /* - * Tests that comparison algorithm works for each entity in the database + * Tests that comparison algorithm works for each entity in the database */ @Ignore @Test @@ -448,147 +427,92 @@ public class DbAuditCompareEntriesTest { logger.info("Setting up DB"); IntegrityAudit.setUnitTesting(true); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/iaTest2"); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - dbDriver = TestUtils.DEFAULT_DB_DRIVER; - dbUrl = TestUtils.DEFAULT_DB_URL; - dbUser = TestUtils.DEFAULT_DB_USER; - dbPwd = TestUtils.DEFAULT_DB_PWD; - siteName = "SiteA"; - nodeType = "pdp_xacml"; - persistenceUnit = "testPU"; - resourceName = "pdp1"; - - //Clean up the two DBs - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManagerFactory emf2 = Persistence.createEntityManagerFactory(persistenceUnit, properties2); - - EntityManager em = emf.createEntityManager(); - EntityManager em2 = emf2.createEntityManager(); - // Start a transaction - EntityTransaction et = em.getTransaction(); - EntityTransaction et2 = em2.getTransaction(); - - /* - * Delete entries in first DB - */ - et.begin(); - - // Clean the IntegrityAuditEntity table - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - - et.begin(); - - // Clean the IaTestEntity table - em.createQuery("Delete from IaTestEntity").executeUpdate(); - - // commit transaction - et.commit(); - em.close(); - - /* - * Delete entries in second DB - */ - et2.begin(); - // Clean the IntegrityAuditEntity table - em2.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); + Properties properties = makeProperties(); - // commit transaction - et2.commit(); - - et2.begin(); + Properties properties2 = makeProperties(); + properties2.put(IntegrityAuditProperties.DB_URL, + "jdbc:h2:mem:" + DbAuditCompareEntriesTest.class.getSimpleName() + "2"); - // Clean the IaTestEntity table - em2.createQuery("Delete from IaTestEntity").executeUpdate(); + // Clean up the two DBs + truncateTables(properties); + truncateTables(properties2); - // commit transaction - et2.commit(); - em2.close(); - logger.info("Exiting set up"); - // Add entries into DB1 - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - new DbDAO("pdp2", persistenceUnit, properties); + 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, persistenceUnit, properties2); - new DbDAO("pdp2", persistenceUnit, properties2); - + 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<Object>(); String className; - for(String c : classNameSet) { + for (String c : classNameSet) { className = c; logger.info("classNameSet entry = " + c); - myEntries = dbDAO.getAllEntries(persistenceUnit, properties, className); - theirEntries = dbDAO3.getAllEntries(persistenceUnit, properties2, 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")){ + if (className.contains("IntegrityAuditEntity")) { break; } } + dbDAO3.destroy(); + // Assert that there is 2 mismatches between IntegrityAuditEntity tables assertEquals(2, mismatchResult.size()); - + logger.info("testCompareAllDbEntities: Exit"); } - + + /** + * @param 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 + * Tests that differences in embedded classes are still caught */ - //@Ignore + // @Ignore @Test public void testEmbeddedClass() throws Exception { logger.info("testEmbeddedClasses: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + + dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); DbAudit dbAudit = new DbAudit(dbDAO); - + String className = null; - //There is only one entry IntegrityAuditEntity, but we will check anyway + // There is only one entry IntegrityAuditEntity, but we will check + // anyway Set<String> classNameSet = dbDAO.getPersistenceClassNames(); - for(String c : classNameSet){ - if (c.equals("org.onap.policy.common.ia.test.jpa.IaTestEntity")){ + for (String c : classNameSet) { + if (c.equals("org.onap.policy.common.ia.jpa.IaTestEntity")) { className = c; } } - + IaTestEntity iate = new IaTestEntity(); IaTestEntity iate2 = new IaTestEntity(); - + 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. + * 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()); @@ -604,27 +528,27 @@ public class DbAuditCompareEntriesTest { 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<Object, Object>(); HashMap<Object, Object> theirEntries = new HashMap<Object, Object>(); - + 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 new file mode 100644 index 00000000..ad4041f5 --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java @@ -0,0 +1,282 @@ +/*- + * ============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; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +import java.util.List; +import java.util.Properties; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.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. + */ +public class DbAuditTest extends IntegrityAuditTestBase { + + private static Logger logger = FlexLogger.getLogger(DbAuditTest.class); + + private static final String resourceName = "pdp1"; + + private EntityManagerFactory emf2; + private EntityManager em2; + private DbDAO dbDAO; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditTest.class.getSimpleName()); + IntegrityAuditEntity.setUnitTesting(true); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + IntegrityAuditEntity.setUnitTesting(false); + } + + @Before + public void setUp() { + logger.info("setUp: Entering"); + + super.setUp(); + + dbDAO = null; + emf2 = null; + em2 = null; + + logger.info("setUp: Exiting"); + } + + @After + 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 + public void noEntitiesTest() throws Exception { + Properties properties = makeProperties(); + + logger.info("noEntitiesTest: Entering"); + + dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); + dbDAO.deleteAllIntegrityAuditEntities(); + try { + DbAudit dbAudit = new DbAudit(dbDAO); + dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); + fail("found unexpected entities"); + + } catch (DbAuditException e) { + + } + + logger.info("noEntitiesTest: Exit"); + } + + /* + * Tests the detection of only one entry in the database + */ + @Test + public void oneEntityTest() throws Exception { + Properties properties = makeProperties(); + + logger.info("oneEntityTest: Entering"); + + ExtractAppender log = watch(debugLogger, "DbAudit: Found only (one) IntegrityAuditEntity entry:"); + + // Add one entry in the database + dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); + + List<IntegrityAuditEntity> iaeList = dbDAO.getIntegrityAuditEntities(A_SEQ_PU, nodeType); + logger.info("List size: " + iaeList.size()); + + verifyItemsInLog(log, "one"); + + logger.info("oneEntityTest: Exit"); + } + + /* + * Tests reporting mismatches and missing entries using the error log + */ + @Test + public void mismatchTest() 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); + + ExtractAppender dbglog = watch(debugLogger, "Mismatched entries [(]keys[)]:(.*)"); + ExtractAppender errlog = watch(errorLogger, "DB Audit: ([0-9])"); + + /* + * Create entries in DB1 & DB2 for the resource of interest + */ + dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); + + new DbDAO(resourceName, 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(resourceName, A_SEQ_PU, nodeType); + + // 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(resourceName, A_SEQ_PU, nodeType); + + assertFalse(dbglog.getExtracted().isEmpty()); + + String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1); + int mismatchEntries = mismatchIndex.trim().split(",").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 + */ + 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 new file mode 100644 index 00000000..c4cba280 --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDAOTest.java @@ -0,0 +1,450 @@ +/*- + * ============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; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/* + * All JUnits are designed to run in the local development environment + * where they have write privileges and can execute time-sensitive + * tasks. + */ +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 javax.persistence.PersistenceUnitUtil; +import javax.persistence.Query; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; +import org.onap.policy.common.utils.jpa.EntityTransCloser; + +/* + * All JUnits are designed to run in the local development environment + * where they have write privileges and can execute time-sensitive + * tasks. + */ +public class DbDAOTest extends IntegrityAuditTestBase { + private static String resourceName = "pdp0"; + + private DbDAO d; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbDAOTest.class.getSimpleName()); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } + + @Before + public void setUp() { + super.setUp(); + d = null; + } + + @After + public void tearDown() { + if(d != null) { + d.destroy(); + } + + super.tearDown(); + } + + /* Tests registering a new IntegrityAuditEntity object in the DB */ + @Test + public void testNewRegistration() throws Exception { + Properties properties = makeProperties(); + + try(EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { + d = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Find the proper entry in the database + Query iaequery = em + .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + 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 + public void testUpdateRegistration() throws Exception { + Properties properties = makeProperties(); + + d = 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, "SiteB"); + d = 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 i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + 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("SiteB", iae.getSite()); + } + } + } + + /* Tests obtaining all Integrity Audit Entities from a table */ + @Test + public void testGetIntegrityAuditEntities() throws Exception { + Properties properties = makeProperties(); + + // Add some entries to the DB + d = 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 = d.getIntegrityAuditEntities(A_SEQ_PU, "pdp_xacml"); + assertEquals(2, entities.size()); + } + + /* Tests retrieving a DbDAO instance's IntegrityAuditEntity */ + @Test + public void testGetMyIntegrityAuditEntity() throws Exception { + Properties properties = makeProperties(); + + d = new DbDAO(resourceName, A_SEQ_PU, properties); + IntegrityAuditEntity iae = d.getMyIntegrityAuditEntity(); + // assertEquals("integrityAuditPU", iae.getPersistenceUnit()); + assertEquals(A_SEQ_PU, iae.getPersistenceUnit()); + } + + /* Tests obtaining an IntegrityAuditEntity by ID */ + @Test + public void testGetIntegrityAuditEntity() throws Exception { + Properties properties = makeProperties(); + + // Obtain an entry from the database based on ID + d = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Find the proper database entry + Query iaequery = em + .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + 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 = d.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 + public 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 + d = new DbDAO(resourceName, A_SEQ_PU, properties); + d.setDesignated(resourceName, A_SEQ_PU, true); + + // Find the proper entry in the database + Query iaequery = em + .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + 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 + public void testSetLastUpdated() throws Exception { + Properties properties = makeProperties(); + + try(EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { + // Create an entry + d = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Find the proper entry in the database + Query iaequery = em + .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + 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 + Date oldDate = iae.getLastUpdated(); + + // ensure dates are different by sleeping for a bit + Thread.sleep(1); + + iae.setSite("SiteB"); + iae.setLastUpdated(new Date()); + 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 + public void testGetAllMyEntriesString() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + d = 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 = d.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); + + // 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 + public void testGetAllMyEntriesStringHashSet() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + d = 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("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); + CriteriaQuery<Object> all = cq.select(rootEntry); + TypedQuery<Object> allQuery = em.createQuery(all); + List<Object> objectList = allQuery.getResultList(); + HashSet<Object> resultSet = new HashSet<Object>(); + 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 = d.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity", + 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 + public void testGetAllEntriesStringPropertiesString() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + d = 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 = d.getAllEntries("integrityAuditPU", properties, + "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); + + // 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 + public void testGetAllEntriesStringPropertiesStringHashSet() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + d = 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("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); + CriteriaQuery<Object> all = cq.select(rootEntry); + TypedQuery<Object> allQuery = em.createQuery(all); + List<Object> objectList = allQuery.getResultList(); + HashSet<Object> resultSet = new HashSet<Object>(); + 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 = d.getAllEntries("integrityAuditPU", properties, + "org.onap.policy.common.ia.jpa.IntegrityAuditEntity", 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 + public void testGetAllEntries() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + d = 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 = d.getAllEntries(A_SEQ_PU, properties, + "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); + + // Assert there were 3 entries for that class + assertEquals(3, entries.size()); + } + + /* Tests obtaining all class names of persisted classes */ + public void testGetPersistenceClassNames() throws Exception { + Properties properties = makeProperties(); + + d = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Retrieve persistence class names + Set<String> result = d.getPersistenceClassNames(); + assertEquals(1, result.size()); + } +} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/ExceptionsTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java index af4a8ceb..b02b0c7f 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/ExceptionsTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.ia.test; +package org.onap.policy.common.ia; import static org.junit.Assert.assertEquals; 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 new file mode 100644 index 00000000..1861787a --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java @@ -0,0 +1,619 @@ +/* + * ============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; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.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. + */ +public 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 = "Starting audit simulation for resourceName=("; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase + .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + IntegrityAuditDesignationTest.class.getSimpleName()); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } + + @Before + public void setUp() { + logger.info("setUp: Entering"); + + super.setUp(); + + logger.info("setUp: Exiting"); + } + + @After + 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 + public void testOneResource() throws Exception { + + logger.info("testOneResource: Entering"); + + 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. A quick way of examining the log is to search for the + * string "audit simulation": + * + * As you can see from the "dbAuditSimulate" method, when it executes, it + * logs the "Starting audit simulation..." message and when it finishes, it + * logs the "Finished audit simulation..." message. By looking for these + * messages, you can verify that the audits are run by the proper resource. + * For example, when testFourResourcesOneDead is run, you should see a + * Starting.../Finished... sequence for "pdp1", followed by a + * Starting.../Finished... sequence for pdp2, followed by a + * Starting.../Finished... sequence for pdp4 (pdp3 is skipped as it's + * dead/hung), followed by a Starting.../Finished... sequence for "pdp1", + * etc. + */ + @Test + public void testTwoResources() throws Exception { + + logger.info("testTwoResources: Entering"); + + 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 + public void testTwoResourcesDifferentPus() throws Exception { + + logger.info("testTwoResourcesDifferentPus: Entering"); + + ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1)"); + 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 + public void testTwoResourcesOneDead() throws Exception { + + logger.info("testTwoResourcesOneDead: Entering"); + + 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 + public void testThreeResources() throws Exception { + + logger.info("testThreeResources: Entering"); + + 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 + public void testFourResourcesDifferentPus() throws Exception { + + logger.info("testFourResourcesDifferentPus: Entering"); + + ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1|pdp3)"); + 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 + public void testFourResourcesOneDead() throws Exception { + + logger.info("testFourResourcesOneDead: Entering"); + + 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 + public void testFourResourcesThreeDead() throws Exception { + + logger.info("testFourResourcesThreeDead: Entering"); + + 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 + public void testDesignatedNodeDead() throws Exception { + logger.info("testDesignatedNodeDead: Entering"); + + ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + /* + * Instantiate audit object for pdp1. + */ + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Start audit for pdp2. + */ + MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); + + /* + * Instantiate audit object for pdp3. + */ + 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/test/IntegrityAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java index 5f19e2b9..344ac34e 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/IntegrityAuditTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.ia.test; +package org.onap.policy.common.ia; import static org.junit.Assert.*; @@ -59,6 +59,13 @@ public class IntegrityAuditTest { assertFalse("".equals(badParams.toString())); assertFalse(badParams.toString().contains("resourceName")); 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); + assertFalse("".equals(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 new file mode 100644 index 00000000..474879d1 --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java @@ -0,0 +1,626 @@ +/* + * ============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; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +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.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; + +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.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; + +/** + * 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. + */ +public 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"; + + /** + * Max time, in milliseconds, to wait for a latch to be triggered. + */ + protected static final long WAIT_MS = 5000l; + + /** + * Milliseconds that auditor should sleep between audit steps. + */ + protected static final long SLEEP_INTERVAL_MS = 2l; + + /** + * Milliseconds that auditor should sleep when an audit completes. + */ + protected static final long COMPLETION_INTERVAL_MS = 5l; + + /** + * Milliseconds that an entire audit-simulation cycles takes. + */ + protected static final long AUDIT_SIMULATION_MS = SLEEP_INTERVAL_MS * AuditThread.AUDIT_SIMULATION_ITERATIONS; + + /** + * Milliseconds that it takes for an auditor's last update to become stale. + * Includes a 1ms fudge factor. + */ + protected static final long STALE_MS = 1 + 2 * Math.max(COMPLETION_INTERVAL_MS, AUDIT_SIMULATION_MS); + + /** + * Milliseconds that the db-audit should wait between makings updates. + */ + private static final long DB_AUDIT_UPDATE_MS = 10l; + + /** + * Milliseconds that the db-audit should sleep between cycles. + */ + private static final long DB_AUDIT_SLEEP_MS = 3l; + + public static final String DEFAULT_DB_URL_PREFIX = "jdbc:h2:mem:"; + + protected static final String dbDriver = "org.h2.Driver"; + protected static final String dbUser = "testu"; + protected static final String dbPwd = "testp"; + protected static final String siteName = "SiteA"; + protected static final String nodeType = "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 = "Starting audit simulation for 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; + + /** + * 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 audit sleep interval, to be restored once all tests complete. + */ + private static long savedSleepIntervalMs; + + /** + * Saved audit completion interval, to be restored once all tests complete. + */ + private static long savedCompletionIntervalMs; + + /** + * Saved db audit update time, to be restored once all tests complete. + */ + private static long savedDbAuditUpdateMs; + + /** + * Saved db audit sleep time, to be restored once all tests complete. + */ + private static long savedDbAuditSleepMs; + + /** + * 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 dbDriver + * the name of the DB Driver class + * @param dbUrl + * the URL to the DB + * @throws IOException + * @throws Exception + */ + 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 + savedDebugLevel = debugLogger.getLevel(); + savedErrorLevel = errorLogger.getLevel(); + savedSleepIntervalMs = AuditThread.getAuditThreadSleepIntervalMillis(); + savedCompletionIntervalMs = AuditThread.getAuditCompletionIntervalMillis(); + savedDbAuditUpdateMs = DbAudit.getDbAuditUpdateMillis(); + savedDbAuditSleepMs = DbAudit.getDbAuditSleepMillis(); + + AuditThread.setAuditThreadSleepIntervalMillis(SLEEP_INTERVAL_MS); + AuditThread.setAuditCompletionIntervalMillis(COMPLETION_INTERVAL_MS); + + DbAudit.setDbAuditUpdateMillis(DB_AUDIT_UPDATE_MS); + DbAudit.setDbAuditSleepMillis(DB_AUDIT_SLEEP_MS); + + IntegrityAudit.setUnitTesting(true); + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, dbDriver); + properties.put(IntegrityAuditProperties.DB_URL, dbUrl); + properties.put(IntegrityAuditProperties.DB_USER, dbUser); + properties.put(IntegrityAuditProperties.DB_PWD, dbPwd); + properties.put(IntegrityAuditProperties.SITE_NAME, siteName); + properties.put(IntegrityAuditProperties.NODE_TYPE, nodeType); + + 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(); + + debugLogger.setLevel(Level.DEBUG); + errorLogger.setLevel(Level.ERROR); + } + + /** + * Restores the configuration to what it was before the test. + */ + protected static void tearDownAfterClass() { + AuditThread.setAuditThreadSleepIntervalMillis(savedSleepIntervalMs); + AuditThread.setAuditCompletionIntervalMillis(savedCompletionIntervalMs); + + DbAudit.setDbAuditUpdateMillis(savedDbAuditUpdateMs); + DbAudit.setDbAuditSleepMillis(savedDbAuditSleepMs); + + IntegrityAudit.setUnitTesting(false); + + 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_MILLISECONDS, String.valueOf(SLEEP_INTERVAL_MS)); + + // Clean up the DB + try (EntityTransCloser etc = new EntityTransCloser(em.getTransaction())) { + EntityTransaction et = etc.getTransation(); + + 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(); + } + } + + /** + * + * @param properties + * @param persistenceUnit + * @param tableName + */ + public 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 em = emc.getManager(); + EntityTransaction et = etc.getTransation(); + + // Clean up the DB + em.createQuery("Delete from " + tableName).executeUpdate(); + + // commit transaction + et.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 textre + * regular expression used to extract an item from a line in the + * log. The first "capture" group of the regular expression is + * assumed to contain the extracted item + * @param items + * items that should be matched by the items extracted from the + * log, in order + * @throws IOException + * @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 rName : app.getExtracted()) { + if (rName.equals(expected)) { + if (!it.hasNext()) { + // matched all of the items + return; + } + + last = expected; + expected = it.next(); + + } else if (!rName.equals(last)) { + List<String> remaining = getRemaining(expected, it); + fail("missing items " + remaining + ", but was: " + rName); + } + } + + List<String> remaining = getRemaining(expected, it); + assertTrue("missing items " + remaining, remaining.isEmpty()); + } + + /** + * 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)) { + System.out.println("failed to stop audit thread"); + return false; + } + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + return true; + } + + /** + * Makes a new auditor. + * + * @param resourceName2 + * @param persistenceUnit2 + * @return a new auditor + * @throws Exception + */ + protected MyIntegrityAudit makeAuditor(String resourceName2, String persistenceUnit2) throws Exception { + return new MyIntegrityAudit(resourceName2, persistenceUnit2, makeProperties()); + } + + /** + * 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 + * @throws InterruptedException + */ + protected void waitStaleAndRun(MyIntegrityAudit... auditors) throws InterruptedException { + waitStale(); + runAudit(auditors); + } + + /** + * Runs an audit on several auditors in parallel. + * + * @param auditors + * @throws InterruptedException + */ + protected void runAudit(MyIntegrityAudit... auditors) throws InterruptedException { + + // start an audit cycle on each auditor + List<CountDownLatch> latches = new ArrayList<>(auditors.length); + for (MyIntegrityAudit p : auditors) { + latches.add(p.startAudit()); + } + + // wait for each auditor to complete its cycle + for (CountDownLatch latch : latches) { + waitLatch(latch); + } + } + + /** + * Waits for a latch to reach zero. + * + * @param latch + * @throws InterruptedException + * @throws AssertionError + * if the latch did not reach zero in the allotted time + */ + protected void waitLatch(CountDownLatch latch) throws InterruptedException { + assertTrue(latch.await(WAIT_MS, TimeUnit.SECONDS)); + } + + /** + * Sleep a bit so that the currently designated pdp becomes stale. + * + * @throws InterruptedException + */ + protected void waitStale() throws InterruptedException { + Thread.sleep(STALE_MS); + } + + /** + * 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(); + } + + public void detach() { + logger.detachAppender(appender); + } + } + + /** + * Manages audits by inserting latches into a queue for the AuditThread to + * count. + */ + protected class MyIntegrityAudit extends IntegrityAudit { + + /** + * Queue from which the AuditThread will take latches. + */ + private BlockingQueue<CountDownLatch> queue = null; + + /** + * Constructs an auditor and starts the AuditThread. + * + * @param resourceName + * @param persistenceUnit + * @param properties + * @throws Exception + */ + public MyIntegrityAudit(String resourceName, String persistenceUnit, Properties properties) throws Exception { + super(resourceName, persistenceUnit, properties); + + auditors.add(this); + + startAuditThread(); + } + + /** + * Interrupts the AuditThread. + */ + public void interrupt() { + super.stopAuditThread(); + } + + /** + * Triggers an audit by adding a latch to the queue. + * + * @return the latch that was added + * @throws InterruptedException + */ + public CountDownLatch startAudit() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + queue.add(latch); + + return latch; + } + + /** + * Starts a new AuditThread. Creates a new latch queue and associates it + * with the thread. + */ + @Override + public final void startAuditThread() throws Exception { + if (queue != null) { + // queue up a bogus latch, in case a thread is still running + queue.add(new CountDownLatch(1) { + @Override + public void countDown() { + throw new RuntimeException("auditor has multiple threads"); + } + }); + } + + queue = new LinkedBlockingQueue<>(); + + if (super.startAuditThread(queue)) { + // wait for the thread to start + CountDownLatch latch = new CountDownLatch(1); + queue.add(latch); + waitLatch(latch); + } + } + + /** + * 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)); + } + } +} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/IaTestEntity.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java index 9c34dc4a..43277a71 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/IaTestEntity.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java @@ -1,8 +1,8 @@ -/*- +/* * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.ia.test.jpa; +package org.onap.policy.common.ia.jpa; import java.io.Serializable; import java.util.Date; diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/PersonSample.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java index eb777e7f..d7fcf330 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/PersonSample.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java @@ -1,8 +1,8 @@ -/*- +/* * ============LICENSE_START======================================================= * Integrity Audit * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.ia.test.jpa; +package org.onap.policy.common.ia.jpa; import java.io.Serializable; diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/AuditPeriodTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/AuditPeriodTest.java deleted file mode 100644 index 68ab42d9..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/AuditPeriodTest.java +++ /dev/null @@ -1,483 +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========================================================= - */ - -package org.onap.policy.common.ia.test; - - -import static org.junit.Assert.*; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Properties; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; - -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import org.onap.policy.common.ia.AuditThread; -import org.onap.policy.common.ia.IntegrityAudit; -import org.onap.policy.common.ia.IntegrityAuditProperties; -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. - * - * If any have been ignored (@Ignore) they will not run at the same time - * as others. You should run them as JUnits by themselves. - */ -public class AuditPeriodTest { - - private static Logger logger = FlexLogger.getLogger(AuditPeriodTest.class); - - private static final String AUDIT_PERIOD_TEST_LOG = "./testingLogs/common-modules/integrity-audit/debug.log"; - - private static String persistenceUnit; - private static Properties properties; - private static String resourceName; - - @Before - public void setUp() throws Exception { - - - System.out.println("setUp: Clearing " + AUDIT_PERIOD_TEST_LOG); - FileOutputStream fstream = new FileOutputStream(AUDIT_PERIOD_TEST_LOG); - fstream.close(); - - logger.info("setUp: Entering"); - - IntegrityAudit.setUnitTesting(true); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - persistenceUnit = "testPU"; - resourceName = "pdp1"; - - //Clean up the DB - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - EntityManager 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 - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - em.close(); - - logger.info("setUp: Exiting"); - - } - - - @After - public void tearDown() throws Exception { - - logger.info("tearDown: Entering"); - - logger.info("tearDown: Exiting"); - - } - - /* - * Verifies (via log parsing) that when a negative audit period is - * specified, the audit is suppressed. - */ - //@Ignore - @Test - public void testNegativeAuditPeriod() throws Exception { - - logger.info("testNegativeAuditPeriod: Entering"); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "-1"); - - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) audit to immediately terminate. - */ - Thread.sleep(1000); - - logger.info("testNegativeAuditPeriod: Stopping audit thread (should be a no-op!)"); - integrityAudit.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(AUDIT_PERIOD_TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("-1")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Suppressing integrity audit, integrityAuditPeriodSeconds=")) { - startIndex = strLine.indexOf("integrityAuditPeriodSeconds=") + 28; - - String integrityAuditPeriodSeconds = strLine.substring(startIndex); - - delegates.add(integrityAuditPeriodSeconds); - } - } - - for (String delegate: delegates) { - logger.info("testNegativeAuditPeriod: delegate: " + delegate); - } - - fstream.close(); - - assertTrue(expectedResult.equals(delegates)); - - 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). - */ - @Ignore - @Test - public void testZeroAuditPeriod() throws Exception { - - logger.info("testZeroAuditPeriod: Entering"); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "0"); - - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, - persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) audit to generate a bunch of sleep wake sequences. - * - * Note: - * - * (AuditThread.AUDIT_SIMULATION_SLEEP_INTERVAL * - * AuditThread.AUDIT_SIMULATION_ITERATIONS) is the time it takes for the - * audit simulation to run. - * - * (integrityAudit.getIntegrityAuditPeriodSeconds() should return a - * value of zero; i.e. audit should not sleep at all between iterations - * - * "100"ms is the time we allow the audit to cycle continuously - */ - long sleepMillis = (AuditThread.AUDIT_SIMULATION_SLEEP_INTERVAL * AuditThread.AUDIT_SIMULATION_ITERATIONS) - + (integrityAudit.getIntegrityAuditPeriodSeconds() * 1000) - + 100; - logger.info("testZeroAuditPeriod: Sleeping " + sleepMillis + "ms before stopping auditThread"); - Thread.sleep(sleepMillis); - - logger.info("testZeroAuditPeriod: Stopping audit thread"); - integrityAudit.stopAuditThread(); - - /* - * Before audit completion message upon awaking from sleep is upper case "Awaking". After audit - * completion, all awakings are lower case "awaking". - */ - logger.info("testZeroAuditPeriod: Parsing " + AUDIT_PERIOD_TEST_LOG + " for 'awaking'"); - FileInputStream fstream = new FileInputStream(AUDIT_PERIOD_TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine = ""; - int awakings = 0; - int lines = 0; - while ((strLine = br.readLine()) != null) { - if (strLine.contains("Awaking from 0ms sleep")) { - fail("Audit appears not to have run!? Got '" + strLine + "'"); - } else { - if (strLine.contains("awaking from 0ms sleep")) { - awakings++; - } - } - lines++; - } - logger.info("testZeroAuditPeriod: Done parsing " - + AUDIT_PERIOD_TEST_LOG + " for 'awaking'; lines parsed=" - + lines + ", closing stream"); - fstream.close(); - - /* - * We should get at least 10 sleep/wake sequences. - */ - assertTrue("Only " + awakings + " awakings", awakings > 10); - assertTrue(integrityAudit.getIntegrityAuditPeriodSeconds() == 0); - - logger.info("testZeroAuditPeriod: Exiting, awakings=" - + awakings + ", integrityAuditPeriodSeconds=" - + integrityAudit.getIntegrityAuditPeriodSeconds()); - - } - - /* - * Verifies (via log parsing) that when an audit period of five minutes is - * specified, there is a five minute interval between the audits run - * on each of three different entities. - */ - @Ignore - @Test - public void testFiveMinuteAuditPeriod() throws Exception { - - logger.info("testFiveMinuteAuditPeriod: Entering"); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "300"); - - /* - * Start audit for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, - persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Start audit for pdp2. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "300"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - integrityAudit2.startAuditThread(); - - /* - * Start audit for pdp3. - */ - Properties properties3 = new Properties(); - properties3.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties3.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties3.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties3.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "300"); - String persistenceUnit3 = "testPU"; - String resourceName3 = "pdp3"; - IntegrityAudit integrityAudit3 = new IntegrityAudit(resourceName3, persistenceUnit3, properties3); - integrityAudit3.startAuditThread(); - - - /* - * 1) All three audit run once. This should take approximately 105 seconds, as follows: - * - * T0: pdp1 runs audit (15 seconds), then sleeps for five minutes (300 seconds) - * pdp2 recognizes that pdp1 is stale (30 seconds) and runs its audit (15 seconds) - * pdp3 recognizes that pdp2 is stale (30 seconds) and runs its audit (15 seconds) - * - * 2) Five minutes after T0, at T1, pdp1 wakes up and the above sequence begins again, - * which should take another 115 seconds: - * - * T1: pdp1 runs audit (15 seconds), then sleeps for two minutes (300 seconds) - * pdp2 wakes up, resets auditCompleted and sleeps (5 seconds), recognizes that pdp1 is stale (30 seconds) and runs its audit (15 seconds) - * pdp3 wakes up, resets auditCompleted and sleeps (5 seconds), recognizes that pdp2 is stale (30 seconds) and runs its audit (15 seconds) - * - * So, the entire sequence should take 15 + 300 + 115 = 430 seconds - * Adding a fudge factor, we sleep for 450 seconds - */ - Thread.sleep(450000); - - - logger.info("testFiveMinuteAuditPeriod: Stopping all three audit threads"); - integrityAudit.stopAuditThread(); - - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - integrityAudit3.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(AUDIT_PERIOD_TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1", "pdp2", "pdp3")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate: delegates) { - logger.info("testFiveMinuteAuditPeriod: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 6); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - assertTrue("delegate 3 is " + expectedResult.get(3), expectedResult.get(3).equals(delegates.get(3))); - assertTrue("delegate 4 is " + expectedResult.get(4), expectedResult.get(4).equals(delegates.get(4))); - assertTrue("delegate 5 is " + expectedResult.get(5), expectedResult.get(5).equals(delegates.get(5))); - - logger.info("testFiveMinuteAuditPeriod: Exiting"); - } - - /* - * Verifies (via log parsing) that when an audit period of 20 seconds is - * specified, there is a 20 second interval between the audits run - * on each of three different entities. - */ - @Ignore - @Test - public void testTwentySecondAuditPeriod() throws Exception { - - logger.info("testTwentySecondAuditPeriod: Entering"); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "20"); - - /* - * Start audit for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, - persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Start audit for pdp2. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "20"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - integrityAudit2.startAuditThread(); - - /* - * Start audit for pdp3. - */ - Properties properties3 = new Properties(); - properties3.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties3.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties3.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties3.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "20"); - String persistenceUnit3 = "testPU"; - String resourceName3 = "pdp3"; - IntegrityAudit integrityAudit3 = new IntegrityAudit(resourceName3, persistenceUnit3, properties3); - integrityAudit3.startAuditThread(); - - - /* - * 1) All three audit run once. - * - * pdp1 runs audit (15 seconds), then goes into 20 second sleep cycles - * pdp2 recognizes that pdp1 is stale (30 seconds), runs its audit (15 seconds), then goes into 20 second sleep cycles - * pdp3 recognizes that pdp2 is stale (30 seconds), runs its audit (15 seconds), then goes into 20 second sleep cycles - * - * 2) Eventually pdp2 gets stale, pdp1 recognizes this and cycle begins again. - * - * So, we allow 15 + (5 * 45) = 240 seconds plus a fudge factor. - * - */ - Thread.sleep(250000); - - - logger.info("testTwentySecondAuditPeriod: Stopping all three audit threads"); - integrityAudit.stopAuditThread(); - - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - integrityAudit3.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(AUDIT_PERIOD_TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1", "pdp2", "pdp3")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate: delegates) { - logger.info("testTwentySecondAuditPeriod: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 6); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - assertTrue("delegate 3 is " + expectedResult.get(3), expectedResult.get(3).equals(delegates.get(3))); - assertTrue("delegate 4 is " + expectedResult.get(4), expectedResult.get(4).equals(delegates.get(4))); - assertTrue("delegate 5 is " + expectedResult.get(5), expectedResult.get(5).equals(delegates.get(5))); - - logger.info("testTwentySecondAuditPeriod: Exiting"); - } - -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditTest.java deleted file mode 100644 index ecf75eef..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditTest.java +++ /dev/null @@ -1,755 +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========================================================= - */ - -package org.onap.policy.common.ia.test; - -import static org.junit.Assert.*; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStreamReader; -import java.util.Date; -import java.util.List; -import java.util.Properties; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import javax.persistence.Query; - - -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.onap.policy.common.ia.DbAudit; -import org.onap.policy.common.ia.DbAuditException; -import org.onap.policy.common.ia.DbDAO; -import org.onap.policy.common.ia.DbDaoTransactionException; -import org.onap.policy.common.ia.IntegrityAudit; -import org.onap.policy.common.ia.IntegrityAuditProperties; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; -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. - * - * If any have been ignored (@Ignore) they will not run at the same time - * as others. You should run them as JUnits by themselves. - */ -public class DbAuditTest { - - private static Logger logger = FlexLogger.getLogger(DbAuditTest.class); - - private DbDAO dbDAO; - private static String persistenceUnit; - private static Properties properties; - private static String resourceName; - private String dbDriver; - private String dbUrl; - private String dbUser; - private String dbPwd; - private String siteName; - private String nodeType; - private static final String TEST_LOG = "./testingLogs/common-modules/integrity-audit/debug.log"; - private static final String ERROR_LOG = "./testingLogs/common-modules/integrity-audit/error.log"; - - public void cleanLog() throws Exception{ - - logger.debug("cleanLog: enter"); - //FileOutputStream fstream = new FileOutputStream("IntegrityAudit.log"); - FileOutputStream fstream = new FileOutputStream(TEST_LOG); - fstream.close(); - fstream = new FileOutputStream(ERROR_LOG); - fstream.close(); - logger.debug("cleanLog: exit"); - } - - public void cleanDb(String persistenceUnit, Properties properties){ - logger.debug("cleanDb: enter"); - - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - EntityManager em = emf.createEntityManager(); - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - // Clean up the DB - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - em.close(); - logger.debug("cleanDb: exit"); - } - - - @Before - public void setUp() throws Exception { - - logger.info("setUp: Entering"); - - IntegrityAudit.setUnitTesting(true); - IntegrityAuditEntity.setUnitTesting(true); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - dbDriver = TestUtils.DEFAULT_DB_DRIVER; - dbUrl = TestUtils.DEFAULT_DB_URL; - dbUser = TestUtils.DEFAULT_DB_USER; - dbPwd = TestUtils.DEFAULT_DB_PWD; - siteName = "SiteA"; - nodeType = "pdp_xacml"; - persistenceUnit = "testPU"; - resourceName = "pdp1"; - - logger.info("setUp: Exiting"); - - } - - @After - public void tearDown() throws Exception { - - logger.info("tearDown: Entering"); - - //cleanDb(persistenceUnit, properties); - - logger.info("tearDown: Exiting"); - } - - //@Ignore - @Test - public void runAllTests() throws Exception{ - //The order is important - I haven't figured out why, but it is. - //mismatchTest(); - noEntitiesTest(); - oneEntityTest(); - } - - - /* - * Tests printing an error to the log in the event where - * there are no entities saved in the database - */ - public void noEntitiesTest() throws Exception { - cleanLog(); - cleanDb(persistenceUnit, properties); - - logger.info("noEntitiesTest: Entering"); - - // Boolean to assert there are no entries found - Boolean noEntities = false; - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - dbDAO.deleteAllIntegrityAuditEntities(); - try { - DbAudit dbAudit = new DbAudit(dbDAO); - dbAudit.dbAudit(resourceName, persistenceUnit, nodeType); - } - catch (DbAuditException e) { - noEntities = true; - } - - dbDAO.deleteAllIntegrityAuditEntities(); - - logger.info("noEntitiesTest: No entities are persisted in the database"); - - // Assert there are no entities retrieved - assertTrue(noEntities); - - logger.info("noEntitiesTest: Exit"); - } - - /* - * Tests the detection of only one entry in the database - */ - public void oneEntityTest() throws Exception{ - cleanLog(); - cleanDb(persistenceUnit, properties); - - logger.info("oneEntityTest: Entering"); - - // Add one entry in the database - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - dbAudit.dbAudit(resourceName, persistenceUnit, nodeType); - - List<IntegrityAuditEntity> iaeList = dbDAO.getIntegrityAuditEntities(persistenceUnit, nodeType); - logger.info("List size: " + iaeList.size()); - - //FileInputStream fstream = new FileInputStream("IntegrityAudit.log"); - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - Boolean oneEntity = false; - while ((strLine = br.readLine()) != null) { - //parse strLine to obtain what you want - - if (strLine.contains("DbAudit: Found only one IntegrityAuditEntity entry:")) { - oneEntity = true; - } - - } - if(oneEntity){ - logger.info("oneEntityTest: One entity is persisted in the database"); - }else{ - logger.info("oneEntityTest: No entities are persisted in the database"); - } - - - // Assert there is only one entry - assertTrue(oneEntity); - - br.close(); - - logger.info("oneEntityTest: Exit"); - } - - /* - * Tests reporting mismatches and misentries using the error log - */ - @SuppressWarnings("unused") - public void mismatchTest() throws Exception{ - cleanLog(); - logger.info("mismatchTest: Entering"); - - // Properties for DB2 - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/iaTest2"); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - //Clean the DBs before we begin - cleanDb(persistenceUnit, properties); - cleanDb(persistenceUnit, properties2); - - // Entries in DB1 - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbDAO dbDAO2 = new DbDAO("pdp2", persistenceUnit, properties); - - /* - * dbDAO3 is a mismatch entry, dbDAO7 is a misentry - */ - DbDAO dbDAO3 = new DbDAO("pdp3", persistenceUnit, properties); - DbDAO dbDAO7 = new DbDAO("pdp4", persistenceUnit, properties); - Date date = new Date(); - - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - /* - * Update DB url's in DB1 to point to DB2 - */ - try{ - EntityManager 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 - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp2"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - 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); - logger.info("Resource: " + "pdp2" + " with PersistenceUnit: " + 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 " + "pdp2" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp2"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl("jdbc:h2:file:./sql/iaTest2"); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not found, create a new entry - iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp1"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList2 = iaequery.getResultList(); - iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - if(!iaeList2.isEmpty()){ - //ignores multiple results - iae = (IntegrityAuditEntity) iaeList2.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info("Resource: " + "pdp1" + " with PersistenceUnit: " + 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 " + "pdp1" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp1"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl("jdbc:h2:file:./sql/iaTest2"); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not found, create a new entry - iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp3"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList3 = iaequery.getResultList(); - iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - if(!iaeList3.isEmpty()){ - //ignores multiple results - iae = (IntegrityAuditEntity) iaeList3.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info("Resource: " + "pdp3" + " with PersistenceUnit: " + persistenceUnit - + " exists and entry be updated"); - }else{ - // If it does not exist, we also must add the resourceName, persistenceUnit and designated values - logger.info("Adding resource " + "pdp3" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp3"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl(dbUrl); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not found, create a new entry - iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp4"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList4 = iaequery.getResultList(); - iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - if(!iaeList4.isEmpty()){ - //ignores multiple results - iae = (IntegrityAuditEntity) iaeList4.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info("Resource: " + "pdp4" + " with PersistenceUnit: " + persistenceUnit - + " exists and entry be updated"); - }else{ - // If it does not exist, we also must add the resourceName, persistenceUnit and designated values - logger.info("Adding resource " + "pdp4" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp4"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl("jdbc:h2:file:./sql/iaTest2"); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - em.close(); - }catch (Exception e){ - String msg = "DbDAO: " + "register() " + "ecountered a problem in execution: "; - logger.error(msg + e); - throw new DbDaoTransactionException(e); - } - - /* - * Identical entries in from DB1 in DB2 except for dbDAO6 - */ - emf = Persistence.createEntityManagerFactory(persistenceUnit, properties2); - DbDAO dbDAO4 = new DbDAO(resourceName, persistenceUnit, properties2); - - DbDAO dbDAO5 = new DbDAO("pdp2", persistenceUnit, properties2); - - /* - * This is the mismatch entry - */ - DbDAO dbDAO6 = new DbDAO("pdp3", persistenceUnit, properties2); - try{ - EntityManager 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 - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp2"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - 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); - logger.info("Resource: " + "pdp2" + " with PersistenceUnit: " + 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 " + "pdp2" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp2"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl("jdbc:h2:file:./sql/iaTest2"); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not found, create a new entry - iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp1"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList2 = iaequery.getResultList(); - iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - if(!iaeList2.isEmpty()){ - //ignores multiple results - iae = (IntegrityAuditEntity) iaeList2.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info("Resource: " + "pdp1" + " with PersistenceUnit: " + 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 " + "pdp1" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp1"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl("jdbc:h2:file:./sql/iaTest2"); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - et.begin(); - - // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not found, create a new entry - iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp3"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList3 = iaequery.getResultList(); - iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - if(!iaeList3.isEmpty()){ - //ignores multiple results - iae = (IntegrityAuditEntity) iaeList3.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(iae); - logger.info("Resource: " + "pdp3" + " with PersistenceUnit: " + 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 " + "pdp3" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp3"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl("jdbc:h2:file:./sql/iaTest2"); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - em.close(); - }catch (Exception e){ - String msg = "DbDAO: " + "register() " + "ecountered a problem in execution: "; - logger.error(msg + e); - throw new DbDaoTransactionException(e); - - } - - /* - * 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(resourceName, persistenceUnit, nodeType); - emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - try{ - EntityManager 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 - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", "pdp3"); - iaequery.setParameter("pu", persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - - //If it already exists, we just want to update the properties and lastUpdated date - 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); - logger.info("Resource: " + "pdp3" + " with PersistenceUnit: " + persistenceUnit - + " exists and entry be updated"); - }else{ - // If it does not exist, we also must add the resourceName, persistenceUnit and designated values - logger.info("Adding resource " + "pdp3" + " with PersistenceUnit: " + persistenceUnit - + " to IntegrityAuditEntity table"); - iae = new IntegrityAuditEntity(); - iae.setResourceName("pdp3"); - iae.setPersistenceUnit(persistenceUnit); - iae.setDesignated(false); - } - - //update/set properties in entry - iae.setSite(siteName); - iae.setNodeType(nodeType); - iae.setLastUpdated(date); - iae.setCreatedDate(date); - iae.setJdbcDriver(dbDriver); - iae.setJdbcPassword(dbPwd); - iae.setJdbcUrl("jdbc:h2:file:./sql/iaTest2"); - iae.setJdbcUser(dbUser); - - em.persist(iae); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - em.close(); - }catch (Exception e){ - String msg = "DbDAO: " + "register() " + "ecountered a problem in execution: "; - logger.error(msg + e); - throw new DbDaoTransactionException(e); - } - - /* - * Run the audit again and correct the mismatch, the result should be one - * entry in the mismatchKeySet because of the misentry from the beginning - * of the test - */ - dbAudit.dbAudit(resourceName, persistenceUnit, nodeType); - - //Cleanup DB2 - cleanDb(persistenceUnit, properties2); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - String mismatchIndex = ""; - while ((strLine = br.readLine()) != null) { - //parse strLine to obtain what you want...retrieve the last entry - - if (strLine.contains("Mismatched entries (keys):")) { - startIndex = strLine.indexOf("(keys):") + 8; - mismatchIndex = strLine.substring(startIndex); - } - } - int mismatchEntries = mismatchIndex.trim().split(",").length; - logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" - + " mismatachEntries = " + mismatchEntries); - - // Assert there is only one entry index - assertEquals(1, mismatchEntries); - - br.close(); - - //Now check the entry in the error.log - fstream = new FileInputStream(ERROR_LOG); - br = new BufferedReader(new InputStreamReader(fstream)); - String mismatchNum = ""; - while ((strLine = br.readLine()) != null) { - //parse strLine to obtain what you want...retrieve the last entry - - if (strLine.contains("DB Audit:")) { - startIndex = strLine.indexOf("DB Audit:") + 10; - mismatchNum = strLine.substring(startIndex, startIndex+1); - } - } - logger.info("mismatchTest: mismatchNum found: '" + mismatchNum + "'"); - - // Assert that there are a total of 3 mismatches - 1 between each comparison node. - assertEquals("3", mismatchNum); - - br.close(); - - logger.info("mismatchTest: Exit"); - } - -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbDAOTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbDAOTest.java deleted file mode 100644 index ac3bc587..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbDAOTest.java +++ /dev/null @@ -1,742 +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========================================================= - */ - -package org.onap.policy.common.ia.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/* - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - */ -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 javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import javax.persistence.PersistenceUnitUtil; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.ia.DbDAO; -import org.onap.policy.common.ia.DbDaoTransactionException; -import org.onap.policy.common.ia.IntegrityAuditProperties; -import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; - -/* - * 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. - */ -public class DbDAOTest { - private static String persistenceUnit; - private static Properties properties; - private static String resourceName; - - DbDAO d; - - @Before - public void setUp() throws Exception { - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - //persistenceUnit = "integrityAuditPU"; - persistenceUnit = "testPU"; - resourceName = "pdp0"; - } - - @After - public void tearDown() throws Exception { - } - - /* Tests registering a new IntegrityAuditEntity object in the DB */ - //@Ignore - @Test - public void testNewRegistration() { - try { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin Transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - et.begin(); - d = new DbDAO(resourceName, persistenceUnit, properties); - - // Find the proper entry in the database - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", DbDAOTest.resourceName); - iaequery.setParameter("pu", DbDAOTest.persistenceUnit); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - - // Assert that the IntegrityAuditEntity object was found - assertNotNull(iaeList); - - // flush to the DB - em.flush(); - et.commit(); - em.close(); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests updating an IntegrityAuditEntity if it has already been registered */ - //@Ignore - @Test - public void testUpdateRegistration() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - // close the EntityManager - em.close(); - - try { - d = new DbDAO(resourceName, persistenceUnit, 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, "SiteB"); - d = new DbDAO(resourceName, persistenceUnit, properties); - - em = emf.createEntityManager(); - - // Start a transaction - et = em.getTransaction(); - - // Begin Transaction - et.begin(); - - // Find the proper entry in the database - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", DbDAOTest.resourceName); - iaequery.setParameter("pu", DbDAOTest.persistenceUnit); - - @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(); - - // close the EntityManager - em.close(); - - // Assert that the site_name for the existing entry was updated - assertEquals("SiteB", iae.getSite()); - } - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests obtaining all Integrity Audit Entities from a table */ - //@Ignore - @Test - public void testGetIntegrityAuditEntities() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - - // close the transaction - et.commit(); - - // close the EntityManager - em.close(); - - try { - // Add some entries to the DB - d = new DbDAO(resourceName, persistenceUnit, properties); - new DbDAO("pdp1", persistenceUnit, properties); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_drools"); - new DbDAO("pdp2", persistenceUnit, properties); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - List<IntegrityAuditEntity> entities; - try { - // Obtain entries based on persistenceUnit and nodeType - entities = d.getIntegrityAuditEntities(persistenceUnit, "pdp_xacml"); - assertEquals(2, entities.size()); - } catch (DbDaoTransactionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests retrieving a DbDAO instance's IntegrityAuditEntity */ - //@Ignore - @Test - public void testGetMyIntegrityAuditEntity() { - try { - d = new DbDAO(resourceName, persistenceUnit, properties); - IntegrityAuditEntity iae = d.getMyIntegrityAuditEntity(); - //assertEquals("integrityAuditPU", iae.getPersistenceUnit()); - assertEquals("testPU", iae.getPersistenceUnit()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests obtaining an IntegrityAuditEntity by ID */ - //@Ignore - @Test - public void testGetIntegrityAuditEntity() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - - // close the transaction - et.commit(); - - try { - // Obtain an entry from the database based on ID - d = new DbDAO(resourceName, persistenceUnit, properties); - - et.begin(); - - // Find the proper database entry - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", DbDAOTest.resourceName); - iaequery.setParameter("pu", DbDAOTest.persistenceUnit); - - @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 = d.getIntegrityAuditEntity((long) iaeId); - Object duplicateId = util.getIdentifier(iaeDuplicate); - - // Assert that the proper entry was retrieved based on ID - assertEquals((long) iaeId, (long) duplicateId); - } - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // close the EntityManager - em.close(); - } - - /* Tests setting an IntegrityAuditEntity as the designated node */ - //@Ignore - @Test - public void testSetDesignated() { - try { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - et.begin(); - - // Create an entry and set it's designated field to true - d = new DbDAO(resourceName, persistenceUnit, properties); - d.setDesignated(resourceName, persistenceUnit, true); - - // Find the proper entry in the database - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", persistenceUnit); - - @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(); - - // close the EntityManager - em.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests that the lastUpdated column in the database is updated properly */ - //@Ignore - @Test - public void testSetLastUpdated() { - try { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - et.begin(); - - // Create an entry - d = new DbDAO(resourceName, persistenceUnit, properties); - - // Find the proper entry in the database - Query iaequery = em.createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", persistenceUnit); - - @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 - Date oldDate = iae.getLastUpdated(); - iae.setSite("SiteB"); - iae.setLastUpdated(new Date()); - Date newDate = iae.getLastUpdated(); - - em.persist(iae); - // flush to the DB - em.flush(); - // close the transaction - et.commit(); - // close the EntityManager - em.close(); - - // Assert that the old and new update times are different - assertNotEquals(oldDate, newDate); - } - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests that all the entries from a class can be retrieved */ - //@Ignore - @Test - public void testGetAllMyEntriesString() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - // close the EntityManager - em.close(); - - try { - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, persistenceUnit, properties); - new DbDAO("pdp1", persistenceUnit, properties); - new DbDAO("pdp2", persistenceUnit, properties); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - // Obtain a hash with the persisted objects - Map<Object, Object> entries = d.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests retrieving all entities in a Persistence Unit using the class name and a hashset of IDs */ - //@Ignore - @Test - public void testGetAllMyEntriesStringHashSet() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - try { - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, persistenceUnit, properties); - new DbDAO("pdp1", persistenceUnit, properties); - new DbDAO("pdp2", persistenceUnit, properties); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - // Obtain all entity keys - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery<Object> cq = cb.createQuery(); - Root<?> rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); - CriteriaQuery<Object> all = cq.select(rootEntry); - TypedQuery<Object> allQuery = em.createQuery(all); - List<Object> objectList = allQuery.getResultList(); - HashSet<Object> resultSet = new HashSet<Object>(); - 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 = d.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity", resultSet); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - // close the EntityManager - em.close(); - } - - /* Tests retrieving all entities in a Persistence Unit using the persistence unit, properties, and class name */ - //@Ignore - @Test - public void testGetAllEntriesStringPropertiesString() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - // close the EntityManager - em.close(); - - try { - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, persistenceUnit, properties); - new DbDAO("pdp1", persistenceUnit, properties); - new DbDAO("pdp2", persistenceUnit, properties); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - // Obtain a hash with the persisted objects - Map<Object, Object> entries = d.getAllEntries("integrityAuditPU", properties, "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests retrieving all entities in a Persistence Unit using the persistence unit, properties, class name, and a hashset of IDs */ - //@Ignore - @Test - public void testGetAllEntriesStringPropertiesStringHashSet() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - try { - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, persistenceUnit, properties); - new DbDAO("pdp1", persistenceUnit, properties); - new DbDAO("pdp2", persistenceUnit, properties); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - // Obtain all entity keys - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery<Object> cq = cb.createQuery(); - Root<?> rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); - CriteriaQuery<Object> all = cq.select(rootEntry); - TypedQuery<Object> allQuery = em.createQuery(all); - List<Object> objectList = allQuery.getResultList(); - HashSet<Object> resultSet = new HashSet<Object>(); - 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 = d.getAllEntries("integrityAuditPU", properties, "org.onap.policy.common.ia.jpa.IntegrityAuditEntity", resultSet); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - // close the EntityManager - em.close(); - } - - /* Tests getting all the entries from a class based on persistenceUnit, properties, and className */ - //@Ignore - @Test - public void testGetAllEntries() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - // close the EntityManager - em.close(); - - try { - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, persistenceUnit, properties); - new DbDAO("pdp1", persistenceUnit, properties); - new DbDAO("pdp2", persistenceUnit, properties); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - // Obtain a hash with the persisted objects - Map<Object, Object> entries = d.getAllEntries(persistenceUnit, properties, "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /* Tests obtaining all class names of persisted classes */ - public void testGetPersistenceClassNames() { - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - EntityManager em = emf.createEntityManager(); - - // Start a transaction - EntityTransaction et = em.getTransaction(); - - // Begin transaction - et.begin(); - - // Clean the DB - em.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate(); - - // flush to the DB - em.flush(); - et.commit(); - - // close the EntityManager - em.close(); - - try { - d = new DbDAO(resourceName, persistenceUnit, properties); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // Retrieve persistence class names - Set<String> result = d.getPersistenceClassNames(); - assertEquals(1, result.size()); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/IntegrityAuditDesignationTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/IntegrityAuditDesignationTest.java deleted file mode 100644 index 5c593123..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/IntegrityAuditDesignationTest.java +++ /dev/null @@ -1,1112 +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========================================================= - */ - -package org.onap.policy.common.ia.test; - -import static org.junit.Assert.*; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Properties; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; - - - -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import org.onap.policy.common.ia.AuditThread; -import org.onap.policy.common.ia.DbDAO; -import org.onap.policy.common.ia.IntegrityAudit; -import org.onap.policy.common.ia.IntegrityAuditProperties; -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. - * - * If any have been ignored (@Ignore) they will not run at the same time - * as others. You should run them as JUnits by themselves. - */ -public class IntegrityAuditDesignationTest { - - private static Logger logger = FlexLogger.getLogger(IntegrityAuditDesignationTest.class); - - /* - * Provides a little cushion for timing events. - */ - private static int FUDGE_FACTOR = 15000; - - private static String persistenceUnit; - private static Properties properties; - private static String resourceName; - private static final String TEST_LOG = "./testingLogs/common-modules/integrity-audit/debug.log"; - @Before - public void setUp() throws Exception { - - - System.out.println("setUp: Clearing debug.log"); - FileOutputStream fstream = new FileOutputStream(TEST_LOG); - fstream.close(); - - logger.info("setUp: Entering"); - - IntegrityAudit.setUnitTesting(true); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - /* - * AuditThread.AUDIT_THREAD_SLEEP_INTERVAL is also five seconds, so - * setting AUDIT_PERIOD_SECONDS to 5 ensures that whether or not audit - * has already been run on a node, it will sleep the same amount of - * time. - */ - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - - persistenceUnit = "testPU"; - resourceName = "pdp1"; - - - //Clean up the DB - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - EntityManager 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 - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - em.close(); - logger.info("setUp: Exiting"); - - } - - - @After - public void tearDown() throws Exception { - - logger.info("tearDown: Entering"); - - 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. - */ - //@Ignore - @Test - public void testOneResource() throws Exception { - - logger.info("testOneResource: Entering"); - - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit (15 seconds) - * - * 2) Logic to detect that no other node is available for designation (60 seconds) - * - * 3) pdp1 to run audit again (15 seconds) - */ - logger.info("testOneResource: Sleeping 100 seconds"); - Thread.sleep(100000); - - logger.info("testOneResource: Stopping audit thread"); - integrityAudit.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - - String rName = ""; - while ((strLine = br.readLine()) != null) { - // parse strLine to obtain what you want - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - rName = strLine.substring(startIndex, endIndex); - logger.info("testOneResource: rName: " + rName); - assertEquals("pdp1", rName); - } - } - fstream.close(); - - /* - * 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 (15 seconds) - * - * 2) Logic to detect that no other node is available for designation (60 seconds) - * - * 3) pdp1 to run audit again (15 seconds) - */ - logger.info("testOneResource: Sleeping 100 seconds for second time"); - Thread.sleep(100000); - - logger.info("testOneResource: Stopping audit thread for second time"); - integrityAudit.stopAuditThread(); - - fstream = new FileInputStream(TEST_LOG); - br = new BufferedReader(new InputStreamReader(fstream)); - - rName = ""; - while ((strLine = br.readLine()) != null) { - // parse strLine to obtain what you want - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - rName = strLine.substring(startIndex, endIndex); - logger.info("testOneResource: rName: " + rName); - assertEquals("pdp1", rName); - } - } - fstream.close(); - - 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. A quick way of examining the log is to search for the - * string "audit simulation": - * - * As you can see from the "dbAuditSimulate" method, when it executes, it - * logs the "Starting audit simulation..." message and when it finishes, it - * logs the "Finished audit simulation..." message. By looking for these - * messages, you can verify that the audits are run by the proper resource. - * For example, when testFourResourcesOneDead is run, you should see a - * Starting.../Finished... sequence for pdp1, followed by a - * Starting.../Finished... sequence for pdp2, followed by a - * Starting.../Finished... sequence for pdp4 (pdp3 is skipped as it's - * dead/hung), followed by a Starting.../Finished... sequence for pdp1, etc. - */ - @Ignore - @Test - public void testTwoResources() throws Exception { - - logger.info("testTwoResources: Entering"); - - /* - * Start audit for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Start audit for pdp2. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - integrityAudit2.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit (15 seconds) - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 (30 seconds) - * - * 3) pdp2 to run audit (15 seconds) - * - * 4) Logic to detect that pdp2 is stale and designate pdp1 (30 seconds) - * - * 5) pdp1 to run audit (15 seconds) - */ - Thread.sleep(120000); - - logger.info("testTwoResources: Stopping audit threads"); - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp1")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate: delegates) { - logger.info("testTwoResources: delegate: " + delegate); - } - - fstream.close(); - - assertTrue(expectedResult.equals(delegates)); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 3); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - - logger.info("testTwoResources: Exiting"); - - } - - /* - * Tests designation logic when two functioning resources are in play, each - * with different PUs. Audits for "testPU" and "integrityAuditPU" should run - * simultaneously. Designation should not alternate. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Ignore - @Test - public void testTwoResourcesDifferentPus() throws Exception { - - logger.info("testTwoResourcesDifferentPus: Entering"); - - /* - * Start audit for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Start audit for pdp2. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "integrityAuditPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - integrityAudit2.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 and pdp2 to run audit simultaneously (15 seconds) - * - * 2) Logic to detect that no other node is available for designation for either pdp1 or pdp2 (60 seconds) - * - * 3) pdp1 and pdp2 to again run audit simultaneously (15 seconds) - * - * NOTE: Based on the above, you would think a 100000ms sleep would be appropriate, - * but for some reason, when all tests are run this test errors. - */ - logger.info("testTwoResourcesDifferentPus: Sleeping 80 seconds"); - Thread.sleep(100000); - - logger.info("testTwoResourcesDifferentPus: Stopping audit threads"); - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp1", "pdp2")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate: delegates) { - logger.info("testTwoResourcesDifferentPus: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 4); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - assertTrue("delegate 3 is " + expectedResult.get(3), expectedResult.get(3).equals(delegates.get(3))); - - assertTrue(expectedResult.equals(delegates)); - - 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. - */ - @Ignore - @Test - public void testTwoResourcesOneDead() throws Exception { - - logger.info("testTwoResourcesOneDead: Entering"); - - /* - * Start audit for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Populate DB for pdp2, which will simulate it having registered but then having died. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - new DbDAO(resourceName2, persistenceUnit2, properties2); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit (15 seconds) - * - * 2) Logic to detect that other node, pdp2, is not available for designation (60 seconds) - * - * 3) pdp1 to run audit again (15 seconds) - */ - logger.info("testTwoResourcesOneDead: Sleeping 100 seconds"); - Thread.sleep(100000); - - logger.info("testTwoResourcesOneDead: Stopping audit thread"); - integrityAudit.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp1")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate: delegates) { - logger.info("testTwoResourcesOneDead: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 2); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - - 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. - */ - @Ignore - @Test - public void testThreeResources() throws Exception { - - logger.info("testThreeResources: Entering"); - - /* - * Start audit for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Start audit for pdp2. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - integrityAudit2.startAuditThread(); - - /* - * Start audit for pdp3. - */ - Properties properties3 = new Properties(); - properties3.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties3.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties3.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties3.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit3 = "testPU"; - String resourceName3 = "pdp3"; - IntegrityAudit integrityAudit3 = new IntegrityAudit(resourceName3, persistenceUnit3, properties3); - integrityAudit3.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit (15 seconds) - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 (30 seconds) - * - * 3) pdp2 to run audit (15 seconds) - * - * 4) Logic to detect that pdp2 is stale and designate pdp3 (30 seconds) - * - * 5) pdp3 to run audit (15 seconds) - * - * 6) Logic to detect that pdp3 is stale and designate pdp1 (30 seconds) - * - * 7) pdp1 to run audit (15 seconds) - */ - logger.info("testThreeResources: Sleeping 160 seconds"); - Thread.sleep(160000); - - logger.info("testThreeResources: Stopping threads"); - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - integrityAudit3.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate: delegates) { - logger.info("testThreeResources: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 3); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - assertTrue("delegate 3 is " + expectedResult.get(3), expectedResult.get(3).equals(delegates.get(3))); - - logger.info("testThreeResources: Exiting"); - - } - - /* - * Tests designation logic when four functioning resources are in play, two - * with one PU, two with another. Audits for "testPU" and "integrityAuditPU" 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. - */ - @Ignore - @Test - public void testFourResourcesDifferentPus() throws Exception { - - logger.info("testFourResourcesDifferentPus: Entering"); - - /* - * Start audit for pdp1, testPU. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Start audit for pdp2, integrityAuditPU. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "integrityAuditPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - integrityAudit2.startAuditThread(); - - /* - * Start audit for pdp3, testPU. - */ - Properties properties3 = new Properties(); - properties3.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties3.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties3.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties3.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit3 = "testPU"; - String resourceName3 = "pdp3"; - IntegrityAudit integrityAudit3 = new IntegrityAudit(resourceName3, persistenceUnit3, properties3); - integrityAudit3.startAuditThread(); - - /* - * Start audit for pdp4, integrityAuditPU. - */ - Properties properties4 = new Properties(); - properties4.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties4.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties4.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties4.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties4.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties4.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties4.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit4 = "integrityAuditPU"; - String resourceName4 = "pdp4"; - IntegrityAudit integrityAudit4 = new IntegrityAudit(resourceName4, persistenceUnit4, properties4); - integrityAudit4.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 and pdp2 to run audit simultaneously (15 seconds) - * - * 2) Logic to detect that pdp1 and pdp2 are stale and designate pdp3 (one's counterpart) and pdp4 (two's counterpart) (30 seconds) - * - * 3) pdp3 and pdp4 to run audit simultaneously (15 seconds) - * - * 4) Logic to detect that pdp3 and pdp4 are stale and designate pdp1 (three's counterpart) and pdp2 (four's counterpart) (30 seconds) - * - * 5) pdp1 and pdp2 to run audit simultaneously (15 seconds) - */ - logger.info("testFourResourcesDifferentPus: Sleeping 120 seconds"); - Thread.sleep(120000); - - logger.info("testFourResourcesDifferentPus: Stopping threads"); - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - integrityAudit3.stopAuditThread(); - integrityAudit4.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp4", "pdp1", "pdp2")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate: delegates) { - logger.info("testFourResourcesDifferentPus: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 6); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - assertTrue("delegate 3 is " + expectedResult.get(3), expectedResult.get(3).equals(delegates.get(3))); - assertTrue("delegate 4 is " + expectedResult.get(4), expectedResult.get(4).equals(delegates.get(4))); - assertTrue("delegate 5 is " + expectedResult.get(5), expectedResult.get(5).equals(delegates.get(5))); - - 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. - */ - @Ignore - @Test - public void testFourResourcesOneDead() throws Exception { - - logger.info("testFourResourcesOneDead: Entering"); - - /* - * Start audit for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - integrityAudit.startAuditThread(); - - /* - * Start audit for pdp2. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - integrityAudit2.startAuditThread(); - - /* - * Populate DB for pdp3, which will simulate it having registered but then having died. - */ - Properties properties3 = new Properties(); - properties3.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties3.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties3.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties3.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit3 = "testPU"; - String resourceName3 = "pdp3"; - new DbDAO(resourceName3, persistenceUnit3, properties3); - - /* - * Start audit for pdp4. - */ - Properties properties4 = new Properties(); - properties4.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties4.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties4.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties4.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties4.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties4.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties4.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit4 = "testPU"; - String resourceName4 = "pdp4"; - IntegrityAudit integrityAudit4 = new IntegrityAudit(resourceName4, persistenceUnit4, properties4); - integrityAudit4.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit (15 seconds) - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 (30 seconds) - * - * 3) pdp2 to run audit (15 seconds) - * - * 4) Logic to detect that pdp2 is stale and designate pdp4 (30 seconds) - * - * 5) pdp4 to run audit (15 seconds) - * - * 6) Logic to detect that pdp4 is stale and designate pdp1 (30 seconds) - * - * 7) pdp1 to run audit (15 seconds) - * - * 8) Logic to detect that pdp1 is stale and designate pdp2 (30 seconds) - * - * 7) pdp2 to run audit (15 seconds) - */ - logger.info("testFourResourcesOneDead: Sleeping 210 seconds"); - Thread.sleep(210000); - - logger.info("testFourResourcesOneDead: Stopping threads"); - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - integrityAudit4.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp4", "pdp1", "pdp2", "pdp4")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate : delegates) { - logger.info("testFourResourcesOneDead: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 6); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - assertTrue("delegate 3 is " + expectedResult.get(3), expectedResult.get(3).equals(delegates.get(3))); - assertTrue("delegate 4 is " + expectedResult.get(4), expectedResult.get(4).equals(delegates.get(4))); - assertTrue("delegate 5 is " + expectedResult.get(5), expectedResult.get(5).equals(delegates.get(5))); - - 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. - */ - @Ignore - @Test - public void testFourResourcesThreeDead() throws Exception { - - logger.info("testFourResourcesThreeDead: Entering"); - - /* - * Populate DB for pdp1, which will simulate it having registered but then having died. - */ - new DbDAO(resourceName, persistenceUnit, properties); - - - /* - * Populate DB for pdp2, which will simulate it having registered but then having died. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - new DbDAO(resourceName2, persistenceUnit2, properties2); - - /* - * Start audit for pdp3. - */ - Properties properties3 = new Properties(); - properties3.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties3.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties3.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties3.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit3 = "testPU"; - String resourceName3 = "pdp3"; - IntegrityAudit integrityAudit3 = new IntegrityAudit(resourceName3, persistenceUnit3, properties3); - integrityAudit3.startAuditThread(); - - /* - * Populate DB for pdp4, which will simulate it having registered but then having died. - */ - Properties properties4 = new Properties(); - properties4.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties4.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties4.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties4.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties4.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties4.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties4.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit4 = "testPU"; - String resourceName4 = "pdp4"; - new DbDAO(resourceName4, persistenceUnit4, properties4); - - /* - * Sleep long enough to allow - * - * 1) pdp3 to discover that all other designation candidates are stale (30 seconds) - * - * 1) pdp3 to run audit (15 seconds) - * - * 2) Logic to detect that no other nodes are available for designation (60 seconds) - * - * 3) pdp3 to run audit again (15 seconds) - */ - logger.info("testFourResourcesThreeDead: Sleeping 130 seconds"); - Thread.sleep(130000); - - logger.info("testFourResourcesThreeDead: Stopping thread"); - integrityAudit3.stopAuditThread(); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp3", "pdp3")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - - for (String delegate : delegates) { - logger.info("testFourResourcesThreeDead: delegate: " + delegate); - } - - fstream.close(); - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 2); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - - 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. - */ - @Ignore - @Test - public void testDesignatedNodeDead() throws Exception { - logger.info("testDesignatedNodeDead: Entering"); - - /* - * Instantiate audit object for pdp1. - */ - IntegrityAudit integrityAudit = new IntegrityAudit(resourceName, persistenceUnit, properties); - - /* - * Start audit for pdp2. - */ - Properties properties2 = new Properties(); - properties2.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties2.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit2 = "testPU"; - String resourceName2 = "pdp2"; - IntegrityAudit integrityAudit2 = new IntegrityAudit(resourceName2, persistenceUnit2, properties2); - - /* - * Instantiate audit object for pdp3. - */ - Properties properties3 = new Properties(); - properties3.put(IntegrityAuditProperties.DB_DRIVER, TestUtils.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, TestUtils.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, TestUtils.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, TestUtils.DEFAULT_DB_PWD); - properties3.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties3.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - properties3.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "5"); - String persistenceUnit3 = "testPU"; - String resourceName3 = "pdp3"; - IntegrityAudit integrityAudit3 = new IntegrityAudit(resourceName3, persistenceUnit3, properties3); - - // Start audit on pdp1 - logger.info("testDesignatedNodeDead: Start audit on pdp1"); - integrityAudit.startAuditThread(); - - // Start the auditing threads on other nodes. - logger.info("testDesignatedNodeDead: Start audit on pdp2"); - integrityAudit2.startAuditThread(); - logger.info("testDesignatedNodeDead: Start audit on pdp3"); - integrityAudit3.startAuditThread(); - - - // Kill audit on pdp1 - logger.info("testDesignatedNodeDead: Kill audit on pdp1"); - integrityAudit.stopAuditThread(); - - // Sleep long enough for pdp1 to get stale and pdp2 to take over - logger.info("testDesignatedNodeDead: Sleep long enough for pdp1 to get stale and pdp2 to take over"); - Thread.sleep(AuditThread.AUDIT_COMPLETION_INTERVAL + FUDGE_FACTOR); - - // Start audit thread on pdp1 again. - logger.info("testDesignatedNodeDead: Start audit thread on pdp1 again."); - integrityAudit.startAuditThread(); - - // Sleep long enough for pdp2 to complete its audit and get stale, at - // which point pdp3 should take over - logger.info("testDesignatedNodeDead: Sleep long enough for pdp2 to complete its audit and get stale, at which point pdp3 should take over"); - Thread.sleep((AuditThread.AUDIT_SIMULATION_SLEEP_INTERVAL * AuditThread.AUDIT_SIMULATION_ITERATIONS) - + AuditThread.AUDIT_COMPLETION_INTERVAL + FUDGE_FACTOR); - - // Kill audit on pdp3 - logger.info("testDesignatedNodeDead: Killing audit on pdp3"); - integrityAudit3.stopAuditThread(); - - // Sleep long enough for pdp3 to get stale and pdp1 to take over - logger.info("testDesignatedNodeDead: Sleep long enough for pdp3 to get stale and pdp1 to take over"); - Thread.sleep(AuditThread.AUDIT_COMPLETION_INTERVAL + FUDGE_FACTOR); - - FileInputStream fstream = new FileInputStream(TEST_LOG); - BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); - String strLine; - int startIndex; - int endIndex; - ArrayList<String> expectedResult = new ArrayList<String>(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1")); - ArrayList<String> delegates = new ArrayList<String>(); - while ((strLine = br.readLine()) != null) { - /* parse strLine to obtain what you want */ - if (strLine.contains("Starting audit simulation for resourceName=")) { - startIndex = strLine.indexOf("resourceName=") + 13; - endIndex = strLine.indexOf(","); - - String rName = strLine.substring(startIndex, endIndex); - - delegates.add(rName); - } - } - fstream.close(); - - // Stop remaining threads. - logger.info("testDesignatedNodeDead: Stopping remaining threads"); - integrityAudit.stopAuditThread(); - integrityAudit2.stopAuditThread(); - - for (String delegate: delegates) { - logger.info("testDesignatedNodeDead: delegate: " + delegate); - } - - assertTrue("delegate count only " + delegates.size(), delegates.size() >= 4); - assertTrue("delegate 0 is " + expectedResult.get(0), expectedResult.get(0).equals(delegates.get(0))); - assertTrue("delegate 1 is " + expectedResult.get(1), expectedResult.get(1).equals(delegates.get(1))); - assertTrue("delegate 2 is " + expectedResult.get(2), expectedResult.get(2).equals(delegates.get(2))); - assertTrue("delegate 3 is " + expectedResult.get(3), expectedResult.get(3).equals(delegates.get(3))); - - logger.info("testDesignatedNodeDead: Exiting"); - } -} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/TestUtils.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/TestUtils.java deleted file mode 100644 index 58874d76..00000000 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/TestUtils.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Test Utils - * ================================================================================ - * 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========================================================= - */ -package org.onap.policy.common.ia.test; - -public class TestUtils { - public static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; - public static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/iaTest"; - public static final String DEFAULT_DB_USER = "sa"; - public static final String DEFAULT_DB_PWD = ""; -} diff --git a/integrity-audit/src/test/resources/logback-test.xml b/integrity-audit/src/test/resources/logback-test.xml new file mode 100644 index 00000000..ca57cb4a --- /dev/null +++ b/integrity-audit/src/test/resources/logback-test.xml @@ -0,0 +1,169 @@ +<!-- + ============LICENSE_START======================================================= + Integrity Audit + ================================================================================ + Copyright (C) 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========================================================= + --> + +<!-- 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="defaultPattern" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" /> + <!-- <property name="defaultPattern" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}|%X{RequestId}|%X{ServiceInstanceId}|%thread||%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}||%X{Timer}|%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>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - + %msg%n"</pattern> --> + <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>INFO</level> --> + <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> + + + <!-- ============================================================================ --> + <!-- 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> + +</configuration> @@ -1,22 +1,22 @@ -<!-- - ============LICENSE_START======================================================= - ONAP Policy Engine - Drools PDP +<!-- + ============LICENSE_START======================================================= + ONAP policy ================================================================================ 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========================================================= - --> + ============LICENSE_END========================================================= +--> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> @@ -26,7 +26,7 @@ <groupId>org.onap.oparent</groupId> <artifactId>oparent</artifactId> <version>0.1.1</version> - <relativePath/> + <relativePath /> </parent> <groupId>org.onap.policy.common</groupId> @@ -39,16 +39,28 @@ <description>Common Modules for Policy-Engine in both XACML and Drools flavor</description> <properties> + <!-- Project common build settings --> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> - <logback.version>1.2.3</logback.version> - <javax.persistence.api.version>1.0.2</javax.persistence.api.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + + <!-- Project path properties --> <nexusproxy>https://nexus.onap.org</nexusproxy> - <sitePath>/content/sites/site/${project.groupId}/${project.artifactId}/${project.version}</sitePath> + <sitePath>/content/sites/site/${project.groupId}/${project.artifactId}/${project.version}</sitePath> <releases.path>content/repositories/releases/</releases.path> <snapshots.path>content/repositories/snapshots/</snapshots.path> - <staging.path>content/repositories/staging/</staging.path> + <staging.path>content/repositories/staging/</staging.path> + + <!-- sonar/jacoco overrides --> + <!-- Overriding oparent default sonar/jacoco settings Combine all our reports + into one file shared across sub-modules --> + <sonar.jacoco.reportPath>${project.basedir}/../target/code-coverage/jacoco-ut.exec</sonar.jacoco.reportPath> + <sonar.jacoco.itReportPath>${project.basedir}/../target/code-coverage/jacoco-it.exec</sonar.jacoco.itReportPath> + <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis> + + <!-- Project common dependency versions --> + <logback.version>1.2.3</logback.version> + <javax.persistence.api.version>1.0.2</javax.persistence.api.version> </properties> @@ -68,34 +80,132 @@ </site> </distributionManagement> - <repositories> - <!-- LF repositories --> - <repository> - <id>ecomp-releases</id> - <name>Release Repository</name> - <url>${nexusproxy}/content/repositories/releases/</url> - </repository> - <repository> - <id>ecomp-staging</id> - <name>Staging Repository</name> - <url>${nexusproxy}/content/repositories/staging/</url> - </repository> - <repository> - <id>ecomp-snapshots</id> - <name>Snapshots Repository</name> - <url>${nexusproxy}/content/repositories/snapshots/</url> - </repository> - <repository> - <id>ecomp-public</id> - <name>Public Repository</name> - <url>${nexusproxy}/content/repositories/public/</url> - </repository> - <!-- LF repositories END--> - </repositories> + <repositories> + <!-- LF repositories --> + <repository> + <id>ecomp-releases</id> + <name>Release Repository</name> + <url>${nexusproxy}/content/repositories/releases/</url> + </repository> + <repository> + <id>ecomp-staging</id> + <name>Staging Repository</name> + <url>${nexusproxy}/content/repositories/staging/</url> + </repository> + <repository> + <id>ecomp-snapshots</id> + <name>Snapshots Repository</name> + <url>${nexusproxy}/content/repositories/snapshots/</url> + </repository> + <repository> + <id>ecomp-public</id> + <name>Public Repository</name> + <url>${nexusproxy}/content/repositories/public/</url> + </repository> + <!-- LF repositories END --> + </repositories> <build> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <version>${jacoco.version}</version> + <configuration> + <!-- Note: This exclusion list should match <sonar.exclusions> + property above --> + <excludes> + <exclude>**/gen/**</exclude> + <exclude>**/generated-sources/**</exclude> + <exclude>**/yang-gen/**</exclude> + <exclude>**/pax/**</exclude> + </excludes> + </configuration> + <executions> + <!-- + Prepares the property pointing to the JaCoCo runtime agent which + is passed as VM argument when Maven the Surefire plugin is executed. + --> + <execution> + <id>pre-unit-test</id> + <goals> + <goal>prepare-agent</goal> + </goals> + <configuration> + <destFile>${sonar.jacoco.reportPath}</destFile> + </configuration> + </execution> + <!-- + Ensures that the code coverage report for unit tests is created after + unit tests have been run. + --> + <execution> + <id>post-unit-test</id> + <phase>test</phase> + <goals> + <goal>report</goal> + </goals> + <configuration> + <dataFile>${sonar.jacoco.reportPath}</dataFile> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-checkstyle-plugin</artifactId> + <versionRange>2.17,)</versionRange> + <goals> + <goal>check</goal> + </goals> + </pluginExecutionFilter> + <action> + <ignore /> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + </plugins> + </pluginManagement> <plugins> <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <executions> + <execution> + <id>pre-unit-test</id> + <goals> + <goal>prepare-agent</goal> + </goals> + <configuration> + <destFile>${sonar.jacoco.reportPath}</destFile> + <append>true</append> + </configuration> + </execution> + <execution> + <id>post-unit-test</id> + <phase>test</phase> + <goals> + <goal>report</goal> + </goals> + <configuration> + <dataFile>${sonar.jacoco.reportPath}</dataFile> + </configuration> + </execution> + </executions> + </plugin> + <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <extensions>true</extensions> @@ -113,64 +223,36 @@ </configuration> </plugin> <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-site-plugin</artifactId> - <dependencies> - <dependency> - <groupId>org.apache.maven.wagon</groupId> - <artifactId>wagon-webdav-jackrabbit</artifactId> - <version>2.10</version> - </dependency> - </dependencies> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-site-plugin</artifactId> + <dependencies> + <dependency> + <groupId>org.apache.maven.wagon</groupId> + <artifactId>wagon-webdav-jackrabbit</artifactId> + <version>2.10</version> + </dependency> + </dependencies> </plugin> </plugins> - <pluginManagement> - <plugins> - <plugin> - <groupId>org.eclipse.m2e</groupId> - <artifactId>lifecycle-mapping</artifactId> - <version>1.0.0</version> - <configuration> - <lifecycleMappingMetadata> - <pluginExecutions> - <pluginExecution> - <pluginExecutionFilter> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-checkstyle-plugin</artifactId> - <versionRange>2.17,)</versionRange> - <goals> - <goal>check</goal> - </goals> - </pluginExecutionFilter> - <action> - <ignore /> - </action> - </pluginExecution> - </pluginExecutions> - </lifecycleMappingMetadata> - </configuration> - </plugin> - </plugins> - </pluginManagement> </build> <reporting> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - <version>2.10.4</version> - <configuration> - <failOnError>false</failOnError> - <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> - <docletArtifact> - <groupId>org.umlgraph</groupId> - <artifactId>umlgraph</artifactId> - <version>5.6</version> - </docletArtifact> - <additionalparam>-views</additionalparam> - <useStandardDocletOptions>true</useStandardDocletOptions> - </configuration> - </plugin> - </plugins> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.10.4</version> + <configuration> + <failOnError>false</failOnError> + <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> + <docletArtifact> + <groupId>org.umlgraph</groupId> + <artifactId>umlgraph</artifactId> + <version>5.6</version> + </docletArtifact> + <additionalparam>-views</additionalparam> + <useStandardDocletOptions>true</useStandardDocletOptions> + </configuration> + </plugin> + </plugins> </reporting> </project> diff --git a/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java b/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java index 78be681f..876e6e06 100644 --- a/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java +++ b/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java @@ -52,6 +52,8 @@ import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.onap.policy.common.im.jpa.ResourceRegistrationEntity; import org.onap.policy.common.im.jpa.StateManagementEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.onap.policy.common.im.jmx.ComponentAdminMBean; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; @@ -64,6 +66,8 @@ import org.apache.commons.cli.ParseException; */ public class Main { + private static final Logger logger = LoggerFactory.getLogger(Main.class.getName()); + // table mapping 'resourceName' to 'StateManagmentEntity' static HashMap<String, StateManagementEntity> stateManagementTable = new HashMap<String, StateManagementEntity>(); @@ -597,7 +601,7 @@ public class Main String formatString = sb.toString(); // display column headers - System.out.printf(formatString, (Object[])labels); + logger.info(formatString, (Object[])labels); System.out.printf(formatString, (Object[])underlines); // display all of the rows |