From f8a620d1ff2b0d33b08a22279058f3e0253bdde1 Mon Sep 17 00:00:00 2001 From: Guo Ruijing Date: Fri, 28 Jul 2017 08:21:14 +0000 Subject: [POLICY-71] replace openecomp for policy-common Change-Id: I3241f5d1f0234043b4dff718eda1ffdc48052276 Signed-off-by: Guo Ruijing Signed-off-by: Pamela Dragosh --- README.md | 2 +- common-logging/config/policyLogger.properties | 2 +- common-logging/policyLogger.properties | 2 +- common-logging/pom.xml | 14 +- .../policy/common/logging/ONAPLoggingContext.java | 595 ++++++ .../policy/common/logging/ONAPLoggingUtils.java | 54 + .../policy/common/logging/eelf/Configuration.java | 101 + .../common/logging/eelf/DroolsPDPMDCInfo.java | 53 + .../policy/common/logging/eelf/ErrorCodeMap.java | 111 + .../onap/policy/common/logging/eelf/EventData.java | 106 + .../policy/common/logging/eelf/EventTrackInfo.java | 84 + .../common/logging/eelf/EventTrackInfoHandler.java | 107 + .../onap/policy/common/logging/eelf/MDCInfo.java | 35 + .../policy/common/logging/eelf/MessageCodes.java | 163 ++ .../policy/common/logging/eelf/PolicyLogger.java | 1448 +++++++++++++ .../common/logging/flexlogger/EelfLogger.java | 486 +++++ .../common/logging/flexlogger/FlexLogger.java | 330 +++ .../logging/flexlogger/FlexLoggerTester.java | 81 + .../policy/common/logging/flexlogger/Logger.java | 221 ++ .../policy/common/logging/flexlogger/Logger4J.java | 488 +++++ .../common/logging/flexlogger/LoggerType.java | 30 + .../common/logging/flexlogger/PropertyUtil.java | 403 ++++ .../common/logging/flexlogger/SystemOutLogger.java | 502 +++++ .../policy/common/logging/nsa/LoggingContext.java | 61 + .../common/logging/nsa/LoggingContextFactory.java | 55 + .../common/logging/nsa/SharedLoggingContext.java | 37 + .../common/logging/nsa/impl/SharedContext.java | 58 + .../logging/nsa/impl/Slf4jLoggingContext.java | 71 + .../policy/common/logging/nsa/package-info.java | 27 + .../policy/common/logging/ECOMPLoggingContext.java | 595 ------ .../policy/common/logging/ECOMPLoggingUtils.java | 52 - .../policy/common/logging/eelf/Configuration.java | 101 - .../common/logging/eelf/DroolsPDPMDCInfo.java | 53 - .../policy/common/logging/eelf/ErrorCodeMap.java | 111 - .../policy/common/logging/eelf/EventData.java | 106 - .../policy/common/logging/eelf/EventTrackInfo.java | 84 - .../common/logging/eelf/EventTrackInfoHandler.java | 107 - .../policy/common/logging/eelf/MDCInfo.java | 35 - .../policy/common/logging/eelf/MessageCodes.java | 163 -- .../policy/common/logging/eelf/PolicyLogger.java | 1448 ------------- .../common/logging/flexlogger/EelfLogger.java | 486 ----- .../common/logging/flexlogger/FlexLogger.java | 330 --- .../logging/flexlogger/FlexLoggerTester.java | 81 - .../policy/common/logging/flexlogger/Logger.java | 221 -- .../policy/common/logging/flexlogger/Logger4J.java | 488 ----- .../common/logging/flexlogger/LoggerType.java | 30 - .../common/logging/flexlogger/PropertyUtil.java | 403 ---- .../common/logging/flexlogger/SystemOutLogger.java | 502 ----- .../policy/common/logging/nsa/LoggingContext.java | 61 - .../common/logging/nsa/LoggingContextFactory.java | 55 - .../common/logging/nsa/SharedLoggingContext.java | 37 - .../common/logging/nsa/impl/SharedContext.java | 58 - .../logging/nsa/impl/Slf4jLoggingContext.java | 71 - .../policy/common/logging/nsa/package-info.java | 27 - .../common/logging/eelf/Resources.properties | 245 +++ .../common/logging/eelf/Resources.properties | 245 --- integrity-audit/pom.xml | 8 +- .../org/onap/policy/common/ia/AuditThread.java | 769 +++++++ .../java/org/onap/policy/common/ia/DbAudit.java | 462 +++++ .../onap/policy/common/ia/DbAuditException.java | 37 + .../main/java/org/onap/policy/common/ia/DbDAO.java | 739 +++++++ .../common/ia/DbDaoTransactionException.java | 37 + .../org/onap/policy/common/ia/IntegrityAudit.java | 241 +++ .../policy/common/ia/IntegrityAuditProperties.java | 54 + .../ia/IntegrityAuditPropertiesException.java | 37 + .../policy/common/ia/jpa/IntegrityAuditEntity.java | 203 ++ .../openecomp/policy/common/ia/AuditThread.java | 769 ------- .../org/openecomp/policy/common/ia/DbAudit.java | 462 ----- .../policy/common/ia/DbAuditException.java | 37 - .../java/org/openecomp/policy/common/ia/DbDAO.java | 739 ------- .../common/ia/DbDaoTransactionException.java | 37 - .../openecomp/policy/common/ia/IntegrityAudit.java | 241 --- .../policy/common/ia/IntegrityAuditProperties.java | 54 - .../ia/IntegrityAuditPropertiesException.java | 37 - .../policy/common/ia/jpa/IntegrityAuditEntity.java | 203 -- .../src/main/resources/META-INF/persistence.xml | 6 +- integrity-audit/src/main/resources/logback.xml | 2 +- .../policy/common/ia/test/AuditPeriodTest.java | 480 +++++ .../common/ia/test/DbAuditCompareEntriesTest.java | 617 ++++++ .../onap/policy/common/ia/test/DbAuditTest.java | 753 +++++++ .../org/onap/policy/common/ia/test/DbDAOTest.java | 735 +++++++ .../ia/test/IntegrityAuditDesignationTest.java | 1109 ++++++++++ .../policy/common/ia/test/jpa/IaTestEntity.java | 157 ++ .../onap/policy/common/ia/test/jpa/PersonTest.java | 64 + .../policy/common/ia/test/AuditPeriodTest.java | 480 ----- .../common/ia/test/DbAuditCompareEntriesTest.java | 617 ------ .../policy/common/ia/test/DbAuditTest.java | 753 ------- .../openecomp/policy/common/ia/test/DbDAOTest.java | 735 ------- .../ia/test/IntegrityAuditDesignationTest.java | 1109 ---------- .../policy/common/ia/test/jpa/IaTestEntity.java | 157 -- .../policy/common/ia/test/jpa/PersonTest.java | 64 - integrity-audit/src/test/resources/logback.xml | 2 +- integrity-monitor/pom.xml | 8 +- .../common/im/AdministrativeStateException.java | 37 + .../policy/common/im/ForwardProgressException.java | 37 + .../onap/policy/common/im/IntegrityMonitor.java | 1566 ++++++++++++++ .../common/im/IntegrityMonitorProperties.java | 57 + .../im/IntegrityMonitorPropertiesException.java | 37 + .../policy/common/im/StandbyStatusException.java | 53 + .../onap/policy/common/im/StateChangeNotifier.java | 76 + .../org/onap/policy/common/im/StateElement.java | 158 ++ .../org/onap/policy/common/im/StateManagement.java | 970 +++++++++ .../org/onap/policy/common/im/StateTransition.java | 726 +++++++ .../onap/policy/common/im/jmx/ComponentAdmin.java | 227 ++ .../policy/common/im/jmx/ComponentAdminMBean.java | 50 + .../policy/common/im/jmx/JmxAgentConnection.java | 131 ++ .../common/im/jpa/ForwardProgressEntity.java | 130 ++ .../onap/policy/common/im/jpa/ImTestEntity.java | 140 ++ .../common/im/jpa/ResourceRegistrationEntity.java | 149 ++ .../common/im/jpa/StateManagementEntity.java | 142 ++ .../common/im/AdministrativeStateException.java | 37 - .../policy/common/im/ForwardProgressException.java | 37 - .../policy/common/im/IntegrityMonitor.java | 1566 -------------- .../common/im/IntegrityMonitorProperties.java | 57 - .../im/IntegrityMonitorPropertiesException.java | 37 - .../policy/common/im/StandbyStatusException.java | 53 - .../policy/common/im/StateChangeNotifier.java | 76 - .../openecomp/policy/common/im/StateElement.java | 158 -- .../policy/common/im/StateManagement.java | 970 --------- .../policy/common/im/StateTransition.java | 726 ------- .../policy/common/im/jmx/ComponentAdmin.java | 227 -- .../policy/common/im/jmx/ComponentAdminMBean.java | 50 - .../policy/common/im/jmx/JmxAgentConnection.java | 131 -- .../common/im/jpa/ForwardProgressEntity.java | 130 -- .../policy/common/im/jpa/ImTestEntity.java | 140 -- .../common/im/jpa/ResourceRegistrationEntity.java | 149 -- .../common/im/jpa/StateManagementEntity.java | 142 -- .../src/main/resources/META-INF/persistence.xml | 16 +- integrity-monitor/src/main/resources/logback.xml | 2 +- .../common/im/test/IntegrityMonitorTest.java | 1232 +++++++++++ .../common/im/test/StateManagementEntityTest.java | 193 ++ .../policy/common/im/test/StateManagementTest.java | 321 +++ .../policy/common/im/test/StateTransitionTest.java | 2175 ++++++++++++++++++++ .../common/im/test/IntegrityMonitorTest.java | 1232 ----------- .../common/im/test/StateManagementEntityTest.java | 193 -- .../policy/common/im/test/StateManagementTest.java | 321 --- .../policy/common/im/test/StateTransitionTest.java | 2175 -------------------- integrity-monitor/src/test/resources/logback.xml | 2 +- pom.xml | 28 +- project-configs/maven/conf/settings.xml | 2 +- site-manager/pom.xml | 6 +- site-manager/src/main/files/siteManager | 2 +- .../org/onap/policy/common/sitemanager/Main.java | 609 ++++++ .../openecomp/policy/common/sitemanager/Main.java | 609 ------ 144 files changed, 21714 insertions(+), 21712 deletions(-) create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTester.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java create mode 100644 common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingContext.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingUtils.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/Configuration.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/DroolsPDPMDCInfo.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/ErrorCodeMap.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventData.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfo.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfoHandler.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MDCInfo.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MessageCodes.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/PolicyLogger.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/EelfLogger.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLogger.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLoggerTester.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger4J.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/LoggerType.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/PropertyUtil.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/SystemOutLogger.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContext.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContextFactory.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/SharedLoggingContext.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/SharedContext.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/Slf4jLoggingContext.java delete mode 100644 common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/package-info.java create mode 100644 common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties delete mode 100644 common-logging/src/main/resources/org/openecomp/policy/common/logging/eelf/Resources.properties create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/DbDAO.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java create mode 100644 integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/AuditThread.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/DbAudit.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/DbAuditException.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/DbDAO.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/DbDaoTransactionException.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/IntegrityAudit.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/IntegrityAuditProperties.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/IntegrityAuditPropertiesException.java delete mode 100644 integrity-audit/src/main/java/org/openecomp/policy/common/ia/jpa/IntegrityAuditEntity.java create mode 100644 integrity-audit/src/test/java/org/onap/policy/common/ia/test/AuditPeriodTest.java create mode 100644 integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditCompareEntriesTest.java create mode 100644 integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditTest.java create mode 100644 integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbDAOTest.java create mode 100644 integrity-audit/src/test/java/org/onap/policy/common/ia/test/IntegrityAuditDesignationTest.java create mode 100644 integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/IaTestEntity.java create mode 100644 integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/PersonTest.java delete mode 100644 integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/AuditPeriodTest.java delete mode 100644 integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbAuditCompareEntriesTest.java delete mode 100644 integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbAuditTest.java delete mode 100644 integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbDAOTest.java delete mode 100644 integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/IntegrityAuditDesignationTest.java delete mode 100644 integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/jpa/IaTestEntity.java delete mode 100644 integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/jpa/PersonTest.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java create mode 100644 integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/AdministrativeStateException.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/ForwardProgressException.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/IntegrityMonitor.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/IntegrityMonitorProperties.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/IntegrityMonitorPropertiesException.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/StandbyStatusException.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/StateChangeNotifier.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/StateElement.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/StateManagement.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/StateTransition.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/jmx/ComponentAdmin.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/jmx/ComponentAdminMBean.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/jmx/JmxAgentConnection.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/jpa/ForwardProgressEntity.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/jpa/ImTestEntity.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/jpa/ResourceRegistrationEntity.java delete mode 100644 integrity-monitor/src/main/java/org/openecomp/policy/common/im/jpa/StateManagementEntity.java create mode 100644 integrity-monitor/src/test/java/org/onap/policy/common/im/test/IntegrityMonitorTest.java create mode 100644 integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementEntityTest.java create mode 100644 integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementTest.java create mode 100644 integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateTransitionTest.java delete mode 100644 integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/IntegrityMonitorTest.java delete mode 100644 integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementEntityTest.java delete mode 100644 integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementTest.java delete mode 100644 integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateTransitionTest.java create mode 100644 site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java delete mode 100644 site-manager/src/main/java/org/openecomp/policy/common/sitemanager/Main.java diff --git a/README.md b/README.md index d356e246..75d4b4e1 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ -This source repository contains OpenECOMP common code, which is shared by 'policy-drools-pdp' and 'policy-engine'. The settings file only needs to support the standard Maven repositories (e.g. central = http://repo1.maven.org/maven2/), and any proxy settings needed in your environment. +This source repository contains ONAP common code, which is shared by 'policy-drools-pdp' and 'policy-engine'. The settings file only needs to support the standard Maven repositories (e.g. central = http://repo1.maven.org/maven2/), and any proxy settings needed in your environment. To build it using Maven 3, run: mvn clean install diff --git a/common-logging/config/policyLogger.properties b/common-logging/config/policyLogger.properties index 6aaa6a91..1feed375 100644 --- a/common-logging/config/policyLogger.properties +++ b/common-logging/config/policyLogger.properties @@ -1,6 +1,6 @@ ### # ============LICENSE_START======================================================= -# ECOMP-Logging +# ONAP-Logging # ================================================================================ # Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ diff --git a/common-logging/policyLogger.properties b/common-logging/policyLogger.properties index 7f160b6d..e2335df6 100644 --- a/common-logging/policyLogger.properties +++ b/common-logging/policyLogger.properties @@ -1,6 +1,6 @@ ### # ============LICENSE_START======================================================= -# ECOMP-Logging +# ONAP-Logging # ================================================================================ # Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ diff --git a/common-logging/pom.xml b/common-logging/pom.xml index 73810465..3352d4f6 100644 --- a/common-logging/pom.xml +++ b/common-logging/pom.xml @@ -1,6 +1,6 @@ - org.openecomp.policy.common - ECOMP-Logging + org.onap.policy.common + ONAP-Logging ${project.version} @@ -85,7 +85,7 @@ messages.html - org.openecomp.policy.common.logging.eelf.MessageCodes + org.onap.policy.common.logging.eelf.MessageCodes This needs to be replaced with your Enum class name .which implements EELFResolvableErrorEnum and have your defined error codes. diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java new file mode 100644 index 00000000..bbaf2e0e --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingContext.java @@ -0,0 +1,595 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging; + +//import static org.onap.policy.common.logging.eelf.Configuration.TRANSACTION_BEGIN_TIME_STAMP; +//import static org.onap.policy.common.logging.eelf.Configuration.TRANSACTION_ELAPSED_TIME; +//import static org.onap.policy.common.logging.eelf.Configuration.TRANSACTION_END_TIME_STAMP; + +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import org.slf4j.MDC; + +import org.onap.policy.common.logging.nsa.LoggingContextFactory; +import org.onap.policy.common.logging.nsa.SharedLoggingContext; + +/** + * A facade over the org.onap.policy.common.logging.nsa.SharedLoggingContext interface/implementation that makes it + * more convenient to use. SharedLoggingContext builds on the SLF4J/log4j Mapped Diagnostic Context (MDC) + * feature, which provides a hashmap-based context for data items that need to be logged, where the + * hashmap is kept in ThreadLocal storage. The data items can be referenced in the log4j configuration + * using the EnhancedPatternLayout appender layout class, and the notation "%X{key}" in the ConversionPattern + * string, where "key" is one of the keys in the MDC hashmap (which is determined by what hashmap entries the + * application code creates). Example: + * log4j.appender.auditAppender.layout=org.apache.log4j.EnhancedPatternLayout + * log4j.appender.auditAppender.layout.ConversionPattern=%d|%X{requestId}|%X{serviceInstanceId}|...|%m%n + * where "requestId" and "serviceInstanceId" are entries in the MDC hashmap. + * + * The notable functionality the SharedLoggingContext adds over MDC is that it maintains its own copy + * of the MDC data items in a hashmap (not in ThreadLocal storage), which allows more control of the data. + * The ONAPLoggingContext constructor that takes another ONAPLoggingContext object as a parameter makes + * use of this feature. For example if there is a thread pulling requests from a queue for processing, it + * can keep a base logging context with data that is common to all requests, and for each request, create a + * new logging context with that base context as a parameter; this will create a new logging context with + * those initial values and none of the request-specific values from the previous request such as a request ID. + + * The setter methods in this class set corresponding items in the SharedLoggingContext/MDC hashmaps. + * These items correspond to the fields defined in the "ONAP platform application logging guidelines" + * document. In addition, there is a pair of convenience functions, transactionStarted() and + * transactionEnded(), that can be called at the beginning and end of transaction processing to calculate + * the duration of the transaction and record that value in the "timer" item. + * + */ +public class ONAPLoggingContext { + + private static final String REQUEST_ID = "requestId"; + private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; + private static final String THREAD_ID = "threadId"; + private static final String SERVER_NAME = "serverName"; + private static final String SERVICE_NAME = "serviceName"; + private static final String PARTNER_NAME = "partnerName"; + private static final String STATUS_CODE = "statusCode"; + private static final String TARGET_ENTITY = "targetEntity"; + private static final String TARGET_SERVICE_NAME = "targetServiceName"; + private static final String INSTANCE_UUID = "instanceUuid"; + private static final String SEVERITY = "severity"; + private static final String SERVER_IP_ADDRESS = "serverIpAddress"; + private static final String SERVER = "server"; + private static final String CLIENT_IP_ADDRESS = "clientIpAddress"; + private static final String CLASSNAME = "classname"; + private static final String TRANSACTION_BEGIN_TIME_STAMP = "TransactionBeginTimestamp"; + private static final String TRANSACTION_END_TIME_STAMP = "TransactionEndTimestamp"; + private static final String TRANSACTION_ELAPSED_TIME = "TransactionElapsedTime"; + private static final String METRIC_BEGIN_TIME_STAMP = "MetricBeginTimestamp"; + private static final String METRIC_END_TIME_STAMP = "MetricEndTimestamp"; + private static final String METRIC_ELAPSED_TIME = "MetricElapsedTime"; + + + private static LoggingContextFactory.Builder loggingContextBuilder = new LoggingContextFactory.Builder(); + + protected SharedLoggingContext context = null; +// private long transactionStartTime = 0; + private Instant transactionStartTime; + private Instant metricStartTime; + + /** + * Create a new ONAPLoggingContext with no base context. + */ + public ONAPLoggingContext() { + context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); + } + + /** + * Create a new ONAPLoggingContext initially populated with the values + * in the given base context. This can be used for example in a servlet + * where each incoming request may be processed by a separate thread, but + * there may be some logging data items that will be unchanging and common + * to all the threads. That constant data can be populated in a base + * context, and then each request handler creates new context passing that + * base context to populate the common data in the new one. + * @param baseContext + */ + public ONAPLoggingContext(ONAPLoggingContext baseContext) { + context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); + // a logging context could be passed into a thread (e.g. one that is servicing a queue) + // that already had a logging context established, so the MDC hashmap could contain + // entries that are no longer appropriate; so clear out the MDC hashmap before + // transferring the new logging context values. + // x + MDC.clear(); + baseContext.context.transferTo(context); + transactionStartTime = baseContext.transactionStartTime; + setServiceName("POLICY"); + setPartnerName("USER"); + setStatusCode("COMPLETE"); + setTargetEntity("POLICY"); + setTargetServiceName("PE Process"); + } + + /** + * Indicate the start of transaction processing. The current system time + * will be recorded for use by transactionEnded() to calculate + * the duration of the transaction. + */ + public void transactionStarted() { +// transactionStartTime = System.currentTimeMillis(); + transactionStartTime = Instant.now(); + setTransactionBeginTimestamp(transactionStartTime); + } + + /** + * Indicate the end of transaction processing. The difference between the + * current system time and the time recorded by transactionStarted() + * will be recorded in the data item with key "TransactionElapsedTime". + */ + public void transactionEnded() { + Instant transactionEndTime = Instant.now(); + setTransactionEndTimestamp(transactionEndTime); + setTransactionElapsedTime(transactionEndTime); + } + + /** + * Indicate the start of metric processing. The current system time + * will be recorded for use by metricEnded() to calculate + * the duration of the metric. + */ + public void metricStarted() { +// transactionStartTime = System.currentTimeMillis(); + metricStartTime = Instant.now(); + setMetricBeginTimestamp(metricStartTime); + } + + /** + * Indicate the end of metric processing. The difference between the + * current system time and the time recorded by metricStarted() + * will be recorded in the data item with key "MetricElapsedTime". + */ + public void metricEnded() { + Instant metricEndTime = Instant.now(); + setMetricEndTimestamp(metricEndTime); + setMetricElapsedTime(metricEndTime); + } + + + /** + * Set the value for the data item with key "requestId" + * + * @param id + */ + public void setRequestID(String id) { + context.put(REQUEST_ID, id); + } + /** + * Get the value for the data item with key "requestId" + * @return current value, or empty string if not set + */ + public String getRequestID() { + return context.get(REQUEST_ID, ""); + } + + /** + * Set the value for the data item with key "serviceInstanceId" + * + * @param id + */ + public void setServiceInstanceID(String id) { + context.put(SERVICE_INSTANCE_ID, id); + } + /** + * Get the value for the data item with key "serviceInstanceId" + * @return current value, or empty string if not set + */ + public String getServiceInstanceID() { + return context.get(SERVICE_INSTANCE_ID, ""); + } + + /** + * Set the value for the data item with key "threadId". + * An alternative to using this item is to use the + * %t conversion character in the appender's conversion string. + * + * @param id + */ + public void setThreadID(String id) { + context.put(THREAD_ID, id); + } + /** + * Get the value for the data item with key "threadId" + * @return current value, or empty string if not set + */ + public String getThreadID() { + return context.get(THREAD_ID, ""); + } + + /** + * Set the value for the data item with key "serverName" + * + * @param id + */ + public void setServerName(String name) { + context.put(SERVER_NAME, name); + } + /** + * Get the value for the data item with key "serverName" + * @return current value, or empty string if not set + */ + public String getServerName() { + return context.get(SERVER_NAME, ""); + } + + /** + * Set the value for the data item with key "serviceName" + * + * @param id + */ + public void setServiceName(String name) { + context.put(SERVICE_NAME, name); + } + /** + * Get the value for the data item with key "serviceName" + * @return current value, or empty string if not set + */ + public String getServiceName() { + return context.get(SERVICE_NAME, ""); + } + + /** + * Set the value for the data item with key "partnerName" + * + * @param id + */ + public void setPartnerName(String name) { + context.put(PARTNER_NAME, name); + } + /** + * Get the value for the data item with key "partnerName" + * @return current value, or empty string if not set + */ + public String getPartnerName() { + return context.get(PARTNER_NAME, ""); + } + + /** + * Set the value for the data item with key "statusCode" + * + * @param id + */ + public void setStatusCode(String name) { + context.put(STATUS_CODE, name); + } + /** + * Get the value for the data item with key "statusCode" + * @return current value, or empty string if not set + */ + public String getStatusCode() { + return context.get(STATUS_CODE, ""); + } + + /** + * Set the value for the data item with key "targetEntity" + * + * @param id + */ + public void setTargetEntity(String name) { + context.put(TARGET_ENTITY, name); + } + /** + * Get the value for the data item with key "targetEntity" + * @return current value, or empty string if not set + */ + public String getTargetEntity() { + return context.get(TARGET_ENTITY, ""); + } + + /** + * Set the value for the data item with key "targetServiceName" + * + * @param id + */ + public void setTargetServiceName(String name) { + context.put(TARGET_SERVICE_NAME, name); + } + /** + * Get the value for the data item with key "targetServiceName" + * @return current value, or empty string if not set + */ + public String getTargetServiceName() { + return context.get(TARGET_SERVICE_NAME, ""); + } + + /** + * Set the value for the data item with key "instanceUuid" + * + * @param id + */ + public void setInstanceUUID(String uuid) { + context.put(INSTANCE_UUID, uuid); + } + /** + * Get the value for the data item with key "instanceUuid" + * @return current value, or empty string if not set + */ + public String getInstanceUUID() { + return context.get(INSTANCE_UUID, ""); + } + + /** + * Set the value for the data item with key "severity" + * + * @param id + */ + public void setSeverity(Long severity) { + context.put(SEVERITY, severity); + } + /** + * Get the value for the data item with key "severity" + * @return current value, or empty string if not set + */ + public String getSeverity() { + return context.get(SEVERITY, ""); + } + + /** + * Set the value for the data item with key "serverIp" + * + * @param id + */ + public void setServerIPAddress(String serverIP) { + context.put(SERVER_IP_ADDRESS, serverIP); + } + /** + * Get the value for the data item with key "serverIp" + * @return current value, or empty string if not set + */ + public String getServerIPAddress() { + return context.get(SERVER_IP_ADDRESS, ""); + } + + /** + * Set the value for the data item with key "server" + * + * @param id + */ + public void setServer(String server) { + context.put(SERVER, server); + } + /** + * Get the value for the data item with key "server" + * @return current value, or empty string if not set + */ + public String getServer() { + return context.get(SERVER, ""); + } + + /** + * Set the value for the data item with key "clientIp" + * + * @param id + */ + public void setClientIPAddress(String clientIP) { + context.put(CLIENT_IP_ADDRESS, clientIP); + } + /** + * Get the value for the data item with key "clientIp" + * @return current value, or empty string if not set + */ + public String getClientIPAddress() { + return context.get(CLIENT_IP_ADDRESS, ""); + } + + /** + * Set the value for the data item with key "classname". + * Use of this item is not recommended (unless it is used to + * indicate something other than the Java classname) since + * it would be unwieldy to maintain a correct value across + * calls to/returns from methods in other classes. + * Use of the PatternLayout %c conversion character in the + * conversion string will give a more reliable value. + * + * @param id + */ + public void setClassname(String classname) { + context.put(CLASSNAME, classname); + } + /** + * Get the value for the data item with key "classname" + * @return current value, or empty string if not set + */ + public String getClassname() { + return context.get(CLASSNAME, ""); + } + + /** + * Set the value for the data item with key "timer". + * An alternative to calling this method directly is to call + * transactionStarted() at the start of transaction + * processing and transactionEnded() at the end, + * which will compute the time difference in milliseconds + * and store the result as the "timer" value. + * + * @param id + */ +// public void setTimer(Long timer) { +// context.put(TIMER, timer); +// } + +// public void setTimer(Long elapsedtime) { +// String unit = " milliseconds"; +// context.put(TRANSACTION_ELAPSED_TIME, elapsedtime + unit); +// } + + /** + * Get the value for the data item with key "timer" + * @return current value, or 0 if not set + */ +// public long getTimer() { +// return context.get(TRANSACTION_ELAPSED_TIME, 0); +// } + + /** + * Set the value for the data item with key "TransactionBeginTimestamp" + * + * @param id + */ + public void setTransactionBeginTimestamp(Instant transactionStartTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(transactionStartTime)); + context.put(TRANSACTION_BEGIN_TIME_STAMP, formatedTime ); + } + + /** + * Get the value for the data item with key "TransactionBeginTimestamp" + * @return current value, or 0 if not set + */ + public long getTransactionBeginTimestamp() { + return context.get(TRANSACTION_BEGIN_TIME_STAMP, 0); + } + + /** + * Set the value for the data item with key "TransactionEndTimestamp" + * + * @param id + */ + public void setTransactionEndTimestamp(Instant transactionEndTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(transactionEndTime)); + context.put(TRANSACTION_END_TIME_STAMP, formatedTime ); + } + + /** + * Get the value for the data item with key "TransactionEndTimestamp" + * @return current value, or 0 if not set + */ + public long getTransactionEndTimestamp() { + return context.get(TRANSACTION_END_TIME_STAMP, 0); + } + + /** + * Set the value for the data item with key "TransactionElapsedTime". + * An alternative to calling this method directly is to call + * transactionStarted() at the start of transaction + * processing and transactionEnded() at the end, + * which will compute the time difference in milliseconds + * and store the result as the "ns" value. + * + * @param id + */ + + public void setTransactionElapsedTime(Instant transactionEndTime) { + long ns = Duration.between(transactionStartTime, transactionEndTime).toMillis(); + //String unit = " Seconds"; + //if(ns == 1){ + //unit = " Second"; + //} + + //if(ns < 1){ + //ns = Duration.between(transactionStartTime, transactionEndTime).toMillis(); + //unit = " milliseconds"; + //} + context.put(TRANSACTION_ELAPSED_TIME, ns); // + unit); + } + + /** + * Get the value for the data item with key "TransactionElapsedTime" + * @return current value, or 0 if not set + */ + public long getTransactionElapsedTime() { + return context.get(TRANSACTION_ELAPSED_TIME, 0); + } + + /** + * Set the value for the data item with key "MetricBeginTimestamp" + * + * @param id + */ + public void setMetricBeginTimestamp(Instant metricStartTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(metricStartTime)); + context.put(METRIC_BEGIN_TIME_STAMP, formatedTime ); + } + + /** + * Get the value for the data item with key "MetricBeginTimestamp" + * @return current value, or 0 if not set + */ + public long getMetricBeginTimestamp() { + return context.get(METRIC_BEGIN_TIME_STAMP, 0); + } + + /** + * Set the value for the data item with key "MetricEndTimestamp" + * + * @param id + */ + public void setMetricEndTimestamp(Instant metricEndTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(metricEndTime)); + context.put(METRIC_END_TIME_STAMP, formatedTime ); + } + + /** + * Get the value for the data item with key "MetricEndTimestamp" + * @return current value, or 0 if not set + */ + public long getMetricEndTimestamp() { + return context.get(METRIC_END_TIME_STAMP, 0); + } + + /** + * Set the value for the data item with key "MetricElapsedTime". + * An alternative to calling this method directly is to call + * metricStarted() at the start of metric + * processing and metricEnded() at the end, + * which will compute the time difference in milliseconds + * and store the result as the "ns" value. + * + * @param id + */ + + public void setMetricElapsedTime(Instant metricEndTime) { + long ns = Duration.between(metricStartTime, metricEndTime).toMillis(); + //String unit = " Seconds"; + //if(ns == 1){ + //unit = " Second"; + //} + + //if(ns < 1){ + //ns = Duration.between(metricStartTime, metricEndTime).toMillis(); + //unit = " milliseconds"; + //} + context.put(METRIC_ELAPSED_TIME, ns); // + unit); + } + + /** + * Get the value for the data item with key "MetricElapsedTime" + * @return current value, or 0 if not set + */ + public long getMetricElapsedTime() { + return context.get(METRIC_ELAPSED_TIME, 0); + } + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java new file mode 100644 index 00000000..b4d4d8d2 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/ONAPLoggingUtils.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging; + +import javax.servlet.http.HttpServletRequest; + +public class ONAPLoggingUtils { + + public static ONAPLoggingContext getLoggingContextForRequest(HttpServletRequest request, + ONAPLoggingContext baseContext) + { + ONAPLoggingContext requestContext = new ONAPLoggingContext(baseContext); + if (request.getLocalAddr() != null) { // may be null in junit tests + requestContext.setServerIPAddress(request.getLocalAddr()); + } + // get client IP address as leftmost address in X-Forwarded-For header if present, + // otherwise from remote address in the request + String forwarded = request.getHeader("X-Forwarded-For"); + if (forwarded != null && forwarded.trim().length() > 0) { + forwarded = forwarded.trim().split(",")[0]; + requestContext.setClientIPAddress(forwarded); + } else if (request.getRemoteAddr() != null) { // may be null in junit tests + requestContext.setClientIPAddress(request.getRemoteAddr()); + } + // RequestID + // This needs to be renamed to ONAP when the other components in ONAP + // rename to this. + String requestId = request.getHeader("X-ECOMP-RequestID"); + if (requestId != null && requestId.trim().length() > 0) { + requestContext.setRequestID(requestId); + } + return requestContext; + } + + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java new file mode 100644 index 00000000..4cbe63af --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/Configuration.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + + +public interface Configuration extends com.att.eelf.configuration.Configuration{ + + /** + * The Date-time of the start of a transaction + */ + public String BEGIN_TIME_STAMP = "BeginTimestamp"; + + /** + * The Date-time of the end of transaction + */ + public String END_TIME_STAMP = "EndTimestamp"; + + /** + * Externally advertised API invoked by clients of this component + */ + public String SERVICE_NAME = "ServiceName"; + + /** + * Client or user invoking the API + */ + public String PARTNER_NAME = "PartnerName"; + + /** + * Target Entity + */ + public String TARGET_ENTITY = "TargetEntity"; + + /** + * Target service name + */ + public String TARGET_SERVICE_NAME = "TargetServiceName"; + + /** + * High level success or failure (COMPLETE or ERROR) + */ + public String STATUS_CODE = "StatusCode"; + + /** + * Application specific response code + */ + public String RESPONSE_CODE = "ResponseCode"; + + /** + * Human readable description of the application specific response code + */ + public String RESPONSE_DESCRIPTION = "ResponseDescription"; + + /** + * Externally advertised API invoked by clients of this component + */ + public String ELAPSED_TIME = "ElapsedTime"; + + /** + * High level failure (ERROR) + */ + public String ERROR_CATEGORY = "ErrorCategory"; + + /** + * Error Code + */ + public String ERROR_CODE = "ErrorCode"; + + /** + * Error Description + */ + public String ERROR_DESCRIPTION = "ErrorDesciption"; + + /** + * Class name + */ + public String CLASS_NAME = "ClassName"; + + /** + * Server name + */ + public String SERVER_NAME = "ServerName"; + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java new file mode 100644 index 00000000..01fc0ddd --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPDPMDCInfo.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import java.util.concurrent.ConcurrentHashMap; + +public class DroolsPDPMDCInfo implements MDCInfo{ + + private static ConcurrentHashMap mdcMap = new ConcurrentHashMap(); + + static { + + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.MDC_REMOTE_HOST, ""); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.MDC_SERVICE_NAME, "Policy.droolsPdp"); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.MDC_SERVICE_INSTANCE_ID, "Policy.droolsPdp.event"); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.MDC_INSTANCE_UUID, ""); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.MDC_ALERT_SEVERITY, ""); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.PARTNER_NAME, "N/A"); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.STATUS_CODE, "N/A"); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.RESPONSE_CODE, "N/A"); + mdcMap.put(org.onap.policy.common.logging.eelf.Configuration.RESPONSE_DESCRIPTION, "N/A"); + + } + + @Override + /** + * @return the instance of ConcurrentHashMap + */ + public ConcurrentHashMap getMDCInfo() { + + return mdcMap; + } + + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java new file mode 100644 index 00000000..cbb8c7a3 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import java.util.HashMap; + +/** + * + * ErrorCodeMap contains a HashMap of ErrorCodeInfo (error code and error description) + * + */ +public class ErrorCodeMap { + + + public static HashMap hm = new HashMap(); + + private static String ERROR_PERMISSIONS = "POLICY-100E"; + private static String ERROR_PERMISSIONS_DESCRIPTION = "This is a Permissions Error. Please check the error message for detail information"; + + private static String ERROR_SCHEMA_INVALID = "POLICY-400E"; + private static String ERROR_SCHEMA_INVALID_DESCRIPTION = "This is an Invalid Schema Error. Please check the error message for detail information"; + + private static String UPDATE_ERROR = "POLICY-502E"; + private static String UPDATE_ERROR_DESCRIPTION = "This is an updating error. Please check the error message for detail information"; + + private static String EXCEPTION_ERROR_CODE = "POLICY-503E"; + private static String EXCEPTION_ERROR_DESCRIPTION = "This is an exception error message during the process. Please check the error message for detail information"; + + private static String MISS_PROPERTY_ERROR = "POLICY-504E"; + private static String MISS_PROPERTY_ERROR_DESCRIPTION = "This is an error of missing properties. Please check the error message for detail information"; + + private static String GENERAL_ERROR_CODE = "POLICY-515E"; + private static String GENERAL_ERROR_DESCRIPTION = "This is a general error message during the process. Please check the error message for detail information"; + + private static String ERROR_SYSTEM_ERROR = "POLICY-516E"; + private static String ERROR_SYSTEM_ERROR_DESCRIPTION = "This is a System Error. Please check the error message for detail information"; + + private static String ERROR_DATA_ISSUE = "POLICY-517E"; + private static String ERROR_DATA_ISSUE_DESCRIPTION = "This is a Data Issue Error. Please check the error message for detail information"; + + private static String ERROR_PROCESS_FLOW = "POLICY-518E"; + private static String ERROR_PROCESS_FLOW_DESCRIPTION = "This is a Process Flow Error. Please check the error message for detail information"; + + private static String ERROR_UNKNOWN = "POLICY-519E"; + private static String ERROR_UNKNOWN_DESCRIPTION = "This is an Unknown Error. Please check the error message for detail information"; + + private static String ERROR_AUDIT = "POLICY-520E"; + private static String ERROR_AUDIT_DESCRIPTION = "This is an audit Error. Please check the error message for detail information"; + + static { + hm.put(MessageCodes.EXCEPTION_ERROR, new ErrorCodeInfo(EXCEPTION_ERROR_CODE, EXCEPTION_ERROR_DESCRIPTION)); + hm.put(MessageCodes.GENERAL_ERROR, new ErrorCodeInfo(GENERAL_ERROR_CODE, GENERAL_ERROR_DESCRIPTION)); + hm.put(MessageCodes.MISS_PROPERTY_ERROR, new ErrorCodeInfo(MISS_PROPERTY_ERROR, MISS_PROPERTY_ERROR_DESCRIPTION)); + hm.put(MessageCodes.UPDATE_ERROR, new ErrorCodeInfo(UPDATE_ERROR, UPDATE_ERROR_DESCRIPTION)); + hm.put(MessageCodes.ERROR_SYSTEM_ERROR, new ErrorCodeInfo(ERROR_SYSTEM_ERROR, ERROR_SYSTEM_ERROR_DESCRIPTION)); + hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); + hm.put(MessageCodes.ERROR_PERMISSIONS, new ErrorCodeInfo(ERROR_PERMISSIONS, ERROR_PERMISSIONS_DESCRIPTION)); + hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); + hm.put(MessageCodes.ERROR_PROCESS_FLOW, new ErrorCodeInfo(ERROR_PROCESS_FLOW, ERROR_PROCESS_FLOW_DESCRIPTION)); + hm.put(MessageCodes.ERROR_SCHEMA_INVALID, new ErrorCodeInfo(ERROR_SCHEMA_INVALID, ERROR_SCHEMA_INVALID_DESCRIPTION)); + hm.put(MessageCodes.ERROR_UNKNOWN, new ErrorCodeInfo(ERROR_UNKNOWN, ERROR_UNKNOWN_DESCRIPTION)); + hm.put(MessageCodes.ERROR_AUDIT, new ErrorCodeInfo(ERROR_AUDIT, ERROR_AUDIT_DESCRIPTION)); + } + + static class ErrorCodeInfo { + + private String errorCode; + private String errorDesc; + + public ErrorCodeInfo(String errorCode, String errorDesc){ + this.errorCode = errorCode; + this.errorDesc = errorDesc; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getErrorDesc() { + return errorDesc; + } + + public void setErrorDesc(String errorDesc) { + this.errorDesc = errorDesc; + } + + } + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java new file mode 100644 index 00000000..2aaa1146 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import java.time.Instant; + +/** + * + * EventData can be used for logging a rule event. + * + */ +public class EventData { + + private String requestID = null; + private Instant startTime = null; + private Instant endTime = null; + + public EventData() { + + } + + public EventData(String requestID, Instant startTime, Instant endTime) { + + this.requestID = requestID; + this.startTime = startTime; + this.endTime = endTime; + } + + public String getRequestID() { + return requestID; + } + + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + public Instant getStartTime() { + return startTime; + } + + public void setStartTime(Instant startTime) { + this.startTime = startTime; + } + + public Instant getEndTime() { + return endTime; + } + + public void setEndTime(Instant endTime) { + this.endTime = endTime; + } + + public String toString(){ + return requestID + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((requestID == null) ? 0 : requestID.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (obj instanceof String) { + String requestId = (String) obj; + if(requestID != null && requestID.equals(requestId)){ + return true; + } + return false; + } + if (getClass() != obj.getClass()) + return false; + EventData other = (EventData) obj; + if (requestID == null) { + if (other.requestID != null) + return false; + } else if (!requestID.equals(other.requestID)) + return false; + return true; + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java new file mode 100644 index 00000000..7e4d45d8 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * EventTrackInfo contains a ConcurrentHashMap of EventData + * + */ +public class EventTrackInfo { + + private ConcurrentHashMap eventInfo = null; + + public EventTrackInfo() { + /* + * An initial capacity of 16 ensures the number of elements before resizing happens + * Load factor of 0,9 ensures a dense packaging inside ConcurrentHashMap which will optimize memory use + * ConcurencyLevel set to 1 will ensure that only one shard is created and maintained + */ + eventInfo = new ConcurrentHashMap(16, 0.9f, 1); + } + + /** + * Returns an instance of EventData associated to this requestID + * @param requestID + * @return EventData + */ + public EventData getEventDataByRequestID(String requestID){ + return eventInfo.get(requestID); + } + + /** + * Stores an EventData object in a ConcurrentHashMap using its requestID as key. + * @param event + */ + public void storeEventData(EventData event){ + + if(event == null || event.getRequestID() == null || event.getRequestID().isEmpty()){ + return; + } + //in case override the start time, check the original event was already stored or not + if(!eventInfo.containsKey(event.getRequestID())){ + eventInfo.put(event.getRequestID(), event); + } + } + + /** + * Removes an EventData object from a ConcurrentHashMap using the eventId as key. + * @param eventId + */ + public void remove(String eventId){ + if(eventInfo != null){ + eventInfo.remove(eventId); + } + } + + /** + * Returns a ConcurrentHashMap of EventData + */ + public ConcurrentHashMap getEventInfo() { + return eventInfo; + } + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java new file mode 100644 index 00000000..d0a7cc16 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.TimerTask; + +/** + * + * EventTrackInfoHandler is the handler of clean up all expired event objcts + * + */ +public class EventTrackInfoHandler extends TimerTask { + + String className = this.getClass().getSimpleName(); + + @Override + public void run() { + + PolicyLogger.info(className + + " Release expired event records start..."); + + CleanUp(); + + PolicyLogger.info(className + " Release expired event records done"); + } + + /** + * Removes all expired event objects from the ConcurrentHashMap of EventData + */ + private void CleanUp() { + + if (PolicyLogger.getEventTracker() == null + || PolicyLogger.getEventTracker().getEventInfo() == null + || PolicyLogger.getEventTracker().getEventInfo().isEmpty()) { + return; + } + + Instant startTime = null; + long ns = 0; + + ArrayList expiredEvents = null; + + for (String key: PolicyLogger.getEventTracker().getEventInfo().keySet()) { + EventData event = PolicyLogger.getEventTracker().getEventInfo().get(key); + startTime = event.getStartTime(); + ns = Duration.between(startTime, Instant.now()).getSeconds(); + + PolicyLogger.info(className + + " duration time : " + ns); + + PolicyLogger.info(className + + " PolicyLogger.EXPIRED_TIME : " + PolicyLogger.EXPIRED_TIME); + + // if longer than EXPIRED_TIME, remove the object + + if (ns > PolicyLogger.EXPIRED_TIME){ + if (expiredEvents == null) { + expiredEvents = new ArrayList(); + } + expiredEvents.add(key); + + PolicyLogger.info(className + + " add expired event request ID: " + + event.getRequestID()); + } + } + + synchronized (PolicyLogger.getEventTracker().getEventInfo()) { + if (expiredEvents != null) { + for (String expiredKey : expiredEvents) { + PolicyLogger.getEventTracker().getEventInfo() + .remove(expiredKey); + System.out.println(className + + " removed expired event request ID: " + + expiredKey); + PolicyLogger.info(className + + " removed expired event request ID: " + + expiredKey); + } + } + + } + + } + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java new file mode 100644 index 00000000..fc44dcff --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MDCInfo.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * Interface needs to be implemented by DroolsPDPMDCInfo + * + */ + +public interface MDCInfo { + + public ConcurrentHashMap getMDCInfo(); + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java new file mode 100644 index 00000000..a9920aec --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +/** + * + * MessageCodes contains all the messagge codes for EELF logging messages + * + */ +public enum MessageCodes implements EELFResolvableErrorEnum { + // Below is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants + // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java + + ERROR_PERMISSIONS, + + ERROR_SYSTEM_ERROR, + + ERROR_DATA_ISSUE, + + ERROR_SCHEMA_INVALID, + + ERROR_PROCESS_FLOW, + + ERROR_UNKNOWN, + + ERROR_AUDIT, + + // Above is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants + // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java + + //----------------------5000-5099 Business/Flow Processing Related --------------------/ + + BAD_TYPE_WARNING, + + GENERAL_INFO, + + GENERAL_WARNING, + + MISS_PROPERTY_ERROR, + + EXCEPTION_ERROR, + + MISS_PROPERTY_INFO, + + RULE_AUDIT_EXEC_INFO, + + RULE_AUDIT_BEGIN_INFO, + + RULE_AUDIT_END_INFO, + + RULE_AUDIT_START_END_INFO, + + RULE_METRICS_INFO, + + UEB_AUDIT_EXEC_INFO, + + UEB_AUDIT_BEGIN_INFO, + + UEB_AUDIT_END_INFO, + + UPDATE_ERROR, + + GENERAL_ERROR, + + //----------------------New enums should be added above this line ------------------------------------------------------------------/ + + //--------------------- The enums below are old code. They should not be used since 1607 release and eventually will be removed -----/ + /** + * Application message which requires no arguments + */ + MESSAGE_SAMPLE_NOARGS, + + /** + * Application message which requires one argument {0} + */ + MESSAGE_SAMPLE_ONEARGUMENT, + + /** + * Audit message which requires one argument {0} + */ + AUDIT_MESSAGE_ONEARGUMENT, + + /** + * Error message which requires one argument {0} + */ + ERROR_MESSAGE_ONEARGUMENT, + + /** + * Metrics message which requires one argument {0} + */ + METRICS_MESSAGE_ONEARGUMENT, + + /** + * Debug message which requires one argument {0} + */ + DEBUG_MESSAGE_ONEARGUMENT, + + /** + * Application message which requires two argument {0} and another argument {1} + */ + MESSAGE_SAMPLE_TWOARGUMENTS, + + /** + * Sample error exception + */ + MESSAGE_SAMPLE_EXCEPTION, + + /** + * Sample warning message + */ + MESSAGE_WARNING_SAMPLE, + + /** + * Sample exception in method {0} + */ + MESSAGE_SAMPLE_EXCEPTION_ONEARGUMENT, + + /** + * Sample trace message + */ + MESSAGE_TRACE_SAMPLE, + + /** + * Sample error message + */ + MESSAGE_ERROR_SAMPLE; + + + /** + * Static initializer to ensure the resource bundles for this class are loaded... + * Here this application loads messages from three bundles + */ + static { + EELFResourceManager.loadMessageBundle("org.onap.policy/common/logging/eelf/Resources"); + String id = EELFResourceManager.getIdentifier(RULE_AUDIT_EXEC_INFO); + String value = EELFResourceManager.getMessage(RULE_AUDIT_EXEC_INFO); + + System.out.println("*********************** " + id); + System.out.println("*********************** " + value); + + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java new file mode 100644 index 00000000..d0cc9c1e --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java @@ -0,0 +1,1448 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.eelf; + +import org.slf4j.MDC; + +import static org.onap.policy.common.logging.eelf.Configuration.*; + +import org.onap.policy.common.logging.flexlogger.LoggerType; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.configuration.EELFManager; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.Iterator; +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * + * PolicyLogger contains all the static methods for EELF logging + * + */ +public class PolicyLogger { + + private static EELFLogger errorLogger = EELFManager.getInstance() + .getErrorLogger(); + + private static EELFLogger metricsLogger = EELFManager.getInstance() + .getMetricsLogger(); + + private static EELFLogger auditLogger = EELFManager.getInstance() + .getAuditLogger(); + + private static EELFLogger debugLogger = EELFManager.getInstance() + .getDebugLogger(); + + private static EventTrackInfo eventTracker = new EventTrackInfo(); + + private static String hostName = null; + private static String hostAddress = null; + private static String component = null; + + private static TimerTask ttrcker = null; + private static boolean isEventTrackerRunning = false; + private static Timer timer = null; + + //Default:Timer initial delay and the delay between in milliseconds before task is to be execute + private static int TIMER_DELAY_TIME = 1000; + + //Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task executions + private static int CHECK_INTERVAL = 30 * 1000; + + //Default:longest time an event info can be stored in the concurrentHashMap for logging - in seconds + static int EXPIRED_TIME = 60*60*1000*24; //one day + + //Default:the size of the concurrentHashMap which stores the event starting time - when its size reaches this limit, the Timer get executed + private static int CONCURRENTHASHMAP_LIMIT = 5000; + + //Default:the size of the concurrentHashMap which stores the event starting time - when its size drops to this point, stop the Timer + private static int STOP_CHECK_POINT = 2500; + + private static boolean isOverrideLogbackLevel = false; + + public static Level DEBUG_LEVEL = Level.INFO; + public static Level AUDIT_LEVEL = Level.INFO; + public static Level METRICS_LEVEL = Level.INFO; + public static Level ERROR_LEVEL = Level.ERROR; + public static String CLASS_NAME = "ClassName"; + + + static{ + if (hostName == null || hostAddress == null) { + try { + hostName = InetAddress.getLocalHost().getHostName(); + hostAddress = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger", "UnknownHostException"); + } + } + } + + /** + * Populates MDC info + * @param transId + * @return String + */ + public static String postMDCInfoForEvent(String transId) { + MDC.clear(); + + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + + if(component != null && component.equalsIgnoreCase("DROOLS")){ + MDC.put(TARGET_ENTITY, "POLICY"); + MDC.put(TARGET_SERVICE_NAME, "drools evaluate rule"); + return postMDCInfoForEvent(transId, new DroolsPDPMDCInfo()); + } else { + // For Xacml + MDC.put(TARGET_ENTITY, "POLICY"); + MDC.put(TARGET_SERVICE_NAME, "PE Process"); + } + + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, transId); + MDC.put(MDC_SERVICE_NAME, "Policy.xacmlPdp"); + MDC.put(MDC_SERVICE_INSTANCE_ID, "Policy.xacmlPdp.event"); + try { + MDC.put(MDC_SERVER_FQDN, hostName); + MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); + } catch (Exception e) { + errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger"); + } + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + long ns = Duration.between(startTime, endTime).toMillis(); // use millisecond as default and remove unit from log + //String unit = " Seconds"; + //if(ns == 1){ + //unit = " Second"; + //} + + //if(ns < 1){ + //ns = Duration.between(startTime, endTime).toMillis(); + //unit = " milliseconds"; + //} + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime ); + + //set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); + + MDC.put(PARTNER_NAME, "N/A"); + + MDC.put(STATUS_CODE, "COMPLETE"); + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + + return transId; + + } + + /** + * Populate MDC Info using the passed in mdcInfo + * @param transId + * @param mdcInfo + * @return String + */ + private static String postMDCInfoForEvent(String transId, MDCInfo mdcInfo ) { + + MDC.put(MDC_KEY_REQUEST_ID, transId); + if(mdcInfo != null && mdcInfo.getMDCInfo() != null && !mdcInfo.getMDCInfo().isEmpty()){ + + ConcurrentHashMap mdcMap = mdcInfo.getMDCInfo(); + Iterator keyIterator = mdcMap.keySet().iterator(); + String key = ""; + + while(keyIterator.hasNext()){ + key = keyIterator.next(); + MDC.put(key, mdcMap.get(key)); + } + } + + try { + MDC.put(MDC_SERVER_FQDN, hostName); + MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); + } catch (Exception e) { + errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger"); + } + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + long ns = Duration.between(startTime, endTime).toMillis(); // use millisecond as default and remove unit from log + //String unit = " Seconds"; + //if(ns == 1){ + //unit = " Second"; + //} + + //if(ns < 1){ + //ns = Duration.between(startTime, endTime).toMillis(); + //unit = " milliseconds"; + //} + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime ); + + //set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); + + return transId; + } + + /** + * Set Timestamps for start, end and duration of logging a transaction + */ + private static void seTimeStamps(){ + + Instant startTime = Instant.now(); + Instant endTime = Instant.now(); + long ns = Duration.between(startTime, endTime).toMillis(); + //String unit = " Seconds"; + //if(ns == 1){ + //unit = " Second"; + //} + + //if(ns < 1){ + //ns = Duration.between(startTime, endTime).toMillis(); + //unit = " milliseconds"; + //} + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime ); + + //set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); + + MDC.put(PARTNER_NAME, "N/A"); + + MDC.put(STATUS_CODE, "COMPLETE"); + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + } + + /** + * Sets transaction Id to MDC + * @param transId + */ + public static void setTransId(String transId){ + + MDC.put(MDC_KEY_REQUEST_ID, transId); + } + + /** + * Returns current transaction Id used in MDC + * @return transId + */ + public static String getTransId(){ + + return MDC.get(MDC_KEY_REQUEST_ID); + } + + /** + * Sets transaction Id to MDC + * @param o + */ + public static void postMDCInfoForEvent(Object o){ + postMDCInfoForEvent(""+o); + } + + /** + * Resets transaction Id in MDC for the rule triggered by this event + * @param transId + * @return String + */ + public static String postMDCInfoForTriggeredRule(String transId) { + + MDC.clear(); + + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + MDC.put(MDC_REMOTE_HOST, ""); + MDC.put(MDC_KEY_REQUEST_ID, transId); + MDC.put(MDC_SERVICE_NAME, "Policy.droolsPdp"); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + try { + MDC.put(MDC_SERVER_FQDN, hostName); + MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); + } catch (Exception e) { + errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger"); + } + MDC.put(MDC_INSTANCE_UUID, ""); + MDC.put(MDC_ALERT_SEVERITY, ""); + MDC.put(STATUS_CODE, "COMPLETE"); + + return transId; + + } + + /** + * Resets transaction Id in MDC for the rule triggered by this event + * @param o + */ + public static void postMDCUUIDForTriggeredRule(Object o) { + + postMDCInfoForTriggeredRule("" + o); + + } + + // ************************************************************************************************ + /** + * Records the Info event with String [] arguments + * @param msg + * @param arguments + */ + public static void info(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + debugLogger.info(msg, arguments); + } + + /** + * Records the Info event with String [] arguments + * @param msg + * @param className + * @param arguments + */ + public static void info(MessageCodes msg, String className, String... arguments) { + MDC.put(CLASS_NAME, className); + debugLogger.info(msg, arguments); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void info( String className, String arg0) { + MDC.put(CLASS_NAME, className); + debugLogger.info(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message without its class name passed in + * @param arg0 + */ + public static void info(String arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.info(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void info(Object arg0) { + MDC.put(CLASS_NAME, ""); + info(arg0); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void info(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.info(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void info(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.info(msg, arguments2); + } + + /** + * Records only one String message with its class name + * @param arg0 log message + * @param className class name + */ + public static void warn( String className, String arg0) { + MDC.put(CLASS_NAME, className); + debugLogger.warn(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void warn(Object arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.warn(MessageCodes.GENERAL_WARNING, "" + arg0); + } + + /** + * Records only one String message without its class name passed in + * @param arg0 + */ + public static void warn(String arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.warn(MessageCodes.GENERAL_WARNING, arg0); + } + + /** + * Records a message with passed in message code and a list of string values + * @param msg + * @param arguments + */ + public static void warn(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + debugLogger.warn(msg, arguments); + } + + /** + * Records a message with passed in message code, class name and a list of string values + * @param msg + * @param className + * @param arguments + */ + public static void warn(MessageCodes msg, String className, String... arguments) { + MDC.put(CLASS_NAME, className); + debugLogger.warn(msg, arguments); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void warn(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.warn(msg, arguments2); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void warn(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + debugLogger.warn(msg, arguments2); + } + + /** + * Records only one String message with its class name + * @param className class name + * @param arg0 log message + */ + public static void error( String className, String arg0) { + MDC.put(CLASS_NAME, className); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void error(String arg0) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void error(Object arg0) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0); + } + + /** + * Records a message with passed in message code, Throwable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void error(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(msg) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); + + } + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void error(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(msg) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); + + } + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code and a list of string values + * @param msg + * @param arguments + */ + public static void error(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(msg) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); + + } + errorLogger.error(msg, arguments); + } + + /** + * Records a message with passed in message code and a list of string values + * @param msg + * @param arguments + */ + public static void debug(MessageCodes msg, String... arguments) { + MDC.put(CLASS_NAME, ""); + debugLogger.debug(msg, arguments); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void debug( String className, String arg0) { + MDC.put(CLASS_NAME, className); + debugLogger.debug(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void debug(String arg0) { + MDC.put(CLASS_NAME, ""); + debugLogger.debug(arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void debug(Object arg0) { + + MDC.put(CLASS_NAME, ""); + debugLogger.debug("" + arg0); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void audit(String className, Object arg0) { + MDC.put(STATUS_CODE, "COMPLETE"); + MDC.put(CLASS_NAME, className); + auditLogger.info("" + arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void audit(Object arg0) { + MDC.put(STATUS_CODE, "COMPLETE"); + MDC.put(CLASS_NAME, ""); + auditLogger.info("" + arg0); + } + + /** + * Records a message with passed in message code, hrowable object, a list of string values + * @param msg + * @param arg0 + * @param arguments + */ + public static void debug(MessageCodes msg, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, ""); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + + /** + * Records a message with passed in message code, class name, Throwable object, a list of string values + * @param msg + * @param className + * @param arg0 + * @param arguments + */ + public static void debug(MessageCodes msg, String className, Throwable arg0, + String... arguments) { + MDC.put(CLASS_NAME, className); + String arguments2 = getNormalizedStackTrace(arg0, arguments); + errorLogger.error(msg, arguments2); + } + /** + * returns true for enabled, false for not enabled + */ + public static boolean isDebugEnabled(){ + + return debugLogger.isDebugEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isErrorEnabled(){ + + return errorLogger.isErrorEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isWarnEnabled(){ + + return debugLogger.isWarnEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isInfoEnabled1(){ + + return debugLogger.isInfoEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isAuditEnabled(){ + + return debugLogger.isInfoEnabled(); + } + + /** + * returns true for enabled, false for not enabled + */ + public static boolean isInfoEnabled(){ + + return debugLogger.isInfoEnabled(); + } + + /** + * Records only one String message with its class name + * @param className + * @param arg0 + */ + public static void trace( String className, String arg0) { + MDC.put(CLASS_NAME, className); + errorLogger.info(MessageCodes.GENERAL_INFO, arg0); + } + + /** + * Records only one String message + * @param arg0 + */ + public static void trace(Object arg0){ + + MDC.put(CLASS_NAME, ""); + debugLogger.trace(""+arg0); + } + /** + * Records the starting time of the event with its request Id as the key + * @param eventId + */ + public static void recordAuditEventStart(String eventId) { + + MDC.put(STATUS_CODE, "COMPLETE"); + postMDCInfoForEvent(eventId); + + if(eventTracker == null){ + eventTracker = new EventTrackInfo(); + } + EventData event = new EventData(); + event.setRequestID(eventId); + event.setStartTime(Instant.now()); + eventTracker.storeEventData(event); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + debugLogger.info("CONCURRENTHASHMAP_LIMIT : " + CONCURRENTHASHMAP_LIMIT); + //--- Tracking the size of the concurrentHashMap, if it is above limit, keep EventTrack Timer running + int size = eventTracker.getEventInfo().size(); + + debugLogger.info("EventInfo concurrentHashMap Size : " + size + " on " + new Date()); + debugLogger.info("isEventTrackerRunning : " + isEventTrackerRunning); + + if( size >= CONCURRENTHASHMAP_LIMIT){ + + + if(!isEventTrackerRunning){ + + startCleanUp(); + isEventTrackerRunning = true; + } + + }else if( size <= STOP_CHECK_POINT){ + + if(isEventTrackerRunning){ + stopCleanUp(); + } + } + } + + /** + * Records the starting time of the event with its request Id as the key + * @param eventId + */ + public static void recordAuditEventStart(UUID eventId) { + + if(eventId == null){ + return; + } + + if(eventTracker == null){ + eventTracker = new EventTrackInfo(); + } + + recordAuditEventStart(eventId.toString()); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + */ + public static void recordAuditEventEnd(String eventId, String rule) { + + if(eventTracker == null){ + return; + } + if(eventId == null){ + return; + } + + creatAuditEventTrackingRecord(eventId, rule, ""); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + * @param policyVersion + */ + public static void recordAuditEventEnd(String eventId, String rule , String policyVersion) { + + if(eventTracker == null){ + return; + } + if(eventId == null){ + return; + } + + creatAuditEventTrackingRecord(eventId, rule, policyVersion); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + * @param policyVersion + */ + public static void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + + if(eventId == null){ + return; + } + + recordAuditEventEnd(eventId.toString(), rule, policyVersion); + + } + + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + */ + public static void recordAuditEventEnd(UUID eventId, String rule) { + + if(eventId == null){ + return; + } + + recordAuditEventEnd(eventId.toString(), rule); + + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + * @param policyVersion + */ + public static void creatAuditEventTrackingRecord(String eventId, String rule, String policyVersion) { + + if(eventTracker == null){ + return; + } + + EventData event = eventTracker.getEventDataByRequestID(eventId); + + if(event != null){ + Instant endTime = event.getEndTime(); + if(endTime == null){ + endTime = Instant.now(); + } + MDC.put(STATUS_CODE, "COMPLETE"); + recordAuditEventStartToEnd(eventId, rule, event.getStartTime(), endTime, policyVersion); + } + } + + /** + * Records the ending time of the event with its request Id as the key + * @param eventId + * @param rule + */ + public static void creatAuditEventTrackingRecord(UUID eventId, String rule) { + + if(eventId == null){ + return; + } + + if(eventTracker == null){ + return; + } + + EventData event = eventTracker.getEventDataByRequestID(eventId.toString()); + + if(event != null){ + Instant endTime = event.getEndTime(); + if(endTime == null){ + endTime = Instant.now(); + } + + recordAuditEventStartToEnd(eventId.toString(), rule, event.getStartTime(), endTime, "N/A"); + } + } + + public static EventTrackInfo getEventTracker() { + return eventTracker; + } + + /** + * Records the audit with an event starting and ending times + * @param eventId + * @param rule + * @param startTime + * @param endTime + * @param policyVersion + */ + public static void recordAuditEventStartToEnd(String eventId, String rule, Instant startTime, Instant endTime, String policyVersion) { + + if(startTime == null || endTime == null){ + return; + } + String serviceName = MDC.get(MDC_SERVICE_NAME); + if(eventId != null && !eventId.isEmpty()){ + MDC.put(MDC_KEY_REQUEST_ID, eventId); + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + + String formatedTime = sdf.format(Date.from(startTime)); + MDC.put(BEGIN_TIME_STAMP, formatedTime ); + + //set default values for these required fields below, they can be overridden + formatedTime = sdf.format(Date.from(endTime)); + MDC.put(END_TIME_STAMP, formatedTime); + + MDC.put(RESPONSE_CODE, "N/A"); + MDC.put(RESPONSE_DESCRIPTION, "N/A"); + + long ns = Duration.between(startTime, endTime).toMillis(); + //String unit = " Seconds"; + //if(ns == 1){ + //unit = " Second"; + //} + + //if(ns < 1){ + //ns = Duration.between(startTime, endTime).toMillis(); + //unit = " milliseconds"; + //} + + MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); + + auditLogger.info(MessageCodes.RULE_AUDIT_START_END_INFO, + serviceName, rule, startTime.toString(), endTime.toString(), Long.toString(ns), policyVersion); + + //--- remove the record from the concurrentHashMap + if(eventTracker != null){ + if(eventTracker.getEventDataByRequestID(eventId) != null){ + eventTracker.remove(eventId); + debugLogger.info("eventTracker.remove(" + eventId + ")"); + } + } + } + + /** + * Records the metrics with an event Id and log message + * @param eventId + * @param arg1 + */ + public static void recordMetricEvent(String eventId, String arg1) { + + seTimeStamps(); + + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, + serviceName, arg1); + + } + + /** + * Records the metrics with an event Id, class name and log message + * @param eventId + * @param className + * @param arg1 + */ + public static void recordMetricEvent(String eventId, String className,String arg1) { + + seTimeStamps(); + + MDC.put(CLASS_NAME, className); + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, + serviceName, arg1); + } + + /** + * Records the metrics with an event Id and log message + * @param eventId + * @param arg1 + */ + public static void recordMetricEvent(UUID eventId, String arg1) { + + if(eventId == null){ + return; + } + String serviceName = MDC.get(MDC_SERVICE_NAME); + MDC.put(MDC_KEY_REQUEST_ID, eventId.toString()); + metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, + serviceName, arg1); + } + + /** + * Records a String message for metrics logs + * @param arg0 + */ + public static void recordMetricEvent(String arg0) { + seTimeStamps(); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, arg0); + } + + + /** + * Records the metrics event with a String message + * @param arg0 + */ + public static void metrics(String arg0) { + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, arg0); + } + + /** + * Records the metrics event with a class name and a String message + * @param arg0 + */ + public static void metrics(String className, Object arg0) { + seTimeStamps(); + MDC.put(CLASS_NAME, className); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, ""+arg0); + } + + /** + * Records the metrics event with a String message + * @param arg0 + */ + public static void metrics(Object arg0) { + seTimeStamps(); + MDC.put(CLASS_NAME, ""); + String serviceName = MDC.get(MDC_SERVICE_NAME); + metricsLogger.info(MessageCodes.RULE_METRICS_INFO, + serviceName, ""+arg0); + } + + /** + * Records the metrics event with a String message + * @param arg0 + */ + public static void metricsPrintln(String arg0) { + MDC.clear(); + metricsLogger.info(arg0); + } + + /** + * Removes all the return lines from the printStackTrace + * @param t + * @param arguments + */ + private static String getNormalizedStackTrace (Throwable t, String...arguments) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + String newStValue = sw.toString().replace ('|', '!').replace ("\n", " - "); + int curSize = (arguments == null ? 0 : arguments.length); + StringBuffer newArgument = new StringBuffer(); + for(int i=0; i 0){ + + TIMER_DELAY_TIME = timerDelayTime; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the timer.delay.time, so use its default value: " + TIMER_DELAY_TIME); + } + + if (checkInterval > 0){ + + CHECK_INTERVAL = checkInterval; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the check.interval, so use its default value: " + CHECK_INTERVAL); + } + + if (expiredDate > 0){ + + EXPIRED_TIME = expiredDate; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the event.expired.time, so use its default value: " + EXPIRED_TIME); + } + + if (concurrentHashMapLimit > 0){ + + CONCURRENTHASHMAP_LIMIT = concurrentHashMapLimit; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the concurrentHashMap.limit, so use its default value: " + CONCURRENTHASHMAP_LIMIT); + } + + if (stopCheckPoint > 0){ + + STOP_CHECK_POINT = stopCheckPoint; + + }else { + MDC.put(ERROR_CATEGORY, "ERROR"); + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the stop.check.point, so use its default value: " + STOP_CHECK_POINT); + } + + if (loggerType != null){ + + if (loggerType.equalsIgnoreCase("EELF")){ + + logger_type = LoggerType.EELF; + + }else if (loggerType.equalsIgnoreCase("LOG4J")){ + + logger_type = LoggerType.LOG4J; + + }else if (loggerType.equalsIgnoreCase("SYSTEMOUT")){ + + logger_type = LoggerType.SYSTEMOUT; + + } + + } + + if (debugLevel != null && !debugLevel.isEmpty()){ + + DEBUG_LEVEL = Level.valueOf(debugLevel); + + } + //Only check if it is to turn off or not + if (errorLevel != null && errorLevel.equalsIgnoreCase(Level.OFF.toString())){ + + ERROR_LEVEL = Level.valueOf(errorLevel); + + } + //Only check if it is to turn off or not + if (metricsLevel != null && metricsLevel.equalsIgnoreCase(Level.OFF.toString())){ + + METRICS_LEVEL = Level.valueOf(metricsLevel); + + } + //Only check if it is to turn off or not + if (auditLevel != null && auditLevel.equalsIgnoreCase(Level.OFF.toString())){ + + AUDIT_LEVEL = Level.valueOf(auditLevel); + + } + + }catch(Exception e){ + MDC.put(ERROR_CATEGORY, "ERROR"); + + if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ + MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); + MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); + + } + errorLogger.error("failed to get the policyLogger.properties, so use their default values",e); + } + + return logger_type; + + } + + /** + * Sets Debug Level + */ + public static void setDebugLevel(String debugLevel){ + + if(isOverrideLogbackLevel){ + PolicyLogger.DEBUG_LEVEL = Level.valueOf(debugLevel); + debugLogger.setLevel(DEBUG_LEVEL); + } + + } + + /** + * Sets Error OFF or ON + */ + public static void setErrorLevel(String errorLevel){ + + if(isOverrideLogbackLevel){ + if(errorLevel != null && errorLevel.equalsIgnoreCase("OFF")){ + PolicyLogger.ERROR_LEVEL = Level.OFF; + errorLogger.setLevel(ERROR_LEVEL); + }else{ + //--- set default value + errorLogger.setLevel(Level.ERROR); + PolicyLogger.ERROR_LEVEL = Level.ERROR; + } + } + } + + /** + * Sets Metrics OFF or ON + */ + public static void setMetricsLevel(String metricsLevel){ + + if(isOverrideLogbackLevel){ + if(metricsLevel != null && metricsLevel.equalsIgnoreCase("OFF")){ + PolicyLogger.METRICS_LEVEL = Level.OFF; + metricsLogger.setLevel(METRICS_LEVEL); + }else { + //--- set default value + metricsLogger.setLevel(Level.INFO); + PolicyLogger.METRICS_LEVEL = Level.INFO; + } + } + + } + + /** + * Sets Audit OFF or ON + */ + public static void setAuditLevel(String auditLevel){ + + if(isOverrideLogbackLevel){ + if(auditLevel != null && auditLevel.equalsIgnoreCase("OFF")){ + PolicyLogger.AUDIT_LEVEL = Level.OFF; + auditLogger.setLevel(AUDIT_LEVEL); + }else { + //--- set default value + auditLogger.setLevel(Level.INFO); + PolicyLogger.AUDIT_LEVEL = Level.INFO; + } + } + } + + /** + * Returns true for overriding logback levels; returns false for not + */ + public static boolean isOverrideLogbackLevel(){ + + return isOverrideLogbackLevel; + } + + /** + * Sets true for overriding logback levels; sets false for not + */ + public static void setOverrideLogbackLevel(boolean odl){ + + isOverrideLogbackLevel = odl; + + } + /** + * Sets server information to MDC + */ + public static void setServerInfo(String serverHost, String serverPort){ + MDC.put(SERVER_NAME, serverHost+":"+serverPort); + } + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java new file mode 100644 index 00000000..fbc0ae1d --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java @@ -0,0 +1,486 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +import java.io.Serializable; +import java.util.UUID; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import com.att.eelf.configuration.EELFLogger.Level; + +/** + * + * EelfLogger implements all the methods of interface Logger by calling PolicyLogger methods + * + */ + +public class EelfLogger implements Logger, Serializable { + + /** + * + */ + private static final long serialVersionUID = 5385586713941277192L; + private String className = ""; + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor + * @param clazz + */ + public EelfLogger(Class clazz) { + if(clazz != null){ + className = clazz.getName(); + } + PolicyLogger.postMDCInfoForEvent(null); + } + + /** + * Constructor + * @param s + */ + public EelfLogger(String s) { + if(s != null){ + className = s; + } + PolicyLogger.postMDCInfoForEvent(null); + } + + /** + * Constructor + * @param clazz + * @param isNewTransaction + */ + public EelfLogger(Class clazz, boolean isNewTransaction) { + if(clazz != null){ + className = clazz.getName(); + } + if(isNewTransaction){ + transId = PolicyLogger.postMDCInfoForEvent(null); + }else{ + transId = PolicyLogger.getTransId(); + } + } + + /** + * Constructor + * @param s + * @param isNewTransaction + */ + public EelfLogger(String s, boolean isNewTransaction) { + if(s != null){ + className = s; + } + if(isNewTransaction){ + transId = PolicyLogger.postMDCInfoForEvent(null); + }else{ + transId = PolicyLogger.getTransId(); + } + } + + /** + * Constructor + * @param clazz + * @param transId + */ + public EelfLogger(Class clazz, String transId) { + if(clazz != null){ + className = clazz.getName(); + } + PolicyLogger.postMDCInfoForEvent(transId); + } + + /** + * Constructor + * @param s + * @param transId + */ + public EelfLogger(String s, String transId) { + if(s != null){ + className = s; + } + PolicyLogger.postMDCInfoForEvent(transId); + } + + /** + * Sets transaction Id for logging + * @param transId + */ + @Override + public void setTransId(String transId){ + + PolicyLogger.setTransId(transId); + this.transId = transId; + } + + /** + * Returns transaction Id for logging + */ + @Override + public String getTransId(){ + return transId; + } + + /** + * Records a message + * @param message + */ + @Override + public void debug(Object message) { + PolicyLogger.debug(className, ""+message); + } + + /** + * Records an error message + * @param message + */ + @Override + public void error(Object message) { + PolicyLogger.error(className, ""+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void info(Object message) { + PolicyLogger.info(className, ""+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void warn(Object message) { + PolicyLogger.warn(className, ""+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void trace(Object message) { + PolicyLogger.trace(className, ""+message); + } + + /** + * Returns true for debug enabled, or false for not + * @return boolean + */ + @Override + public boolean isDebugEnabled(){ + return PolicyLogger.isDebugEnabled(); + } + + /** + * Returns true for info enabled, or false for not + * @return boolean + */ + @Override + public boolean isInfoEnabled(){ + return PolicyLogger.isInfoEnabled(); + } + + /** + * Returns true for warn enabled, or false for not + * @return boolean + */ + @Override + public boolean isWarnEnabled(){ + return PolicyLogger.isWarnEnabled(); + } + + /** + * Returns true for error enabled, or false for not + * @return boolean + */ + @Override + public boolean isErrorEnabled(){ + return PolicyLogger.isErrorEnabled(); + } + + /** + * Returns true for audit enabled, or false for not + * @return boolean + */ + @Override + public boolean isAuditEnabled(){ + if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Returns true for metrics enabled, or false for not + * @return boolean + */ + @Override + public boolean isMetricsEnabled(){ + if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Returns true for trace enabled, or false for not + * @return boolean + */ + @Override + public boolean isTraceEnabled(){ + return PolicyLogger.isDebugEnabled(); + } + + /** + * Records an audit message + * @param arg0 + */ + @Override + public void audit(Object arg0) { + PolicyLogger.audit(className, ""+ arg0); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void debug(Object message, Throwable t) { + PolicyLogger.debug(MessageCodes.GENERAL_INFO, t, message.toString()); + } + + /** + * Records an error message + * @param message + * @param t + */ + @Override + public void error(Object message, Throwable t) { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, t, message.toString()); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void info(Object message, Throwable t) { + PolicyLogger.info(MessageCodes.GENERAL_INFO, t, message.toString()); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void warn(Object message, Throwable t) { + PolicyLogger.warn(MessageCodes.GENERAL_WARNING, t, message.toString()); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void trace(Object message, Throwable t) { + PolicyLogger.trace(message); + } + + /** + * Records an audit message + * @param arg0 + * @param t + */ + @Override + public void audit(Object arg0, Throwable t) { + PolicyLogger.audit(arg0); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(String eventId) { + PolicyLogger.recordAuditEventStart(eventId); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(UUID eventId) { + PolicyLogger.recordAuditEventStart(eventId); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + PolicyLogger.recordAuditEventEnd(eventId, rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + PolicyLogger.recordAuditEventEnd(eventId, rule); + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(String eventId, String arg1) { + PolicyLogger.recordMetricEvent(eventId, arg1); + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(UUID eventId, String arg1) { + PolicyLogger.recordMetricEvent(eventId, arg1); + } + + /** + * Records a metrics message + * @param arg0 + */ + @Override + public void metrics(Object arg0) { + PolicyLogger.metrics(className, arg0); + } + + /** + * Records an error message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void error(MessageCodes msg, Throwable arg0, String... arguments){ + PolicyLogger.error(msg, className, arg0, arguments); + } + + /** + * Records an error message + * @param msg + * @param arguments + */ + @Override + public void error(MessageCodes msg, String... arguments){ + PolicyLogger.error(msg, arguments); + } + + /** + * Populates MDC Info + * @param transId + */ + @Override + public String postMDCInfoForEvent(String transId) { + return PolicyLogger.postMDCInfoForEvent(transId); + + } + + /** + * Records a message + * @param msg + * @param arguments + */ + @Override + public void warn(MessageCodes msg, String... arguments){ + PolicyLogger.warn(msg, className, arguments); + } + + /** + * Records a message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void warn(MessageCodes msg, Throwable arg0, String... arguments){ + PolicyLogger.warn(msg, className, arg0, arguments); + } + + /** + * Populates MDC Info for the rule triggered + * @param transId + */ + @Override + public void postMDCInfoForTriggeredRule(String transId){ + PolicyLogger.postMDCInfoForTriggeredRule(transId); + } + + /** + * Populates MDC Info + * @param o + */ + @Override + public void postMDCInfoForEvent(Object o){ + PolicyLogger.postMDCInfoForEvent(o); + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java new file mode 100644 index 00000000..797f857b --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java @@ -0,0 +1,330 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.Date; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener; + +/** + * + * FlexLogger acts as factory to generate instances of Logger based on logger type + * + */ +public class FlexLogger extends SecurityManager{ + + private static LoggerType loggerType = LoggerType.EELF; + private static ConcurrentHashMap logger4JMap = new ConcurrentHashMap(); + private static ConcurrentHashMap eelfLoggerMap = new ConcurrentHashMap(); + private static ConcurrentHashMap systemOutMap = new ConcurrentHashMap(); + //--- init logger first + static { + loggerType = initlogger(); + } + + /** + * Returns an instance of Logger + * @param clazz + */ + static public Logger getLogger(Class clazz) { + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(clazz, false); + break; + case LOG4J: + logger = getLog4JLogger(clazz); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger + * @param s + */ + static public Logger getLogger(String s) { + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(null,false); + break; + case LOG4J: + logger = getLog4JLogger(s); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger + * @param clazz + * @param isNewTransaction + */ + static public Logger getLogger(Class clazz, boolean isNewTransaction) { + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(clazz, isNewTransaction); + break; + case LOG4J: + logger = getLog4JLogger(clazz); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + + } + + /** + * Returns an instance of Logger + * @param s + * @param isNewTransaction + */ + static public Logger getLogger(String s, boolean isNewTransaction) { + Logger logger = null; + System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); + switch (loggerType) { + + case EELF: + logger = getEelfLogger(null, isNewTransaction); + break; + case LOG4J: + logger = getLog4JLogger(s); + break; + case SYSTEMOUT: + logger = getSystemOutLogger(null); + break; + } + + return logger; + } + + /** + * Returns the calling class name + */ + public String getClassName(){ + System.out.println("getClassContext()[3].getName() " + getClassContext()[3].getName()); + return getClassContext()[3].getName(); + } + + /** + * Returns an instance of Logger4J + * @param clazz + */ + private static Logger4J getLog4JLogger(Class clazz){ + String className = new FlexLogger().getClassName(); + + if(!logger4JMap.containsKey(className)){ + //for 1610 release use the default debug.log for log4j + Logger4J logger = new Logger4J("debugLogger", className); + logger4JMap.put(className, logger); + } + + return logger4JMap.get(className); + } + + /** + * Returns an instance of Logger4J + * @param s + */ + private static Logger4J getLog4JLogger(String s){ + String className = new FlexLogger().getClassName(); + + if(!logger4JMap.containsKey(className)){ + Logger4J logger = new Logger4J(s, className); + logger4JMap.put(className, logger); + } + + return logger4JMap.get(className); + } + + /** + * Returns an instance of EelfLogger + * @param clazz + * @param isNewTransaction + */ + private static EelfLogger getEelfLogger(Class clazz, boolean isNewTransaction){ + + String className = ""; + EelfLogger logger = null; + if(clazz != null){ + className = clazz.getName(); + }else{ + className = new FlexLogger().getClassName(); + } + + if(!eelfLoggerMap.containsKey(className)){ + logger = new EelfLogger(clazz, isNewTransaction); + eelfLoggerMap.put(className, logger); + }else{ + logger = eelfLoggerMap.get(className); + if(logger == null){ + logger = new EelfLogger(clazz, isNewTransaction); + eelfLoggerMap.put(className, logger); + } + //installl already created but it is new transaction + if(isNewTransaction){ + String transId = PolicyLogger.postMDCInfoForEvent(null); + logger.setTransId(transId); + } + } + System.out.println("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className); + return logger; + } + + /** + * Returns an instance of SystemOutLogger + * @param clazz + */ + private static SystemOutLogger getSystemOutLogger(Class clazz){ + + String className = new FlexLogger().getClassName(); + + if(!systemOutMap.containsKey(className)){ + SystemOutLogger logger = new SystemOutLogger(className); + systemOutMap.put(className, logger); + } + + return systemOutMap.get(className); + } + + /** + * loads the logger properties + */ + private static LoggerType initlogger() { + LoggerType loggerType = LoggerType.EELF; + String overrideLogbackLevel = "FALSE"; + String loggerTypeString = ""; + Properties properties = null; + + try { + properties = PropertyUtil.getProperties("config/policyLogger.properties"); + System.out.println("FlexLogger:properties => " + properties); + + if(properties != null) { + overrideLogbackLevel = properties.getProperty("override.logback.level.setup"); + System.out.println("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel); + loggerTypeString = properties.getProperty("logger.type"); + if (loggerTypeString != null){ + if (loggerTypeString.equalsIgnoreCase("EELF")){ + loggerType = LoggerType.EELF; + if (overrideLogbackLevel != null && + overrideLogbackLevel.equalsIgnoreCase("TRUE")) { + System.out.println("FlexLogger: start listener."); + properties = PropertyUtil.getProperties + ("config/policyLogger.properties", + new PropertiesCallBack("FlexLogger-CallBack")); + } + }else if (loggerTypeString.equalsIgnoreCase("LOG4J")){ + loggerType = LoggerType.LOG4J; + }else if (loggerTypeString.equalsIgnoreCase("SYSTEMOUT")){ + loggerType = LoggerType.SYSTEMOUT; + } + + System.out.println("FlexLogger.logger_Type value: " + loggerTypeString); + } + } + } catch (IOException e1) { + System.out.println("initlogger" + e1); + } finally { + // OK to pass no properties (null) + loggerType = PolicyLogger.init(properties); + } + + return loggerType; + } + + /** + * PropertiesCallBack is listening any updates on the policyLogger.properties + */ + static public class PropertiesCallBack implements Listener { + String name; + + public PropertiesCallBack(String name) { + this.name = name; + } + + /** + * This method will be called automatically if he policyLogger.properties got updated + */ + public void propertiesChanged(Properties properties, + Set changedKeys) { + + String debugLevel = properties.getProperty("debugLogger.level"); + String metricsLevel = properties.getProperty("metricsLogger.level"); + String auditLevel = properties.getProperty("audit.level"); + String errorLevel = properties.getProperty("error.level"); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); + Instant startTime = Instant.now(); + String formatedTime = sdf.format(Date.from(startTime)); + System.out.println("FlexLogger.propertiesChanged : called at time : " + formatedTime); + System.out.println("FlexLogger.propertiesChanged : debugLevel : " + debugLevel); + + if (changedKeys != null) { + + if (changedKeys.contains("debugLogger.level")) { + PolicyLogger.setDebugLevel(debugLevel); + } + + if (changedKeys.contains("metricsLogger.level")) { + PolicyLogger.setMetricsLevel(metricsLevel); + } + + if (changedKeys.contains("error.level")) { + PolicyLogger.setErrorLevel(errorLevel); + } + + if (changedKeys.contains("audit.level")) { + PolicyLogger.setAuditLevel(auditLevel); + } + } + } + } + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTester.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTester.java new file mode 100644 index 00000000..eddece12 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTester.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +import java.util.UUID; + +public class FlexLoggerTester { + + + public void testLogging(){ + + // get an instance of logger + Logger logger = FlexLogger.getLogger(FlexLoggerTester.class); + + //logger.info("this is a testing of FlexLogger with logger type:" + FlexLogger.loggerType); + + logger.info("logger.isAuditEnabled():" + logger.isAuditEnabled()); + logger.info("logger.isDebugEnabled():" + logger.isDebugEnabled()); + logger.info("logger.isErrorEnabled():" + logger.isErrorEnabled()); + logger.info("logger.isInfoEnabled():" + logger.isInfoEnabled()); + logger.info("logger.isMetricsEnabled():" + logger.isMetricsEnabled()); + logger.info("logger.isWarnEnabled():" + logger.isWarnEnabled()); + + if(logger.isDebugEnabled()) + logger.debug("this is from logger.debug call"); + else + logger.info("this is from logger.info call"); + + if(logger.isMetricsEnabled()) logger.metrics("this is from logger.metrics call"); + + logger.error("this is from logger.error call"); + if(logger.isAuditEnabled()) + logger.audit("this is from logger.audit call"); + else{ + logger.audit("shouldn't see this line in audit log"); + logger.info("shouldn't see this line in audit log"); + } + + if(logger.isMetricsEnabled()) + logger.metrics("this is from logger.metrics call"); + else{ + logger.metrics("shouldn't see this line in metrics log"); + logger.info("shouldn't see this line in metrics log"); + } + + if(logger.isErrorEnabled()) { + logger.error("this is from logger.error call"); + }else{ + logger.error("shouldn't see this logger.error call in error.log"); + logger.info("error is not enabled"); + } + + logger.info("logger.isDebugEnabled() returned value:" + logger.isDebugEnabled()); + logger.recordAuditEventEnd("123345456464998", "from recordAuditEventEnd call", "12345"); + logger.recordAuditEventEnd(UUID.randomUUID(), "from recordAuditEventEnd call", "abcdf"); + logger.recordAuditEventStart("from recordAuditEventStart call"); + logger.recordAuditEventStart(UUID.randomUUID().toString()); + logger.recordMetricEvent("123345456464998", "from recordMetricEvent call"); + logger.recordMetricEvent(UUID.randomUUID(), "from recordMetricEvent call"); + logger.trace("from trace call"); + + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java new file mode 100644 index 00000000..d3113d31 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java @@ -0,0 +1,221 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +import java.util.UUID; + +import org.onap.policy.common.logging.eelf.MessageCodes; + +/** + * + * Interface Logger - implemented by Logger4J, EelfLogger and SystemOutLogger + * + */ +public interface Logger { + + /** + * Prints messages with the level.DEBUG + */ + public void debug(Object message); + + /** + * Prints messages with the level.ERROR + */ + public void error(Object message); + + /** + * Prints messages with the level.ERROR + */ + public void error(MessageCodes msg, Throwable arg0, String... arguments); + + /** + * Prints messages with the level.INFO + */ + public void info(Object message); + + /** + * Prints messages with the level.WARN + */ + public void warn(Object message); + + /** + * Prints messages with the level.TRACE + */ + public void trace(Object message); + + /** + * Prints messages in audit log with the level.INFO + */ + public void audit(Object arg0); + + /** + * Prints messages with the level.DEBUG + */ + public void debug(Object message, Throwable t); + + /** + * Prints messages with the level.ERROR + */ + public void error(Object message, Throwable t); + + /** + * Prints messages with the level.INFO + */ + public void info(Object message, Throwable t); + + /** + * Prints messages with the level.WARN + */ + public void warn(Object message, Throwable t); + + /** + * Prints messages with the level.TRACE + */ + public void trace(Object message, Throwable t); + + /** + * Prints messages in audit log with the level.INFO + */ + public void audit(Object arg0, Throwable t); + + /** + * Records event Id in audit log with the level.INFO + */ + public void recordAuditEventStart(String eventId); + + /** + * Records the starting time of the event with its request Id as the key + */ + public void recordAuditEventStart(UUID eventId); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(String eventId, String rule, String policyVersion ); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(String eventId, String rule); + + /** + * Records the ending time of the event with its request Id as the key + */ + public void recordAuditEventEnd(UUID eventId, String rule); + + + /** + * Records the Metrics with event Id and log message + */ + public void recordMetricEvent(String eventId, String arg1); + + /** + * Records the Metrics with event Id and log message + */ + public void recordMetricEvent(UUID eventId, String arg1); + + /** + * Records the Metrics log message + */ + public void metrics(Object arg0); + + /** + * Returns a boolean value, true for debug logging enabled, false for not enabled + */ + public boolean isDebugEnabled(); + + /** + * Returns a boolean value, true for error logging enabled, false for not enabled + */ + public boolean isErrorEnabled(); + + /** + * Returns a boolean value, true for warn logging enabled, false for not enabled + */ + public boolean isWarnEnabled(); + + /** + * Returns a boolean value, true for info logging enabled, false for not enabled + */ + public boolean isInfoEnabled(); + + /** + * Returns a boolean value, true for error logging enabled, false for not enabled + */ + public boolean isAuditEnabled(); + + /** + * Returns a boolean value, true for warn logging enabled, false for not enabled + */ + public boolean isMetricsEnabled(); + + /** + * Returns a boolean value, true for trace logging enabled, false for not enabled + */ + public boolean isTraceEnabled(); + + + /** + * Populates MDC info + */ + public String postMDCInfoForEvent(String transId); + + /** + * Prints messages with the level.WARN + */ + public void warn(MessageCodes msg, String... arguments) ; + + /** + * Prints messages with the level.WARN + */ + public void warn(MessageCodes msg, Throwable arg0, String... arguments) ; + + /** + * Prints messages with the level.ERROR + */ + public void error(MessageCodes msg, String... arguments) ; + + /** + * Sets transaction Id + */ + public void setTransId(String transId); + + /** + * Returns transaction Id + */ + String getTransId(); + + /** + * Populates MDC Info for the rule triggered + */ + public void postMDCInfoForTriggeredRule(String transId); + + /** + * Populates MDC Info + */ + public void postMDCInfoForEvent(Object o); + +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java new file mode 100644 index 00000000..2e67a735 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger4J.java @@ -0,0 +1,488 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.UUID; + +import org.apache.log4j.Logger; +import org.apache.log4j.Priority; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import com.att.eelf.configuration.EELFLogger.Level; + +/** + * + * Logger4J implements all the methods of interface Logger by calling org.apache.log4j.Logger + * + */ +public class Logger4J implements org.onap.policy.common.logging.flexlogger.Logger, Serializable { + + /** + * + */ + private static final long serialVersionUID = 3183729429888828471L; + private Logger log = null; + private String methodName = ""; + private String className = ""; + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor + * @param clazz + */ + public Logger4J (Class clazz){ + System.out.println("create instance of Logger4J"); + if(clazz != null){ + log = Logger.getLogger(clazz); + className = clazz.getName(); + } + } + + /** + * Constructor + * @param s + * @param className + */ + public Logger4J (String s, String className){ + System.out.println("create instance of Logger4J"); + if(s != null){ + log = Logger.getLogger(s); + } + this.className = className; + } + + /** + * Sets transaction Id + */ + @Override + public void setTransId(String transId){ + log.info(transId); + this.transId = transId; + } + + /** + * Returns transaction Id + */ + @Override + public String getTransId(){ + return transId; + } + + /** + * Records a message + * @param message + */ + @Override + public void debug(Object message) { + if(isDebugEnabled()){ + log.debug(transId + "|" + message); + } + } + + /** + * Records an error message + * @param message + */ + @Override + public void error(Object message) { + log.error( transId + "|" + className +"|" + message); + } + + /** + * Records a message + * @param message + */ + @Override + public void info(Object message) { + log.info( transId + "|" + className +"|" + message); + } + + /** + * Records a message + * @param message + */ + @Override + public void warn(Object message) { + log.warn( transId + "|" + className +"|" + message); + } + + /** + * Records a message + * @param message + */ + @Override + public void trace(Object message) { + log.trace(transId + "|"+ className +"|" + message); + } + + /** + * Returns true for debug enabled, or false for not + * @return boolean + */ + @Override + public boolean isDebugEnabled(){ + return log.isDebugEnabled(); + } + + /** + * Returns true for error enabled, or false for not + * @return boolean + */ + @SuppressWarnings("deprecation") + @Override + public boolean isErrorEnabled(){ + return log.isEnabledFor(Priority.ERROR); + } + + /** + * Returns true for info enabled, or false for not + * @return boolean + */ + @Override + public boolean isInfoEnabled(){ + return log.isInfoEnabled(); + } + + /** + * Returns true for warn enabled, or false for not + * @return boolean + */ + @SuppressWarnings("deprecation") + @Override + public boolean isWarnEnabled(){ + //return log4j value + return log.isEnabledFor(Priority.WARN); + } + + /** + * Returns true for audit enabled, or false for not + * @return boolean + */ + @Override + public boolean isAuditEnabled(){ + if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Returns true for metrics enabled, or false for not + * @return boolean + */ + @Override + public boolean isMetricsEnabled(){ + if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ + return false; + }else { + return true; + } + } + + /** + * Records an audit message + * @param arg0 + */ + @Override + public void audit(Object arg0) { + log.info(className +"|" +arg0); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(String eventId) { + log.info(className +"|recordAuditEventStart with eventId " + eventId); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(UUID eventId) { + if(eventId != null){ + recordAuditEventStart(eventId.toString()); + } + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + log.info(className +"|"+ eventId + ":" + rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + if(eventId != null){ + recordAuditEventEnd(eventId.toString(), rule, policyVersion); + }else{ + recordAuditEventEnd(eventId, rule, policyVersion); + } + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + log.info(className +"|" +eventId + ":" + rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + if(eventId != null){ + recordAuditEventEnd(eventId.toString(), rule); + }else{ + recordAuditEventEnd(eventId, rule); + } + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(String eventId, String arg1) { + log.info(className +"|" +eventId + ":" + arg1); + + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(UUID eventId, String arg1) { + if(eventId != null){ + recordMetricEvent(eventId.toString(), arg1); + }else{ + recordMetricEvent(eventId, arg1); + } + } + + /** + * Records a metrics message + * @param arg0 + */ + @Override + public void metrics(Object arg0) { + log.info(arg0); + } + + /** + * Records an error message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void error(MessageCodes msg, Throwable arg0, String... arguments){ + log.error(transId + "|" + className +"|" + "MessageCodes :" + msg + arguments); + + } + + /** + * Records an error message + * @param msg + * @param arguments + */ + @Override + public void error(MessageCodes msg, String... arguments){ + log.error(transId + "|" + className +"|" + "MessageCode:" + msg + arguments); + } + + /** + * Returns transaction Id + * @param transId + */ + @Override + public String postMDCInfoForEvent(String transId) { + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + + return transId; + } + + /** + * Records a message + * @param msg + * @param arguments + */ + @Override + public void warn(MessageCodes msg, String... arguments){ + log.warn(className +"|" +"MessageCodes:" + msg + arguments); + } + + /** + * Records a message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void warn(MessageCodes msg, Throwable arg0, String... arguments){ + log.warn(className +"|" +"MessageCodes:" + msg + arguments); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void debug(Object message, Throwable t) { + log.debug(message, t); + } + + /** + * Records an error message + * @param message + * @param t + */ + @Override + public void error(Object message, Throwable t) { + log.error(message, t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void info(Object message, Throwable t) { + log.info(message, t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void warn(Object message, Throwable t) { + log.warn(message, t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void trace(Object message, Throwable t) { + log.trace(message, t); + } + + /** + * Records an audit message + * @param arg0 + * @param t + */ + + @Override + public void audit(Object arg0, Throwable t) { + log.info(arg0, t); + } + + /** + * Returns true for trace enabled, or false for not + * @return boolean + */ + @Override + public boolean isTraceEnabled() { + return log.isTraceEnabled(); + } + + /** + * Records transaction Id + * @param transId + */ + @Override + public void postMDCInfoForTriggeredRule(String transId){ + log.info(transId); + } + + /** + * Records transaction Id + * @param o + */ + @Override + public void postMDCInfoForEvent(Object o){ + log.info(o); + } + + /* ============================================================ */ + + /* + * Support for 'Serializable' -- + * the default rules don't work for the 'log' field + */ + + private void writeObject(ObjectOutputStream out) throws IOException { + // write out 'methodName', 'className', 'transId' strings + out.writeObject(methodName); + out.writeObject(className); + out.writeObject(transId); + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException { + + // read in 'methodName', 'className', 'transId' strings + methodName = (String)(in.readObject()); + className = (String)(in.readObject()); + transId = (String)(in.readObject()); + + // look up associated logger + log = Logger.getLogger(className); + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java new file mode 100644 index 00000000..ed2029e6 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +/** + * + * Logger types + * + */ +public enum LoggerType { + EELF, LOG4J, SYSTEMOUT +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java new file mode 100644 index 00000000..598dd09b --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java @@ -0,0 +1,403 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Properties; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; + +/** + * This class provides utilities to read properties from a properties + * file, and optionally get notifications of future changes + */ +public class PropertyUtil +{ + /** + * Read in a properties file + * @param file the properties file + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file + * does not exist or can't be opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(File file) throws IOException + { + // create an InputStream (may throw a FileNotFoundException) + FileInputStream fis = new FileInputStream(file); + try + { + // create the properties instance + Properties rval = new Properties(); + + // load properties (may throw an IOException) + rval.load(fis); + return(rval); + } + finally + { + // close input stream + fis.close(); + } + } + + /** + * Read in a properties file + * @param fileName the properties file + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file + * does not exist or can't be opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(String fileName) throws IOException + { + return(getProperties(new File(fileName))); + } + + /* ============================================================ */ + + // timer thread used for polling for property file changes + private static Timer timer = null; + + /** + * This is the callback interface, used for sending notifications of + * changes in the properties file. + */ + public interface Listener + { + /** + * Notification of a properties file change + * @param properties the new properties + * @param the set of property names that have changed, including + * additions and removals + */ + void propertiesChanged(Properties properties, Set changedKeys); + } + + // this table maps canonical file into a 'ListenerRegistration' instance + static private HashMap registrations = + new HashMap(); + + /** + * This is an internal class - one instance of this exists for each + * property file that is being monitored. Note that multiple listeners + * can be registered for the same file. + */ + private static class ListenerRegistration + { + // the canonical path of the file being monitored + File file; + + // the most recent value of 'file.lastModified()' + long lastModified; + + // the most recent set of properties + Properties properties; + + // the set of listeners monitoring this file + LinkedList listeners; + + // the 'TimerTask' instance, used for periodic polling + TimerTask timerTask; + + /** + * Constructor - create a 'ListenerRegistration' instance for this + * file, but with no listeners + */ + ListenerRegistration(File file) throws IOException + { + this.file = file; + + // The initial value of 'lastModified' is set to 0 to ensure that we + // correctly handle the case where the file is modified within the + // same second that polling begins. + lastModified = 0; + + // fetch current properties + properties = getProperties(file); + + // no listeners yet + listeners = new LinkedList(); + + // add to static table, so this instance can be shared + registrations.put(file, this); + + if (timer == null) + { + // still need to create a timer thread + synchronized(PropertyUtil.class) + { + // an additional check is added inside the 'synchronized' block, + // just in case someone beat us to it + if (timer == null) + { + timer = new Timer("PropertyUtil-Timer", true); + } + } + } + + // create and schedule the timer task, so this is periodically polled + timerTask = new TimerTask() + { + public void run() + { + try + { + poll(); + } + catch (Exception e) + { + System.err.println(e); + } + } + }; + timer.schedule(timerTask, 10000L, 10000L); + } + + /** + * Add a listener to the notification list + * @param listener this is the listener to add to the list + * @return the properties at the moment the listener was added to the list + */ + synchronized Properties addListener(Listener listener) + { + listeners.add(listener); + return((Properties)properties.clone()); + } + + /** + * Remove a listener from the notification list + * @param listener this is the listener to remove + */ + synchronized void removeListener(Listener listener) + { + listeners.remove(listener); + + // See if we need to remove this 'ListenerRegistration' instance + // from the table. The 'synchronized' block is needed in case + // another listener is being added at about the same time that this + // one is being removed. + synchronized(registrations) + { + if (listeners.size() == 0) + { + timerTask.cancel(); + registrations.remove(file); + } + } + } + + /** + * This method is periodically called to check for property list updates + * @throws IOException if there is an error in reading the properties file + */ + synchronized void poll() throws IOException + { + long timestamp = file.lastModified(); + if (timestamp != lastModified) + { + // update the record, and send out the notifications + lastModified = timestamp; + + // Save old set, and initial set of changed properties. + Properties oldProperties = properties; + HashSet changedProperties = + new HashSet(oldProperties.stringPropertyNames()); + + // Fetch the list of listeners that we will potentially notify, + // and the new properties. Note that this is in a 'synchronized' + // block to ensure that all listeners receiving notifications + // actually have a newer list of properties than the one + // returned on the initial 'getProperties' call. + properties = getProperties(file); + + Set newPropertyNames = properties.stringPropertyNames(); + changedProperties.addAll(newPropertyNames); + + // At this point, 'changedProperties' is the union of all properties + // in both the old and new properties files. Iterate through all + // of the entries in the new properties file - if the entry + // matches the one in the old file, remove it from + // 'changedProperties'. + for (String name : newPropertyNames) + { + if (properties.getProperty(name).equals + (oldProperties.getProperty(name))) + { + // Apparently, any property that exists must be of type + // 'String', and can't be null. For this reason, we don't + // need to worry about the case where + // 'properties.getProperty(name)' returns 'null'. Note that + // 'oldProperties.getProperty(name)' may be 'null' if the + // old property does not exist. + changedProperties.remove(name); + } + } + + // 'changedProperties' should be correct at this point + if (changedProperties.size() != 0) + { + // there were changes - notify everyone in 'listeners' + for (final Listener notify : listeners) + { + // Copy 'properties' and 'changedProperties', so it doesn't + // cause problems if the recipient makes changes. + final Properties tmpProperties = + (Properties)(properties.clone()); + final HashSet tmpChangedProperties = + new HashSet(changedProperties); + + // Do the notification in a separate thread, so blocking + // won't cause any problems. + new Thread() + { + public void run() + { + notify.propertiesChanged + (tmpProperties, tmpChangedProperties); + } + }.start(); + } + } + } + } + } + + /** + * Read in a properties file, and register for update notifications. + * NOTE: it is possible that the first callback will occur while this + * method is still in progress. To avoid this problem, use 'synchronized' + * blocks around this invocation and in the callback -- that will ensure + * that the processing of the initial properties complete before any + * updates are processed. + * + * @param file the properties file + * @param notify if not null, this is a callback interface that is used for + * notifications of changes + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file + * does not exist or can't be opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(File file, Listener listener) + throws IOException + { + if (listener == null) + { + // no listener specified -- just fetch the properties + return(getProperties(file)); + } + + // Convert the file to a canonical form in order to avoid the situation + // where different names refer to the same file. + file = file.getCanonicalFile(); + + // See if there is an existing registration. The 'synchronized' block + // is needed to handle the case where a new listener is added at about + // the same time that another one is being removed. + synchronized(registrations) + { + ListenerRegistration reg = registrations.get(file); + if (reg == null) + { + // a new registration is needed + reg = new ListenerRegistration(file); + } + return(reg.addListener(listener)); + } + } + + /** + * Read in a properties file, and register for update notifications. + * NOTE: it is possible that the first callback will occur while this + * method is still in progress. To avoid this problem, use 'synchronized' + * blocks around this invocation and in the callback -- that will ensure + * that the processing of the initial properties complete before any + * updates are processed. + * + * @param fileName the properties file + * @param notify if not null, this is a callback interface that is used for + * notifications of changes + * @return a Properties object, containing the associated properties + * @throws IOException - subclass 'FileNotFoundException' if the file + * does not exist or can't be opened, and 'IOException' if there is + * a problem loading the properties file. + */ + static public Properties getProperties(String fileName, Listener listener) + throws IOException + { + return(getProperties(new File(fileName), listener)); + } + + /** + * Stop listenening for updates + * @param file the properties file + * @param notify if not null, this is a callback interface that was used for + * notifications of changes + */ + static public void stopListening(File file, Listener listener) + { + if (listener != null) + { + ListenerRegistration reg = registrations.get(file); + if (reg != null) + { + reg.removeListener(listener); + } + } + } + + /** + * Stop listenening for updates + * @param fileName the properties file + * @param notify if not null, this is a callback interface that was used for + * notifications of changes + */ + static public void stopListening(String fileName, Listener listener) + { + stopListening(new File(fileName), listener); + } + + /* ============================================================ */ + + // TEMPORARY - used to test callback interface + static public class Test implements Listener + { + String name; + + public Test(String name) + { + this.name = name; + } + + public void propertiesChanged(Properties properties, Set changedKeys) + { + System.out.println("Test(" + name + ")\nproperties = " + properties + + "\nchangedKeys = " + changedKeys); + } + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java new file mode 100644 index 00000000..f1acc042 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java @@ -0,0 +1,502 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.flexlogger; + +import java.io.Serializable; +import java.util.UUID; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import com.att.eelf.configuration.EELFLogger.Level; + +/** + * + * SystemOutLogger implements all the methods of interface Logger by calling System.out.println + * + */ +public class SystemOutLogger implements Logger, Serializable { + + /** + * + */ + private static final long serialVersionUID = 4956408061058933929L; + private String className = ""; + private boolean isDebugEnabled = true; + private boolean isInfoEnabled = true; + private boolean isWarnEnabled = true; + private boolean isErrorEnabled = true; + private boolean isAuditEnabled = true; + private boolean isMetricsEnabled = true; + private String transId = UUID.randomUUID().toString(); + + /** + * Constructor + * @param clazz + */ + public SystemOutLogger (Class clazz){ + System.out.println("create instance of SystemOutLogger"); + if(clazz != null){ + className = clazz.getName(); + } + initLevel(); + } + + /** + * Constructor + * @param s + */ + public SystemOutLogger (String s){ + System.out.println("create instance of SystemOutLogger"); + if(s != null){ + className = s; + } + initLevel(); + } + + /** + * Sets logging levels + */ + private void initLevel(){ + + if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.DEBUG.toString())){ + isDebugEnabled = true; + isInfoEnabled = true; + isWarnEnabled = true; + }else{ + isDebugEnabled = false; + } + + if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.INFO.toString())){ + isInfoEnabled = true; + isWarnEnabled = true; + isDebugEnabled = false; + } + + if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.OFF.toString())){ + isInfoEnabled = false; + isWarnEnabled = false; + isDebugEnabled = false; + } + + if(PolicyLogger.ERROR_LEVEL != null && PolicyLogger.ERROR_LEVEL.toString().equals(Level.OFF.toString())){ + isErrorEnabled = false; + } + + if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ + isAuditEnabled = false; + } + + if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ + isMetricsEnabled = false; + } + } + + /** + * Sets transaction Id + */ + @Override + public void setTransId(String transId){ + + System.out.println(transId); + this.transId = transId; + } + + /** + * Returns transaction Id + */ + @Override + public String getTransId(){ + + return transId; + } + + /** + * Records a message + * @param message + */ + @Override + public void debug(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Records an error message + * @param message + */ + @Override + public void error(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void info(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + + } + + /** + * Records a message + * @param message + */ + @Override + public void warn(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Records a message + * @param message + */ + @Override + public void trace(Object message) { + + System.out.println(transId + "|" + className+" : "+message); + } + + /** + * Returns true for debug enabled, or false for not + * @return boolean + */ + @Override + public boolean isDebugEnabled(){ + + return isDebugEnabled; + } + + /** + * Returns true for warn enabled, or false for not + * @return boolean + */ + @Override + public boolean isWarnEnabled(){ + + return isWarnEnabled; + } + + /** + * Returns true for info enabled, or false for not + * @return boolean + */ + @Override + public boolean isInfoEnabled(){ + + return isInfoEnabled; + } + + /** + * Returns true for error enabled, or false for not + * @return boolean + */ + @Override + public boolean isErrorEnabled(){ + + return isErrorEnabled; + } + + /** + * Returns true for audit enabled, or false for not + * @return boolean + */ + @Override + public boolean isAuditEnabled(){ + + return isAuditEnabled; + } + + /** + * Returns true for metrics enabled, or false for not + * @return boolean + */ + @Override + public boolean isMetricsEnabled(){ + + return isMetricsEnabled; + } + + /** + * Records an audit message + * @param arg0 + */ + @Override + public void audit(Object arg0) { + + System.out.println(transId + "|" +className+" : "+arg0); + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(String eventId) { + + System.out.println(transId + "|" +className+" : "+eventId); + + } + + /** + * Records an audit message + * @param eventId + */ + @Override + public void recordAuditEventStart(UUID eventId) { + + System.out.println(eventId); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { + + System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + * @param policyVersion + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { + + System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(String eventId, String rule) { + + System.out.println(className+" : "+eventId + ":" + rule); + } + + /** + * Records an audit message + * @param eventId + * @param rule + */ + @Override + public void recordAuditEventEnd(UUID eventId, String rule) { + + System.out.println(className+" : "+eventId + ":" + rule); + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(String eventId, String arg1) { + + System.out.println(className+" : "+"eventId:" + ":" + eventId + "message:" + arg1); + + } + + /** + * Records a metrics message + * @param eventId + * @param arg1 + */ + @Override + public void recordMetricEvent(UUID eventId, String arg1) { + + System.out.println(className+" : "+eventId + ":" + arg1); + } + + /** + * Records a metrics message + * @param arg0 + */ + @Override + public void metrics(Object arg0) { + + System.out.println(className+" : "+arg0); + } + + /** + * Records an error message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void error(MessageCodes msg, Throwable arg0, String... arguments){ + + System.out.println(className+" : "+"MessageCodes :" + msg + arguments); + + } + + /** + * Records an error message + * @param msg + * @param arguments + */ + @Override + public void error(MessageCodes msg, String... arguments){ + + System.out.println(transId + "|" + className+" : "+"MessageCode:" + msg + arguments); + } + + /** + * Returns transaction Id + * @param transId + */ + @Override + public String postMDCInfoForEvent(String transId) { + + if(transId == null || transId.isEmpty()){ + transId = UUID.randomUUID().toString(); + } + + return transId; + } + + /** + * Records a message + * @param msg + * @param arguments + */ + @Override + public void warn(MessageCodes msg, String... arguments){ + + System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + arguments); + } + + /** + * Records a message + * @param msg + * @param arg0 + * @param arguments + */ + @Override + public void warn(MessageCodes msg, Throwable arg0, String... arguments){ + + System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + arguments); + + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void debug(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records an error message + * @param message + * @param t + */ + @Override + public void error(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void info(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void warn(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records a message + * @param message + * @param t + */ + @Override + public void trace(Object message, Throwable t) { + System.out.println(transId + "|" + className+" : "+ message + ":" + t); + } + + /** + * Records an audit message + * @param arg0 + * @param t + */ + @Override + public void audit(Object arg0, Throwable t) { + System.out.println(transId + "|" + className+" : "+ arg0 + ":" + t); + } + + /** + * Returns true for trace enabled, or false for not + * @return boolean + */ + @Override + public boolean isTraceEnabled() { + // default + return false; + } + + /** + * Records transaction Id + * @param transId + */ + @Override + public void postMDCInfoForTriggeredRule(String transId){ + + System.out.println(transId); + } + + /** + * Records transaction Id + * @param o + */ + @Override + public void postMDCInfoForEvent(Object o){ + System.out.println(o); + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java new file mode 100644 index 00000000..0786febd --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.nsa; + +/** + * An interface for providing data into the underlying logging context. Systems should use + * this interface rather than log system specific MDC solutions in order to reduce dependencies. + * + * A LoggingContext is specific to the calling thread. + * + */ +public interface LoggingContext +{ + /** + * Put a key/value pair into the logging context, replacing an entry with the same key. + * @param key + * @param value + */ + void put ( String key, String value ); + + /** + * Put a key/value pair into the logging context, replacing an entry with the same key. + * @param key + * @param value + */ + void put ( String key, long value ); + + /** + * Get a string value, returning the default value if the value is missing. + * @param key + * @param defaultValue + * @return a string value + */ + String get ( String key, String defaultValue ); + + /** + * Get a long value, returning the default value if the value is missing or not a long. + * @param key + * @param defaultValue + * @return a long value + */ + long get ( String key, long defaultValue ); +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java new file mode 100644 index 00000000..78fffefe --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.nsa; + + +import org.onap.policy.common.logging.nsa.impl.SharedContext; +import org.onap.policy.common.logging.nsa.impl.Slf4jLoggingContext; + +/** + * A factory for setting up a LoggingContext + * + */ +public class LoggingContextFactory +{ + public static class Builder + { + public Builder withBaseContext ( LoggingContext lc ) + { + fBase = lc; + return this; + } + + public Builder forSharing () + { + fShared = true; + return this; + } + + public LoggingContext build () + { + return fShared ? new SharedContext ( fBase ) : new Slf4jLoggingContext ( fBase ); + } + + private LoggingContext fBase = null; + private boolean fShared = false; + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java new file mode 100644 index 00000000..af0cc393 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.nsa; + +/** + * A logging context must be thread-specific. Contexts that implement SharedLoggingContext + * are expected to be shared across threads, and they have to be able to populate another + * logging context with their data. + * + */ +public interface SharedLoggingContext extends LoggingContext +{ + /** + * Copy this context's data to the given context. This must work across threads so that + * a base context can be shared in another thread. + * @param lc + */ + void transferTo ( SharedLoggingContext lc ); +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java new file mode 100644 index 00000000..715edfab --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.nsa.impl; + +import java.util.HashMap; +import java.util.Map.Entry; + +import org.onap.policy.common.logging.nsa.LoggingContext; +import org.onap.policy.common.logging.nsa.SharedLoggingContext; + +/** + * A shared logging context for SLF4J + * + */ +public class SharedContext extends Slf4jLoggingContext implements SharedLoggingContext +{ + public SharedContext ( LoggingContext base ) + { + super ( base ); + fMap = new HashMap (); + } + + @Override + public void put ( String key, String value ) + { + super.put ( key, value ); + fMap.put ( key, value ); + } + + @Override + public void transferTo ( SharedLoggingContext lc ) + { + for ( Entry e : fMap.entrySet () ) + { + lc.put ( e.getKey(), e.getValue() ); + } + } + + private final HashMap fMap; +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java new file mode 100644 index 00000000..187b2954 --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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.logging.nsa.impl; + +import org.slf4j.MDC; + +import org.onap.policy.common.logging.nsa.LoggingContext; + +/** + * A logging context for SLF4J + * + */ +public class Slf4jLoggingContext implements LoggingContext +{ + public Slf4jLoggingContext ( LoggingContext base ) + { + } + + @Override + public void put ( String key, String value ) + { + MDC.put ( key, value ); + } + + public void put ( String key, long value ) + { + put ( key, "" + value ); + } + + + public String get ( String key, String defaultValue ) + { + String result = MDC.get ( key ); + if ( result == null ) + { + result = defaultValue; + } + return result; + } + + public long get ( String key, long defaultValue ) + { + final String str = get ( key, "" + defaultValue ); + try + { + return Long.parseLong ( str ); + } + catch ( NumberFormatException x ) + { + return defaultValue; + } + } +} diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java new file mode 100644 index 00000000..6f58bb0f --- /dev/null +++ b/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * 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========================================================= + */ + +/** + * This package provides a logging context infrastructure and a corresponding + * implementation based on the SLF4J/Log4j "MDC" (Mapped Diagnostic Context) feature. + * + */ +package org.onap.policy.common.logging.nsa; + diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingContext.java deleted file mode 100644 index 606e872d..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingContext.java +++ /dev/null @@ -1,595 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging; - -//import static org.openecomp.policy.common.logging.eelf.Configuration.TRANSACTION_BEGIN_TIME_STAMP; -//import static org.openecomp.policy.common.logging.eelf.Configuration.TRANSACTION_ELAPSED_TIME; -//import static org.openecomp.policy.common.logging.eelf.Configuration.TRANSACTION_END_TIME_STAMP; - -import java.text.SimpleDateFormat; -import java.time.Duration; -import java.time.Instant; -import java.util.Date; -import org.slf4j.MDC; - -import org.openecomp.policy.common.logging.nsa.LoggingContextFactory; -import org.openecomp.policy.common.logging.nsa.SharedLoggingContext; - -/** - * A facade over the org.openecomp.policy.common.logging.nsa.SharedLoggingContext interface/implementation that makes it - * more convenient to use. SharedLoggingContext builds on the SLF4J/log4j Mapped Diagnostic Context (MDC) - * feature, which provides a hashmap-based context for data items that need to be logged, where the - * hashmap is kept in ThreadLocal storage. The data items can be referenced in the log4j configuration - * using the EnhancedPatternLayout appender layout class, and the notation "%X{key}" in the ConversionPattern - * string, where "key" is one of the keys in the MDC hashmap (which is determined by what hashmap entries the - * application code creates). Example: - * log4j.appender.auditAppender.layout=org.apache.log4j.EnhancedPatternLayout - * log4j.appender.auditAppender.layout.ConversionPattern=%d|%X{requestId}|%X{serviceInstanceId}|...|%m%n - * where "requestId" and "serviceInstanceId" are entries in the MDC hashmap. - * - * The notable functionality the SharedLoggingContext adds over MDC is that it maintains its own copy - * of the MDC data items in a hashmap (not in ThreadLocal storage), which allows more control of the data. - * The ECOMPLoggingContext constructor that takes another ECOMPLoggingContext object as a parameter makes - * use of this feature. For example if there is a thread pulling requests from a queue for processing, it - * can keep a base logging context with data that is common to all requests, and for each request, create a - * new logging context with that base context as a parameter; this will create a new logging context with - * those initial values and none of the request-specific values from the previous request such as a request ID. - - * The setter methods in this class set corresponding items in the SharedLoggingContext/MDC hashmaps. - * These items correspond to the fields defined in the "ECOMP platform application logging guidelines" - * document. In addition, there is a pair of convenience functions, transactionStarted() and - * transactionEnded(), that can be called at the beginning and end of transaction processing to calculate - * the duration of the transaction and record that value in the "timer" item. - * - */ -public class ECOMPLoggingContext { - - private static final String REQUEST_ID = "requestId"; - private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; - private static final String THREAD_ID = "threadId"; - private static final String SERVER_NAME = "serverName"; - private static final String SERVICE_NAME = "serviceName"; - private static final String PARTNER_NAME = "partnerName"; - private static final String STATUS_CODE = "statusCode"; - private static final String TARGET_ENTITY = "targetEntity"; - private static final String TARGET_SERVICE_NAME = "targetServiceName"; - private static final String INSTANCE_UUID = "instanceUuid"; - private static final String SEVERITY = "severity"; - private static final String SERVER_IP_ADDRESS = "serverIpAddress"; - private static final String SERVER = "server"; - private static final String CLIENT_IP_ADDRESS = "clientIpAddress"; - private static final String CLASSNAME = "classname"; - private static final String TRANSACTION_BEGIN_TIME_STAMP = "TransactionBeginTimestamp"; - private static final String TRANSACTION_END_TIME_STAMP = "TransactionEndTimestamp"; - private static final String TRANSACTION_ELAPSED_TIME = "TransactionElapsedTime"; - private static final String METRIC_BEGIN_TIME_STAMP = "MetricBeginTimestamp"; - private static final String METRIC_END_TIME_STAMP = "MetricEndTimestamp"; - private static final String METRIC_ELAPSED_TIME = "MetricElapsedTime"; - - - private static LoggingContextFactory.Builder loggingContextBuilder = new LoggingContextFactory.Builder(); - - protected SharedLoggingContext context = null; -// private long transactionStartTime = 0; - private Instant transactionStartTime; - private Instant metricStartTime; - - /** - * Create a new ECOMPLoggingContext with no base context. - */ - public ECOMPLoggingContext() { - context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); - } - - /** - * Create a new ECOMPLoggingContext initially populated with the values - * in the given base context. This can be used for example in a servlet - * where each incoming request may be processed by a separate thread, but - * there may be some logging data items that will be unchanging and common - * to all the threads. That constant data can be populated in a base - * context, and then each request handler creates new context passing that - * base context to populate the common data in the new one. - * @param baseContext - */ - public ECOMPLoggingContext(ECOMPLoggingContext baseContext) { - context = (SharedLoggingContext) loggingContextBuilder.forSharing().build(); - // a logging context could be passed into a thread (e.g. one that is servicing a queue) - // that already had a logging context established, so the MDC hashmap could contain - // entries that are no longer appropriate; so clear out the MDC hashmap before - // transferring the new logging context values. - // x - MDC.clear(); - baseContext.context.transferTo(context); - transactionStartTime = baseContext.transactionStartTime; - setServiceName("POLICY"); - setPartnerName("USER"); - setStatusCode("COMPLETE"); - setTargetEntity("POLICY"); - setTargetServiceName("PE Process"); - } - - /** - * Indicate the start of transaction processing. The current system time - * will be recorded for use by transactionEnded() to calculate - * the duration of the transaction. - */ - public void transactionStarted() { -// transactionStartTime = System.currentTimeMillis(); - transactionStartTime = Instant.now(); - setTransactionBeginTimestamp(transactionStartTime); - } - - /** - * Indicate the end of transaction processing. The difference between the - * current system time and the time recorded by transactionStarted() - * will be recorded in the data item with key "TransactionElapsedTime". - */ - public void transactionEnded() { - Instant transactionEndTime = Instant.now(); - setTransactionEndTimestamp(transactionEndTime); - setTransactionElapsedTime(transactionEndTime); - } - - /** - * Indicate the start of metric processing. The current system time - * will be recorded for use by metricEnded() to calculate - * the duration of the metric. - */ - public void metricStarted() { -// transactionStartTime = System.currentTimeMillis(); - metricStartTime = Instant.now(); - setMetricBeginTimestamp(metricStartTime); - } - - /** - * Indicate the end of metric processing. The difference between the - * current system time and the time recorded by metricStarted() - * will be recorded in the data item with key "MetricElapsedTime". - */ - public void metricEnded() { - Instant metricEndTime = Instant.now(); - setMetricEndTimestamp(metricEndTime); - setMetricElapsedTime(metricEndTime); - } - - - /** - * Set the value for the data item with key "requestId" - * - * @param id - */ - public void setRequestID(String id) { - context.put(REQUEST_ID, id); - } - /** - * Get the value for the data item with key "requestId" - * @return current value, or empty string if not set - */ - public String getRequestID() { - return context.get(REQUEST_ID, ""); - } - - /** - * Set the value for the data item with key "serviceInstanceId" - * - * @param id - */ - public void setServiceInstanceID(String id) { - context.put(SERVICE_INSTANCE_ID, id); - } - /** - * Get the value for the data item with key "serviceInstanceId" - * @return current value, or empty string if not set - */ - public String getServiceInstanceID() { - return context.get(SERVICE_INSTANCE_ID, ""); - } - - /** - * Set the value for the data item with key "threadId". - * An alternative to using this item is to use the - * %t conversion character in the appender's conversion string. - * - * @param id - */ - public void setThreadID(String id) { - context.put(THREAD_ID, id); - } - /** - * Get the value for the data item with key "threadId" - * @return current value, or empty string if not set - */ - public String getThreadID() { - return context.get(THREAD_ID, ""); - } - - /** - * Set the value for the data item with key "serverName" - * - * @param id - */ - public void setServerName(String name) { - context.put(SERVER_NAME, name); - } - /** - * Get the value for the data item with key "serverName" - * @return current value, or empty string if not set - */ - public String getServerName() { - return context.get(SERVER_NAME, ""); - } - - /** - * Set the value for the data item with key "serviceName" - * - * @param id - */ - public void setServiceName(String name) { - context.put(SERVICE_NAME, name); - } - /** - * Get the value for the data item with key "serviceName" - * @return current value, or empty string if not set - */ - public String getServiceName() { - return context.get(SERVICE_NAME, ""); - } - - /** - * Set the value for the data item with key "partnerName" - * - * @param id - */ - public void setPartnerName(String name) { - context.put(PARTNER_NAME, name); - } - /** - * Get the value for the data item with key "partnerName" - * @return current value, or empty string if not set - */ - public String getPartnerName() { - return context.get(PARTNER_NAME, ""); - } - - /** - * Set the value for the data item with key "statusCode" - * - * @param id - */ - public void setStatusCode(String name) { - context.put(STATUS_CODE, name); - } - /** - * Get the value for the data item with key "statusCode" - * @return current value, or empty string if not set - */ - public String getStatusCode() { - return context.get(STATUS_CODE, ""); - } - - /** - * Set the value for the data item with key "targetEntity" - * - * @param id - */ - public void setTargetEntity(String name) { - context.put(TARGET_ENTITY, name); - } - /** - * Get the value for the data item with key "targetEntity" - * @return current value, or empty string if not set - */ - public String getTargetEntity() { - return context.get(TARGET_ENTITY, ""); - } - - /** - * Set the value for the data item with key "targetServiceName" - * - * @param id - */ - public void setTargetServiceName(String name) { - context.put(TARGET_SERVICE_NAME, name); - } - /** - * Get the value for the data item with key "targetServiceName" - * @return current value, or empty string if not set - */ - public String getTargetServiceName() { - return context.get(TARGET_SERVICE_NAME, ""); - } - - /** - * Set the value for the data item with key "instanceUuid" - * - * @param id - */ - public void setInstanceUUID(String uuid) { - context.put(INSTANCE_UUID, uuid); - } - /** - * Get the value for the data item with key "instanceUuid" - * @return current value, or empty string if not set - */ - public String getInstanceUUID() { - return context.get(INSTANCE_UUID, ""); - } - - /** - * Set the value for the data item with key "severity" - * - * @param id - */ - public void setSeverity(Long severity) { - context.put(SEVERITY, severity); - } - /** - * Get the value for the data item with key "severity" - * @return current value, or empty string if not set - */ - public String getSeverity() { - return context.get(SEVERITY, ""); - } - - /** - * Set the value for the data item with key "serverIp" - * - * @param id - */ - public void setServerIPAddress(String serverIP) { - context.put(SERVER_IP_ADDRESS, serverIP); - } - /** - * Get the value for the data item with key "serverIp" - * @return current value, or empty string if not set - */ - public String getServerIPAddress() { - return context.get(SERVER_IP_ADDRESS, ""); - } - - /** - * Set the value for the data item with key "server" - * - * @param id - */ - public void setServer(String server) { - context.put(SERVER, server); - } - /** - * Get the value for the data item with key "server" - * @return current value, or empty string if not set - */ - public String getServer() { - return context.get(SERVER, ""); - } - - /** - * Set the value for the data item with key "clientIp" - * - * @param id - */ - public void setClientIPAddress(String clientIP) { - context.put(CLIENT_IP_ADDRESS, clientIP); - } - /** - * Get the value for the data item with key "clientIp" - * @return current value, or empty string if not set - */ - public String getClientIPAddress() { - return context.get(CLIENT_IP_ADDRESS, ""); - } - - /** - * Set the value for the data item with key "classname". - * Use of this item is not recommended (unless it is used to - * indicate something other than the Java classname) since - * it would be unwieldy to maintain a correct value across - * calls to/returns from methods in other classes. - * Use of the PatternLayout %c conversion character in the - * conversion string will give a more reliable value. - * - * @param id - */ - public void setClassname(String classname) { - context.put(CLASSNAME, classname); - } - /** - * Get the value for the data item with key "classname" - * @return current value, or empty string if not set - */ - public String getClassname() { - return context.get(CLASSNAME, ""); - } - - /** - * Set the value for the data item with key "timer". - * An alternative to calling this method directly is to call - * transactionStarted() at the start of transaction - * processing and transactionEnded() at the end, - * which will compute the time difference in milliseconds - * and store the result as the "timer" value. - * - * @param id - */ -// public void setTimer(Long timer) { -// context.put(TIMER, timer); -// } - -// public void setTimer(Long elapsedtime) { -// String unit = " milliseconds"; -// context.put(TRANSACTION_ELAPSED_TIME, elapsedtime + unit); -// } - - /** - * Get the value for the data item with key "timer" - * @return current value, or 0 if not set - */ -// public long getTimer() { -// return context.get(TRANSACTION_ELAPSED_TIME, 0); -// } - - /** - * Set the value for the data item with key "TransactionBeginTimestamp" - * - * @param id - */ - public void setTransactionBeginTimestamp(Instant transactionStartTime) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(transactionStartTime)); - context.put(TRANSACTION_BEGIN_TIME_STAMP, formatedTime ); - } - - /** - * Get the value for the data item with key "TransactionBeginTimestamp" - * @return current value, or 0 if not set - */ - public long getTransactionBeginTimestamp() { - return context.get(TRANSACTION_BEGIN_TIME_STAMP, 0); - } - - /** - * Set the value for the data item with key "TransactionEndTimestamp" - * - * @param id - */ - public void setTransactionEndTimestamp(Instant transactionEndTime) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(transactionEndTime)); - context.put(TRANSACTION_END_TIME_STAMP, formatedTime ); - } - - /** - * Get the value for the data item with key "TransactionEndTimestamp" - * @return current value, or 0 if not set - */ - public long getTransactionEndTimestamp() { - return context.get(TRANSACTION_END_TIME_STAMP, 0); - } - - /** - * Set the value for the data item with key "TransactionElapsedTime". - * An alternative to calling this method directly is to call - * transactionStarted() at the start of transaction - * processing and transactionEnded() at the end, - * which will compute the time difference in milliseconds - * and store the result as the "ns" value. - * - * @param id - */ - - public void setTransactionElapsedTime(Instant transactionEndTime) { - long ns = Duration.between(transactionStartTime, transactionEndTime).toMillis(); - //String unit = " Seconds"; - //if(ns == 1){ - //unit = " Second"; - //} - - //if(ns < 1){ - //ns = Duration.between(transactionStartTime, transactionEndTime).toMillis(); - //unit = " milliseconds"; - //} - context.put(TRANSACTION_ELAPSED_TIME, ns); // + unit); - } - - /** - * Get the value for the data item with key "TransactionElapsedTime" - * @return current value, or 0 if not set - */ - public long getTransactionElapsedTime() { - return context.get(TRANSACTION_ELAPSED_TIME, 0); - } - - /** - * Set the value for the data item with key "MetricBeginTimestamp" - * - * @param id - */ - public void setMetricBeginTimestamp(Instant metricStartTime) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(metricStartTime)); - context.put(METRIC_BEGIN_TIME_STAMP, formatedTime ); - } - - /** - * Get the value for the data item with key "MetricBeginTimestamp" - * @return current value, or 0 if not set - */ - public long getMetricBeginTimestamp() { - return context.get(METRIC_BEGIN_TIME_STAMP, 0); - } - - /** - * Set the value for the data item with key "MetricEndTimestamp" - * - * @param id - */ - public void setMetricEndTimestamp(Instant metricEndTime) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(metricEndTime)); - context.put(METRIC_END_TIME_STAMP, formatedTime ); - } - - /** - * Get the value for the data item with key "MetricEndTimestamp" - * @return current value, or 0 if not set - */ - public long getMetricEndTimestamp() { - return context.get(METRIC_END_TIME_STAMP, 0); - } - - /** - * Set the value for the data item with key "MetricElapsedTime". - * An alternative to calling this method directly is to call - * metricStarted() at the start of metric - * processing and metricEnded() at the end, - * which will compute the time difference in milliseconds - * and store the result as the "ns" value. - * - * @param id - */ - - public void setMetricElapsedTime(Instant metricEndTime) { - long ns = Duration.between(metricStartTime, metricEndTime).toMillis(); - //String unit = " Seconds"; - //if(ns == 1){ - //unit = " Second"; - //} - - //if(ns < 1){ - //ns = Duration.between(metricStartTime, metricEndTime).toMillis(); - //unit = " milliseconds"; - //} - context.put(METRIC_ELAPSED_TIME, ns); // + unit); - } - - /** - * Get the value for the data item with key "MetricElapsedTime" - * @return current value, or 0 if not set - */ - public long getMetricElapsedTime() { - return context.get(METRIC_ELAPSED_TIME, 0); - } - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingUtils.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingUtils.java deleted file mode 100644 index 5e6aa909..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/ECOMPLoggingUtils.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging; - -import javax.servlet.http.HttpServletRequest; - -public class ECOMPLoggingUtils { - - public static ECOMPLoggingContext getLoggingContextForRequest(HttpServletRequest request, - ECOMPLoggingContext baseContext) - { - ECOMPLoggingContext requestContext = new ECOMPLoggingContext(baseContext); - if (request.getLocalAddr() != null) { // may be null in junit tests - requestContext.setServerIPAddress(request.getLocalAddr()); - } - // get client IP address as leftmost address in X-Forwarded-For header if present, - // otherwise from remote address in the request - String forwarded = request.getHeader("X-Forwarded-For"); - if (forwarded != null && forwarded.trim().length() > 0) { - forwarded = forwarded.trim().split(",")[0]; - requestContext.setClientIPAddress(forwarded); - } else if (request.getRemoteAddr() != null) { // may be null in junit tests - requestContext.setClientIPAddress(request.getRemoteAddr()); - } - // RequestID - String requestId = request.getHeader("X-ECOMP-RequestID"); - if (requestId != null && requestId.trim().length() > 0) { - requestContext.setRequestID(requestId); - } - return requestContext; - } - - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/Configuration.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/Configuration.java deleted file mode 100644 index a839ea16..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/Configuration.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - - -public interface Configuration extends com.att.eelf.configuration.Configuration{ - - /** - * The Date-time of the start of a transaction - */ - public String BEGIN_TIME_STAMP = "BeginTimestamp"; - - /** - * The Date-time of the end of transaction - */ - public String END_TIME_STAMP = "EndTimestamp"; - - /** - * Externally advertised API invoked by clients of this component - */ - public String SERVICE_NAME = "ServiceName"; - - /** - * Client or user invoking the API - */ - public String PARTNER_NAME = "PartnerName"; - - /** - * Target Entity - */ - public String TARGET_ENTITY = "TargetEntity"; - - /** - * Target service name - */ - public String TARGET_SERVICE_NAME = "TargetServiceName"; - - /** - * High level success or failure (COMPLETE or ERROR) - */ - public String STATUS_CODE = "StatusCode"; - - /** - * Application specific response code - */ - public String RESPONSE_CODE = "ResponseCode"; - - /** - * Human readable description of the application specific response code - */ - public String RESPONSE_DESCRIPTION = "ResponseDescription"; - - /** - * Externally advertised API invoked by clients of this component - */ - public String ELAPSED_TIME = "ElapsedTime"; - - /** - * High level failure (ERROR) - */ - public String ERROR_CATEGORY = "ErrorCategory"; - - /** - * Error Code - */ - public String ERROR_CODE = "ErrorCode"; - - /** - * Error Description - */ - public String ERROR_DESCRIPTION = "ErrorDesciption"; - - /** - * Class name - */ - public String CLASS_NAME = "ClassName"; - - /** - * Server name - */ - public String SERVER_NAME = "ServerName"; - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/DroolsPDPMDCInfo.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/DroolsPDPMDCInfo.java deleted file mode 100644 index ad502475..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/DroolsPDPMDCInfo.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import java.util.concurrent.ConcurrentHashMap; - -public class DroolsPDPMDCInfo implements MDCInfo{ - - private static ConcurrentHashMap mdcMap = new ConcurrentHashMap(); - - static { - - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_REMOTE_HOST, ""); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_SERVICE_NAME, "Policy.droolsPdp"); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_SERVICE_INSTANCE_ID, "Policy.droolsPdp.event"); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_INSTANCE_UUID, ""); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.MDC_ALERT_SEVERITY, ""); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.PARTNER_NAME, "N/A"); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.STATUS_CODE, "N/A"); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.RESPONSE_CODE, "N/A"); - mdcMap.put(org.openecomp.policy.common.logging.eelf.Configuration.RESPONSE_DESCRIPTION, "N/A"); - - } - - @Override - /** - * @return the instance of ConcurrentHashMap - */ - public ConcurrentHashMap getMDCInfo() { - - return mdcMap; - } - - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/ErrorCodeMap.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/ErrorCodeMap.java deleted file mode 100644 index abd972e1..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/ErrorCodeMap.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import java.util.HashMap; - -/** - * - * ErrorCodeMap contains a HashMap of ErrorCodeInfo (error code and error description) - * - */ -public class ErrorCodeMap { - - - public static HashMap hm = new HashMap(); - - private static String ERROR_PERMISSIONS = "POLICY-100E"; - private static String ERROR_PERMISSIONS_DESCRIPTION = "This is a Permissions Error. Please check the error message for detail information"; - - private static String ERROR_SCHEMA_INVALID = "POLICY-400E"; - private static String ERROR_SCHEMA_INVALID_DESCRIPTION = "This is an Invalid Schema Error. Please check the error message for detail information"; - - private static String UPDATE_ERROR = "POLICY-502E"; - private static String UPDATE_ERROR_DESCRIPTION = "This is an updating error. Please check the error message for detail information"; - - private static String EXCEPTION_ERROR_CODE = "POLICY-503E"; - private static String EXCEPTION_ERROR_DESCRIPTION = "This is an exception error message during the process. Please check the error message for detail information"; - - private static String MISS_PROPERTY_ERROR = "POLICY-504E"; - private static String MISS_PROPERTY_ERROR_DESCRIPTION = "This is an error of missing properties. Please check the error message for detail information"; - - private static String GENERAL_ERROR_CODE = "POLICY-515E"; - private static String GENERAL_ERROR_DESCRIPTION = "This is a general error message during the process. Please check the error message for detail information"; - - private static String ERROR_SYSTEM_ERROR = "POLICY-516E"; - private static String ERROR_SYSTEM_ERROR_DESCRIPTION = "This is a System Error. Please check the error message for detail information"; - - private static String ERROR_DATA_ISSUE = "POLICY-517E"; - private static String ERROR_DATA_ISSUE_DESCRIPTION = "This is a Data Issue Error. Please check the error message for detail information"; - - private static String ERROR_PROCESS_FLOW = "POLICY-518E"; - private static String ERROR_PROCESS_FLOW_DESCRIPTION = "This is a Process Flow Error. Please check the error message for detail information"; - - private static String ERROR_UNKNOWN = "POLICY-519E"; - private static String ERROR_UNKNOWN_DESCRIPTION = "This is an Unknown Error. Please check the error message for detail information"; - - private static String ERROR_AUDIT = "POLICY-520E"; - private static String ERROR_AUDIT_DESCRIPTION = "This is an audit Error. Please check the error message for detail information"; - - static { - hm.put(MessageCodes.EXCEPTION_ERROR, new ErrorCodeInfo(EXCEPTION_ERROR_CODE, EXCEPTION_ERROR_DESCRIPTION)); - hm.put(MessageCodes.GENERAL_ERROR, new ErrorCodeInfo(GENERAL_ERROR_CODE, GENERAL_ERROR_DESCRIPTION)); - hm.put(MessageCodes.MISS_PROPERTY_ERROR, new ErrorCodeInfo(MISS_PROPERTY_ERROR, MISS_PROPERTY_ERROR_DESCRIPTION)); - hm.put(MessageCodes.UPDATE_ERROR, new ErrorCodeInfo(UPDATE_ERROR, UPDATE_ERROR_DESCRIPTION)); - hm.put(MessageCodes.ERROR_SYSTEM_ERROR, new ErrorCodeInfo(ERROR_SYSTEM_ERROR, ERROR_SYSTEM_ERROR_DESCRIPTION)); - hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); - hm.put(MessageCodes.ERROR_PERMISSIONS, new ErrorCodeInfo(ERROR_PERMISSIONS, ERROR_PERMISSIONS_DESCRIPTION)); - hm.put(MessageCodes.ERROR_DATA_ISSUE, new ErrorCodeInfo(ERROR_DATA_ISSUE, ERROR_DATA_ISSUE_DESCRIPTION)); - hm.put(MessageCodes.ERROR_PROCESS_FLOW, new ErrorCodeInfo(ERROR_PROCESS_FLOW, ERROR_PROCESS_FLOW_DESCRIPTION)); - hm.put(MessageCodes.ERROR_SCHEMA_INVALID, new ErrorCodeInfo(ERROR_SCHEMA_INVALID, ERROR_SCHEMA_INVALID_DESCRIPTION)); - hm.put(MessageCodes.ERROR_UNKNOWN, new ErrorCodeInfo(ERROR_UNKNOWN, ERROR_UNKNOWN_DESCRIPTION)); - hm.put(MessageCodes.ERROR_AUDIT, new ErrorCodeInfo(ERROR_AUDIT, ERROR_AUDIT_DESCRIPTION)); - } - - static class ErrorCodeInfo { - - private String errorCode; - private String errorDesc; - - public ErrorCodeInfo(String errorCode, String errorDesc){ - this.errorCode = errorCode; - this.errorDesc = errorDesc; - } - - public String getErrorCode() { - return errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - public String getErrorDesc() { - return errorDesc; - } - - public void setErrorDesc(String errorDesc) { - this.errorDesc = errorDesc; - } - - } - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventData.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventData.java deleted file mode 100644 index d26a4977..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventData.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import java.time.Instant; - -/** - * - * EventData can be used for logging a rule event. - * - */ -public class EventData { - - private String requestID = null; - private Instant startTime = null; - private Instant endTime = null; - - public EventData() { - - } - - public EventData(String requestID, Instant startTime, Instant endTime) { - - this.requestID = requestID; - this.startTime = startTime; - this.endTime = endTime; - } - - public String getRequestID() { - return requestID; - } - - public void setRequestID(String requestID) { - this.requestID = requestID; - } - - public Instant getStartTime() { - return startTime; - } - - public void setStartTime(Instant startTime) { - this.startTime = startTime; - } - - public Instant getEndTime() { - return endTime; - } - - public void setEndTime(Instant endTime) { - this.endTime = endTime; - } - - public String toString(){ - return requestID + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((requestID == null) ? 0 : requestID.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (obj instanceof String) { - String requestId = (String) obj; - if(requestID != null && requestID.equals(requestId)){ - return true; - } - return false; - } - if (getClass() != obj.getClass()) - return false; - EventData other = (EventData) obj; - if (requestID == null) { - if (other.requestID != null) - return false; - } else if (!requestID.equals(other.requestID)) - return false; - return true; - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfo.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfo.java deleted file mode 100644 index f1b7afb5..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfo.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * EventTrackInfo contains a ConcurrentHashMap of EventData - * - */ -public class EventTrackInfo { - - private ConcurrentHashMap eventInfo = null; - - public EventTrackInfo() { - /* - * An initial capacity of 16 ensures the number of elements before resizing happens - * Load factor of 0,9 ensures a dense packaging inside ConcurrentHashMap which will optimize memory use - * ConcurencyLevel set to 1 will ensure that only one shard is created and maintained - */ - eventInfo = new ConcurrentHashMap(16, 0.9f, 1); - } - - /** - * Returns an instance of EventData associated to this requestID - * @param requestID - * @return EventData - */ - public EventData getEventDataByRequestID(String requestID){ - return eventInfo.get(requestID); - } - - /** - * Stores an EventData object in a ConcurrentHashMap using its requestID as key. - * @param event - */ - public void storeEventData(EventData event){ - - if(event == null || event.getRequestID() == null || event.getRequestID().isEmpty()){ - return; - } - //in case override the start time, check the original event was already stored or not - if(!eventInfo.containsKey(event.getRequestID())){ - eventInfo.put(event.getRequestID(), event); - } - } - - /** - * Removes an EventData object from a ConcurrentHashMap using the eventId as key. - * @param eventId - */ - public void remove(String eventId){ - if(eventInfo != null){ - eventInfo.remove(eventId); - } - } - - /** - * Returns a ConcurrentHashMap of EventData - */ - public ConcurrentHashMap getEventInfo() { - return eventInfo; - } - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfoHandler.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfoHandler.java deleted file mode 100644 index e45f8998..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/EventTrackInfoHandler.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.TimerTask; - -/** - * - * EventTrackInfoHandler is the handler of clean up all expired event objcts - * - */ -public class EventTrackInfoHandler extends TimerTask { - - String className = this.getClass().getSimpleName(); - - @Override - public void run() { - - PolicyLogger.info(className - + " Release expired event records start..."); - - CleanUp(); - - PolicyLogger.info(className + " Release expired event records done"); - } - - /** - * Removes all expired event objects from the ConcurrentHashMap of EventData - */ - private void CleanUp() { - - if (PolicyLogger.getEventTracker() == null - || PolicyLogger.getEventTracker().getEventInfo() == null - || PolicyLogger.getEventTracker().getEventInfo().isEmpty()) { - return; - } - - Instant startTime = null; - long ns = 0; - - ArrayList expiredEvents = null; - - for (String key: PolicyLogger.getEventTracker().getEventInfo().keySet()) { - EventData event = PolicyLogger.getEventTracker().getEventInfo().get(key); - startTime = event.getStartTime(); - ns = Duration.between(startTime, Instant.now()).getSeconds(); - - PolicyLogger.info(className - + " duration time : " + ns); - - PolicyLogger.info(className - + " PolicyLogger.EXPIRED_TIME : " + PolicyLogger.EXPIRED_TIME); - - // if longer than EXPIRED_TIME, remove the object - - if (ns > PolicyLogger.EXPIRED_TIME){ - if (expiredEvents == null) { - expiredEvents = new ArrayList(); - } - expiredEvents.add(key); - - PolicyLogger.info(className - + " add expired event request ID: " - + event.getRequestID()); - } - } - - synchronized (PolicyLogger.getEventTracker().getEventInfo()) { - if (expiredEvents != null) { - for (String expiredKey : expiredEvents) { - PolicyLogger.getEventTracker().getEventInfo() - .remove(expiredKey); - System.out.println(className - + " removed expired event request ID: " - + expiredKey); - PolicyLogger.info(className - + " removed expired event request ID: " - + expiredKey); - } - } - - } - - } - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MDCInfo.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MDCInfo.java deleted file mode 100644 index 6b5e395f..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MDCInfo.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * Interface needs to be implemented by DroolsPDPMDCInfo - * - */ - -public interface MDCInfo { - - public ConcurrentHashMap getMDCInfo(); - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MessageCodes.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MessageCodes.java deleted file mode 100644 index 6f1437eb..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/MessageCodes.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import com.att.eelf.i18n.EELFResolvableErrorEnum; -import com.att.eelf.i18n.EELFResourceManager; - -/** - * - * MessageCodes contains all the messagge codes for EELF logging messages - * - */ -public enum MessageCodes implements EELFResolvableErrorEnum { - // Below is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants - // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java - - ERROR_PERMISSIONS, - - ERROR_SYSTEM_ERROR, - - ERROR_DATA_ISSUE, - - ERROR_SCHEMA_INVALID, - - ERROR_PROCESS_FLOW, - - ERROR_UNKNOWN, - - ERROR_AUDIT, - - // Above is a list of Error Messages taken from com.att.research.xacml.api XACMLErrorConstants - // found under: policy-engine\XACML\src\main\java\com\att\research\xacml\api\XACMLErrorConstants.java - - //----------------------5000-5099 Business/Flow Processing Related --------------------/ - - BAD_TYPE_WARNING, - - GENERAL_INFO, - - GENERAL_WARNING, - - MISS_PROPERTY_ERROR, - - EXCEPTION_ERROR, - - MISS_PROPERTY_INFO, - - RULE_AUDIT_EXEC_INFO, - - RULE_AUDIT_BEGIN_INFO, - - RULE_AUDIT_END_INFO, - - RULE_AUDIT_START_END_INFO, - - RULE_METRICS_INFO, - - UEB_AUDIT_EXEC_INFO, - - UEB_AUDIT_BEGIN_INFO, - - UEB_AUDIT_END_INFO, - - UPDATE_ERROR, - - GENERAL_ERROR, - - //----------------------New enums should be added above this line ------------------------------------------------------------------/ - - //--------------------- The enums below are old code. They should not be used since 1607 release and eventually will be removed -----/ - /** - * Application message which requires no arguments - */ - MESSAGE_SAMPLE_NOARGS, - - /** - * Application message which requires one argument {0} - */ - MESSAGE_SAMPLE_ONEARGUMENT, - - /** - * Audit message which requires one argument {0} - */ - AUDIT_MESSAGE_ONEARGUMENT, - - /** - * Error message which requires one argument {0} - */ - ERROR_MESSAGE_ONEARGUMENT, - - /** - * Metrics message which requires one argument {0} - */ - METRICS_MESSAGE_ONEARGUMENT, - - /** - * Debug message which requires one argument {0} - */ - DEBUG_MESSAGE_ONEARGUMENT, - - /** - * Application message which requires two argument {0} and another argument {1} - */ - MESSAGE_SAMPLE_TWOARGUMENTS, - - /** - * Sample error exception - */ - MESSAGE_SAMPLE_EXCEPTION, - - /** - * Sample warning message - */ - MESSAGE_WARNING_SAMPLE, - - /** - * Sample exception in method {0} - */ - MESSAGE_SAMPLE_EXCEPTION_ONEARGUMENT, - - /** - * Sample trace message - */ - MESSAGE_TRACE_SAMPLE, - - /** - * Sample error message - */ - MESSAGE_ERROR_SAMPLE; - - - /** - * Static initializer to ensure the resource bundles for this class are loaded... - * Here this application loads messages from three bundles - */ - static { - EELFResourceManager.loadMessageBundle("org/openecomp/policy/common/logging/eelf/Resources"); - String id = EELFResourceManager.getIdentifier(RULE_AUDIT_EXEC_INFO); - String value = EELFResourceManager.getMessage(RULE_AUDIT_EXEC_INFO); - - System.out.println("*********************** " + id); - System.out.println("*********************** " + value); - - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/PolicyLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/PolicyLogger.java deleted file mode 100644 index 8cc73743..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/eelf/PolicyLogger.java +++ /dev/null @@ -1,1448 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.eelf; - -import org.slf4j.MDC; - -import static org.openecomp.policy.common.logging.eelf.Configuration.*; - -import org.openecomp.policy.common.logging.flexlogger.LoggerType; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFLogger.Level; -import com.att.eelf.configuration.EELFManager; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.text.SimpleDateFormat; -import java.time.Duration; -import java.time.Instant; -import java.util.Date; -import java.util.Iterator; -import java.util.Properties; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * PolicyLogger contains all the static methods for EELF logging - * - */ -public class PolicyLogger { - - private static EELFLogger errorLogger = EELFManager.getInstance() - .getErrorLogger(); - - private static EELFLogger metricsLogger = EELFManager.getInstance() - .getMetricsLogger(); - - private static EELFLogger auditLogger = EELFManager.getInstance() - .getAuditLogger(); - - private static EELFLogger debugLogger = EELFManager.getInstance() - .getDebugLogger(); - - private static EventTrackInfo eventTracker = new EventTrackInfo(); - - private static String hostName = null; - private static String hostAddress = null; - private static String component = null; - - private static TimerTask ttrcker = null; - private static boolean isEventTrackerRunning = false; - private static Timer timer = null; - - //Default:Timer initial delay and the delay between in milliseconds before task is to be execute - private static int TIMER_DELAY_TIME = 1000; - - //Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task executions - private static int CHECK_INTERVAL = 30 * 1000; - - //Default:longest time an event info can be stored in the concurrentHashMap for logging - in seconds - static int EXPIRED_TIME = 60*60*1000*24; //one day - - //Default:the size of the concurrentHashMap which stores the event starting time - when its size reaches this limit, the Timer get executed - private static int CONCURRENTHASHMAP_LIMIT = 5000; - - //Default:the size of the concurrentHashMap which stores the event starting time - when its size drops to this point, stop the Timer - private static int STOP_CHECK_POINT = 2500; - - private static boolean isOverrideLogbackLevel = false; - - public static Level DEBUG_LEVEL = Level.INFO; - public static Level AUDIT_LEVEL = Level.INFO; - public static Level METRICS_LEVEL = Level.INFO; - public static Level ERROR_LEVEL = Level.ERROR; - public static String CLASS_NAME = "ClassName"; - - - static{ - if (hostName == null || hostAddress == null) { - try { - hostName = InetAddress.getLocalHost().getHostName(); - hostAddress = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger", "UnknownHostException"); - } - } - } - - /** - * Populates MDC info - * @param transId - * @return String - */ - public static String postMDCInfoForEvent(String transId) { - MDC.clear(); - - if(transId == null || transId.isEmpty()){ - transId = UUID.randomUUID().toString(); - } - - if(component != null && component.equalsIgnoreCase("DROOLS")){ - MDC.put(TARGET_ENTITY, "POLICY"); - MDC.put(TARGET_SERVICE_NAME, "drools evaluate rule"); - return postMDCInfoForEvent(transId, new DroolsPDPMDCInfo()); - } else { - // For Xacml - MDC.put(TARGET_ENTITY, "POLICY"); - MDC.put(TARGET_SERVICE_NAME, "PE Process"); - } - - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, transId); - MDC.put(MDC_SERVICE_NAME, "Policy.xacmlPdp"); - MDC.put(MDC_SERVICE_INSTANCE_ID, "Policy.xacmlPdp.event"); - try { - MDC.put(MDC_SERVER_FQDN, hostName); - MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); - } catch (Exception e) { - errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger"); - } - Instant startTime = Instant.now(); - Instant endTime = Instant.now(); - long ns = Duration.between(startTime, endTime).toMillis(); // use millisecond as default and remove unit from log - //String unit = " Seconds"; - //if(ns == 1){ - //unit = " Second"; - //} - - //if(ns < 1){ - //ns = Duration.between(startTime, endTime).toMillis(); - //unit = " milliseconds"; - //} - MDC.put(MDC_INSTANCE_UUID, ""); - MDC.put(MDC_ALERT_SEVERITY, ""); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); - - MDC.put(PARTNER_NAME, "N/A"); - - MDC.put(STATUS_CODE, "COMPLETE"); - MDC.put(RESPONSE_CODE, "N/A"); - MDC.put(RESPONSE_DESCRIPTION, "N/A"); - - - return transId; - - } - - /** - * Populate MDC Info using the passed in mdcInfo - * @param transId - * @param mdcInfo - * @return String - */ - private static String postMDCInfoForEvent(String transId, MDCInfo mdcInfo ) { - - MDC.put(MDC_KEY_REQUEST_ID, transId); - if(mdcInfo != null && mdcInfo.getMDCInfo() != null && !mdcInfo.getMDCInfo().isEmpty()){ - - ConcurrentHashMap mdcMap = mdcInfo.getMDCInfo(); - Iterator keyIterator = mdcMap.keySet().iterator(); - String key = ""; - - while(keyIterator.hasNext()){ - key = keyIterator.next(); - MDC.put(key, mdcMap.get(key)); - } - } - - try { - MDC.put(MDC_SERVER_FQDN, hostName); - MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); - } catch (Exception e) { - errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger"); - } - Instant startTime = Instant.now(); - Instant endTime = Instant.now(); - long ns = Duration.between(startTime, endTime).toMillis(); // use millisecond as default and remove unit from log - //String unit = " Seconds"; - //if(ns == 1){ - //unit = " Second"; - //} - - //if(ns < 1){ - //ns = Duration.between(startTime, endTime).toMillis(); - //unit = " milliseconds"; - //} - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); - - return transId; - } - - /** - * Set Timestamps for start, end and duration of logging a transaction - */ - private static void seTimeStamps(){ - - Instant startTime = Instant.now(); - Instant endTime = Instant.now(); - long ns = Duration.between(startTime, endTime).toMillis(); - //String unit = " Seconds"; - //if(ns == 1){ - //unit = " Second"; - //} - - //if(ns < 1){ - //ns = Duration.between(startTime, endTime).toMillis(); - //unit = " milliseconds"; - //} - MDC.put(MDC_INSTANCE_UUID, ""); - MDC.put(MDC_ALERT_SEVERITY, ""); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); - - MDC.put(PARTNER_NAME, "N/A"); - - MDC.put(STATUS_CODE, "COMPLETE"); - MDC.put(RESPONSE_CODE, "N/A"); - MDC.put(RESPONSE_DESCRIPTION, "N/A"); - - } - - /** - * Sets transaction Id to MDC - * @param transId - */ - public static void setTransId(String transId){ - - MDC.put(MDC_KEY_REQUEST_ID, transId); - } - - /** - * Returns current transaction Id used in MDC - * @return transId - */ - public static String getTransId(){ - - return MDC.get(MDC_KEY_REQUEST_ID); - } - - /** - * Sets transaction Id to MDC - * @param o - */ - public static void postMDCInfoForEvent(Object o){ - postMDCInfoForEvent(""+o); - } - - /** - * Resets transaction Id in MDC for the rule triggered by this event - * @param transId - * @return String - */ - public static String postMDCInfoForTriggeredRule(String transId) { - - MDC.clear(); - - if(transId == null || transId.isEmpty()){ - transId = UUID.randomUUID().toString(); - } - MDC.put(MDC_REMOTE_HOST, ""); - MDC.put(MDC_KEY_REQUEST_ID, transId); - MDC.put(MDC_SERVICE_NAME, "Policy.droolsPdp"); - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - try { - MDC.put(MDC_SERVER_FQDN, hostName); - MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress); - } catch (Exception e) { - errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyLogger"); - } - MDC.put(MDC_INSTANCE_UUID, ""); - MDC.put(MDC_ALERT_SEVERITY, ""); - MDC.put(STATUS_CODE, "COMPLETE"); - - return transId; - - } - - /** - * Resets transaction Id in MDC for the rule triggered by this event - * @param o - */ - public static void postMDCUUIDForTriggeredRule(Object o) { - - postMDCInfoForTriggeredRule("" + o); - - } - - // ************************************************************************************************ - /** - * Records the Info event with String [] arguments - * @param msg - * @param arguments - */ - public static void info(MessageCodes msg, String... arguments) { - MDC.put(CLASS_NAME, ""); - debugLogger.info(msg, arguments); - } - - /** - * Records the Info event with String [] arguments - * @param msg - * @param className - * @param arguments - */ - public static void info(MessageCodes msg, String className, String... arguments) { - MDC.put(CLASS_NAME, className); - debugLogger.info(msg, arguments); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void info( String className, String arg0) { - MDC.put(CLASS_NAME, className); - debugLogger.info(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message without its class name passed in - * @param arg0 - */ - public static void info(String arg0) { - MDC.put(CLASS_NAME, ""); - debugLogger.info(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void info(Object arg0) { - MDC.put(CLASS_NAME, ""); - info(arg0); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void info(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, ""); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.info(msg, arguments2); - } - - /** - * Records a message with passed in message code, class name, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void info(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, className); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.info(msg, arguments2); - } - - /** - * Records only one String message with its class name - * @param arg0 log message - * @param className class name - */ - public static void warn( String className, String arg0) { - MDC.put(CLASS_NAME, className); - debugLogger.warn(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void warn(Object arg0) { - MDC.put(CLASS_NAME, ""); - debugLogger.warn(MessageCodes.GENERAL_WARNING, "" + arg0); - } - - /** - * Records only one String message without its class name passed in - * @param arg0 - */ - public static void warn(String arg0) { - MDC.put(CLASS_NAME, ""); - debugLogger.warn(MessageCodes.GENERAL_WARNING, arg0); - } - - /** - * Records a message with passed in message code and a list of string values - * @param msg - * @param arguments - */ - public static void warn(MessageCodes msg, String... arguments) { - MDC.put(CLASS_NAME, ""); - debugLogger.warn(msg, arguments); - } - - /** - * Records a message with passed in message code, class name and a list of string values - * @param msg - * @param className - * @param arguments - */ - public static void warn(MessageCodes msg, String className, String... arguments) { - MDC.put(CLASS_NAME, className); - debugLogger.warn(msg, arguments); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void warn(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, ""); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.warn(msg, arguments2); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void warn(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, className); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - debugLogger.warn(msg, arguments2); - } - - /** - * Records only one String message with its class name - * @param className class name - * @param arg0 log message - */ - public static void error( String className, String arg0) { - MDC.put(CLASS_NAME, className); - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void error(String arg0) { - MDC.put(CLASS_NAME, ""); - MDC.put(ERROR_CATEGORY, "ERROR"); - - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error(MessageCodes.GENERAL_ERROR, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void error(Object arg0) { - MDC.put(CLASS_NAME, ""); - MDC.put(ERROR_CATEGORY, "ERROR"); - - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0); - } - - /** - * Records a message with passed in message code, Throwable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void error(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, ""); - MDC.put(ERROR_CATEGORY, "ERROR"); - - if(ErrorCodeMap.hm.get(msg) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); - - } - String arguments2 = getNormalizedStackTrace(arg0, arguments); - errorLogger.error(msg, arguments2); - } - - /** - * Records a message with passed in message code, class name, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void error(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, className); - MDC.put(ERROR_CATEGORY, "ERROR"); - - if(ErrorCodeMap.hm.get(msg) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); - - } - String arguments2 = getNormalizedStackTrace(arg0, arguments); - errorLogger.error(msg, arguments2); - } - - /** - * Records a message with passed in message code and a list of string values - * @param msg - * @param arguments - */ - public static void error(MessageCodes msg, String... arguments) { - MDC.put(CLASS_NAME, ""); - MDC.put(ERROR_CATEGORY, "ERROR"); - - if(ErrorCodeMap.hm.get(msg) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(msg).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(msg).getErrorDesc()); - - } - errorLogger.error(msg, arguments); - } - - /** - * Records a message with passed in message code and a list of string values - * @param msg - * @param arguments - */ - public static void debug(MessageCodes msg, String... arguments) { - MDC.put(CLASS_NAME, ""); - debugLogger.debug(msg, arguments); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void debug( String className, String arg0) { - MDC.put(CLASS_NAME, className); - debugLogger.debug(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void debug(String arg0) { - MDC.put(CLASS_NAME, ""); - debugLogger.debug(arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void debug(Object arg0) { - - MDC.put(CLASS_NAME, ""); - debugLogger.debug("" + arg0); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void audit(String className, Object arg0) { - MDC.put(STATUS_CODE, "COMPLETE"); - MDC.put(CLASS_NAME, className); - auditLogger.info("" + arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void audit(Object arg0) { - MDC.put(STATUS_CODE, "COMPLETE"); - MDC.put(CLASS_NAME, ""); - auditLogger.info("" + arg0); - } - - /** - * Records a message with passed in message code, hrowable object, a list of string values - * @param msg - * @param arg0 - * @param arguments - */ - public static void debug(MessageCodes msg, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, ""); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - errorLogger.error(msg, arguments2); - } - - /** - * Records a message with passed in message code, class name, Throwable object, a list of string values - * @param msg - * @param className - * @param arg0 - * @param arguments - */ - public static void debug(MessageCodes msg, String className, Throwable arg0, - String... arguments) { - MDC.put(CLASS_NAME, className); - String arguments2 = getNormalizedStackTrace(arg0, arguments); - errorLogger.error(msg, arguments2); - } - /** - * returns true for enabled, false for not enabled - */ - public static boolean isDebugEnabled(){ - - return debugLogger.isDebugEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isErrorEnabled(){ - - return errorLogger.isErrorEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isWarnEnabled(){ - - return debugLogger.isWarnEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isInfoEnabled1(){ - - return debugLogger.isInfoEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isAuditEnabled(){ - - return debugLogger.isInfoEnabled(); - } - - /** - * returns true for enabled, false for not enabled - */ - public static boolean isInfoEnabled(){ - - return debugLogger.isInfoEnabled(); - } - - /** - * Records only one String message with its class name - * @param className - * @param arg0 - */ - public static void trace( String className, String arg0) { - MDC.put(CLASS_NAME, className); - errorLogger.info(MessageCodes.GENERAL_INFO, arg0); - } - - /** - * Records only one String message - * @param arg0 - */ - public static void trace(Object arg0){ - - MDC.put(CLASS_NAME, ""); - debugLogger.trace(""+arg0); - } - /** - * Records the starting time of the event with its request Id as the key - * @param eventId - */ - public static void recordAuditEventStart(String eventId) { - - MDC.put(STATUS_CODE, "COMPLETE"); - postMDCInfoForEvent(eventId); - - if(eventTracker == null){ - eventTracker = new EventTrackInfo(); - } - EventData event = new EventData(); - event.setRequestID(eventId); - event.setStartTime(Instant.now()); - eventTracker.storeEventData(event); - MDC.put(MDC_KEY_REQUEST_ID, eventId); - debugLogger.info("CONCURRENTHASHMAP_LIMIT : " + CONCURRENTHASHMAP_LIMIT); - //--- Tracking the size of the concurrentHashMap, if it is above limit, keep EventTrack Timer running - int size = eventTracker.getEventInfo().size(); - - debugLogger.info("EventInfo concurrentHashMap Size : " + size + " on " + new Date()); - debugLogger.info("isEventTrackerRunning : " + isEventTrackerRunning); - - if( size >= CONCURRENTHASHMAP_LIMIT){ - - - if(!isEventTrackerRunning){ - - startCleanUp(); - isEventTrackerRunning = true; - } - - }else if( size <= STOP_CHECK_POINT){ - - if(isEventTrackerRunning){ - stopCleanUp(); - } - } - } - - /** - * Records the starting time of the event with its request Id as the key - * @param eventId - */ - public static void recordAuditEventStart(UUID eventId) { - - if(eventId == null){ - return; - } - - if(eventTracker == null){ - eventTracker = new EventTrackInfo(); - } - - recordAuditEventStart(eventId.toString()); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - */ - public static void recordAuditEventEnd(String eventId, String rule) { - - if(eventTracker == null){ - return; - } - if(eventId == null){ - return; - } - - creatAuditEventTrackingRecord(eventId, rule, ""); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - * @param policyVersion - */ - public static void recordAuditEventEnd(String eventId, String rule , String policyVersion) { - - if(eventTracker == null){ - return; - } - if(eventId == null){ - return; - } - - creatAuditEventTrackingRecord(eventId, rule, policyVersion); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - * @param policyVersion - */ - public static void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - - if(eventId == null){ - return; - } - - recordAuditEventEnd(eventId.toString(), rule, policyVersion); - - } - - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - */ - public static void recordAuditEventEnd(UUID eventId, String rule) { - - if(eventId == null){ - return; - } - - recordAuditEventEnd(eventId.toString(), rule); - - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - * @param policyVersion - */ - public static void creatAuditEventTrackingRecord(String eventId, String rule, String policyVersion) { - - if(eventTracker == null){ - return; - } - - EventData event = eventTracker.getEventDataByRequestID(eventId); - - if(event != null){ - Instant endTime = event.getEndTime(); - if(endTime == null){ - endTime = Instant.now(); - } - MDC.put(STATUS_CODE, "COMPLETE"); - recordAuditEventStartToEnd(eventId, rule, event.getStartTime(), endTime, policyVersion); - } - } - - /** - * Records the ending time of the event with its request Id as the key - * @param eventId - * @param rule - */ - public static void creatAuditEventTrackingRecord(UUID eventId, String rule) { - - if(eventId == null){ - return; - } - - if(eventTracker == null){ - return; - } - - EventData event = eventTracker.getEventDataByRequestID(eventId.toString()); - - if(event != null){ - Instant endTime = event.getEndTime(); - if(endTime == null){ - endTime = Instant.now(); - } - - recordAuditEventStartToEnd(eventId.toString(), rule, event.getStartTime(), endTime, "N/A"); - } - } - - public static EventTrackInfo getEventTracker() { - return eventTracker; - } - - /** - * Records the audit with an event starting and ending times - * @param eventId - * @param rule - * @param startTime - * @param endTime - * @param policyVersion - */ - public static void recordAuditEventStartToEnd(String eventId, String rule, Instant startTime, Instant endTime, String policyVersion) { - - if(startTime == null || endTime == null){ - return; - } - String serviceName = MDC.get(MDC_SERVICE_NAME); - if(eventId != null && !eventId.isEmpty()){ - MDC.put(MDC_KEY_REQUEST_ID, eventId); - } - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - - String formatedTime = sdf.format(Date.from(startTime)); - MDC.put(BEGIN_TIME_STAMP, formatedTime ); - - //set default values for these required fields below, they can be overridden - formatedTime = sdf.format(Date.from(endTime)); - MDC.put(END_TIME_STAMP, formatedTime); - - MDC.put(RESPONSE_CODE, "N/A"); - MDC.put(RESPONSE_DESCRIPTION, "N/A"); - - long ns = Duration.between(startTime, endTime).toMillis(); - //String unit = " Seconds"; - //if(ns == 1){ - //unit = " Second"; - //} - - //if(ns < 1){ - //ns = Duration.between(startTime, endTime).toMillis(); - //unit = " milliseconds"; - //} - - MDC.put(ELAPSED_TIME, Long.toString(ns)); // + unit); - - auditLogger.info(MessageCodes.RULE_AUDIT_START_END_INFO, - serviceName, rule, startTime.toString(), endTime.toString(), Long.toString(ns), policyVersion); - - //--- remove the record from the concurrentHashMap - if(eventTracker != null){ - if(eventTracker.getEventDataByRequestID(eventId) != null){ - eventTracker.remove(eventId); - debugLogger.info("eventTracker.remove(" + eventId + ")"); - } - } - } - - /** - * Records the metrics with an event Id and log message - * @param eventId - * @param arg1 - */ - public static void recordMetricEvent(String eventId, String arg1) { - - seTimeStamps(); - - String serviceName = MDC.get(MDC_SERVICE_NAME); - MDC.put(MDC_KEY_REQUEST_ID, eventId); - metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, - serviceName, arg1); - - } - - /** - * Records the metrics with an event Id, class name and log message - * @param eventId - * @param className - * @param arg1 - */ - public static void recordMetricEvent(String eventId, String className,String arg1) { - - seTimeStamps(); - - MDC.put(CLASS_NAME, className); - String serviceName = MDC.get(MDC_SERVICE_NAME); - MDC.put(MDC_KEY_REQUEST_ID, eventId); - metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, - serviceName, arg1); - } - - /** - * Records the metrics with an event Id and log message - * @param eventId - * @param arg1 - */ - public static void recordMetricEvent(UUID eventId, String arg1) { - - if(eventId == null){ - return; - } - String serviceName = MDC.get(MDC_SERVICE_NAME); - MDC.put(MDC_KEY_REQUEST_ID, eventId.toString()); - metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, - serviceName, arg1); - } - - /** - * Records a String message for metrics logs - * @param arg0 - */ - public static void recordMetricEvent(String arg0) { - seTimeStamps(); - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, arg0); - } - - - /** - * Records the metrics event with a String message - * @param arg0 - */ - public static void metrics(String arg0) { - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, arg0); - } - - /** - * Records the metrics event with a class name and a String message - * @param arg0 - */ - public static void metrics(String className, Object arg0) { - seTimeStamps(); - MDC.put(CLASS_NAME, className); - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, ""+arg0); - } - - /** - * Records the metrics event with a String message - * @param arg0 - */ - public static void metrics(Object arg0) { - seTimeStamps(); - MDC.put(CLASS_NAME, ""); - String serviceName = MDC.get(MDC_SERVICE_NAME); - metricsLogger.info(MessageCodes.RULE_METRICS_INFO, - serviceName, ""+arg0); - } - - /** - * Records the metrics event with a String message - * @param arg0 - */ - public static void metricsPrintln(String arg0) { - MDC.clear(); - metricsLogger.info(arg0); - } - - /** - * Removes all the return lines from the printStackTrace - * @param t - * @param arguments - */ - private static String getNormalizedStackTrace (Throwable t, String...arguments) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - String newStValue = sw.toString().replace ('|', '!').replace ("\n", " - "); - int curSize = (arguments == null ? 0 : arguments.length); - StringBuffer newArgument = new StringBuffer(); - for(int i=0; i 0){ - - TIMER_DELAY_TIME = timerDelayTime; - - }else { - MDC.put(ERROR_CATEGORY, "ERROR"); - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the timer.delay.time, so use its default value: " + TIMER_DELAY_TIME); - } - - if (checkInterval > 0){ - - CHECK_INTERVAL = checkInterval; - - }else { - MDC.put(ERROR_CATEGORY, "ERROR"); - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the check.interval, so use its default value: " + CHECK_INTERVAL); - } - - if (expiredDate > 0){ - - EXPIRED_TIME = expiredDate; - - }else { - MDC.put(ERROR_CATEGORY, "ERROR"); - - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the event.expired.time, so use its default value: " + EXPIRED_TIME); - } - - if (concurrentHashMapLimit > 0){ - - CONCURRENTHASHMAP_LIMIT = concurrentHashMapLimit; - - }else { - MDC.put(ERROR_CATEGORY, "ERROR"); - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the concurrentHashMap.limit, so use its default value: " + CONCURRENTHASHMAP_LIMIT); - } - - if (stopCheckPoint > 0){ - - STOP_CHECK_POINT = stopCheckPoint; - - }else { - MDC.put(ERROR_CATEGORY, "ERROR"); - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the stop.check.point, so use its default value: " + STOP_CHECK_POINT); - } - - if (loggerType != null){ - - if (loggerType.equalsIgnoreCase("EELF")){ - - logger_type = LoggerType.EELF; - - }else if (loggerType.equalsIgnoreCase("LOG4J")){ - - logger_type = LoggerType.LOG4J; - - }else if (loggerType.equalsIgnoreCase("SYSTEMOUT")){ - - logger_type = LoggerType.SYSTEMOUT; - - } - - } - - if (debugLevel != null && !debugLevel.isEmpty()){ - - DEBUG_LEVEL = Level.valueOf(debugLevel); - - } - //Only check if it is to turn off or not - if (errorLevel != null && errorLevel.equalsIgnoreCase(Level.OFF.toString())){ - - ERROR_LEVEL = Level.valueOf(errorLevel); - - } - //Only check if it is to turn off or not - if (metricsLevel != null && metricsLevel.equalsIgnoreCase(Level.OFF.toString())){ - - METRICS_LEVEL = Level.valueOf(metricsLevel); - - } - //Only check if it is to turn off or not - if (auditLevel != null && auditLevel.equalsIgnoreCase(Level.OFF.toString())){ - - AUDIT_LEVEL = Level.valueOf(auditLevel); - - } - - }catch(Exception e){ - MDC.put(ERROR_CATEGORY, "ERROR"); - - if(ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR) != null){ - MDC.put(ERROR_CODE, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorCode()); - MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.hm.get(MessageCodes.GENERAL_ERROR).getErrorDesc()); - - } - errorLogger.error("failed to get the policyLogger.properties, so use their default values",e); - } - - return logger_type; - - } - - /** - * Sets Debug Level - */ - public static void setDebugLevel(String debugLevel){ - - if(isOverrideLogbackLevel){ - PolicyLogger.DEBUG_LEVEL = Level.valueOf(debugLevel); - debugLogger.setLevel(DEBUG_LEVEL); - } - - } - - /** - * Sets Error OFF or ON - */ - public static void setErrorLevel(String errorLevel){ - - if(isOverrideLogbackLevel){ - if(errorLevel != null && errorLevel.equalsIgnoreCase("OFF")){ - PolicyLogger.ERROR_LEVEL = Level.OFF; - errorLogger.setLevel(ERROR_LEVEL); - }else{ - //--- set default value - errorLogger.setLevel(Level.ERROR); - PolicyLogger.ERROR_LEVEL = Level.ERROR; - } - } - } - - /** - * Sets Metrics OFF or ON - */ - public static void setMetricsLevel(String metricsLevel){ - - if(isOverrideLogbackLevel){ - if(metricsLevel != null && metricsLevel.equalsIgnoreCase("OFF")){ - PolicyLogger.METRICS_LEVEL = Level.OFF; - metricsLogger.setLevel(METRICS_LEVEL); - }else { - //--- set default value - metricsLogger.setLevel(Level.INFO); - PolicyLogger.METRICS_LEVEL = Level.INFO; - } - } - - } - - /** - * Sets Audit OFF or ON - */ - public static void setAuditLevel(String auditLevel){ - - if(isOverrideLogbackLevel){ - if(auditLevel != null && auditLevel.equalsIgnoreCase("OFF")){ - PolicyLogger.AUDIT_LEVEL = Level.OFF; - auditLogger.setLevel(AUDIT_LEVEL); - }else { - //--- set default value - auditLogger.setLevel(Level.INFO); - PolicyLogger.AUDIT_LEVEL = Level.INFO; - } - } - } - - /** - * Returns true for overriding logback levels; returns false for not - */ - public static boolean isOverrideLogbackLevel(){ - - return isOverrideLogbackLevel; - } - - /** - * Sets true for overriding logback levels; sets false for not - */ - public static void setOverrideLogbackLevel(boolean odl){ - - isOverrideLogbackLevel = odl; - - } - /** - * Sets server information to MDC - */ - public static void setServerInfo(String serverHost, String serverPort){ - MDC.put(SERVER_NAME, serverHost+":"+serverPort); - } - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/EelfLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/EelfLogger.java deleted file mode 100644 index 106c734c..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/EelfLogger.java +++ /dev/null @@ -1,486 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -import java.io.Serializable; -import java.util.UUID; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import com.att.eelf.configuration.EELFLogger.Level; - -/** - * - * EelfLogger implements all the methods of interface Logger by calling PolicyLogger methods - * - */ - -public class EelfLogger implements Logger, Serializable { - - /** - * - */ - private static final long serialVersionUID = 5385586713941277192L; - private String className = ""; - private String transId = UUID.randomUUID().toString(); - - /** - * Constructor - * @param clazz - */ - public EelfLogger(Class clazz) { - if(clazz != null){ - className = clazz.getName(); - } - PolicyLogger.postMDCInfoForEvent(null); - } - - /** - * Constructor - * @param s - */ - public EelfLogger(String s) { - if(s != null){ - className = s; - } - PolicyLogger.postMDCInfoForEvent(null); - } - - /** - * Constructor - * @param clazz - * @param isNewTransaction - */ - public EelfLogger(Class clazz, boolean isNewTransaction) { - if(clazz != null){ - className = clazz.getName(); - } - if(isNewTransaction){ - transId = PolicyLogger.postMDCInfoForEvent(null); - }else{ - transId = PolicyLogger.getTransId(); - } - } - - /** - * Constructor - * @param s - * @param isNewTransaction - */ - public EelfLogger(String s, boolean isNewTransaction) { - if(s != null){ - className = s; - } - if(isNewTransaction){ - transId = PolicyLogger.postMDCInfoForEvent(null); - }else{ - transId = PolicyLogger.getTransId(); - } - } - - /** - * Constructor - * @param clazz - * @param transId - */ - public EelfLogger(Class clazz, String transId) { - if(clazz != null){ - className = clazz.getName(); - } - PolicyLogger.postMDCInfoForEvent(transId); - } - - /** - * Constructor - * @param s - * @param transId - */ - public EelfLogger(String s, String transId) { - if(s != null){ - className = s; - } - PolicyLogger.postMDCInfoForEvent(transId); - } - - /** - * Sets transaction Id for logging - * @param transId - */ - @Override - public void setTransId(String transId){ - - PolicyLogger.setTransId(transId); - this.transId = transId; - } - - /** - * Returns transaction Id for logging - */ - @Override - public String getTransId(){ - return transId; - } - - /** - * Records a message - * @param message - */ - @Override - public void debug(Object message) { - PolicyLogger.debug(className, ""+message); - } - - /** - * Records an error message - * @param message - */ - @Override - public void error(Object message) { - PolicyLogger.error(className, ""+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void info(Object message) { - PolicyLogger.info(className, ""+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void warn(Object message) { - PolicyLogger.warn(className, ""+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void trace(Object message) { - PolicyLogger.trace(className, ""+message); - } - - /** - * Returns true for debug enabled, or false for not - * @return boolean - */ - @Override - public boolean isDebugEnabled(){ - return PolicyLogger.isDebugEnabled(); - } - - /** - * Returns true for info enabled, or false for not - * @return boolean - */ - @Override - public boolean isInfoEnabled(){ - return PolicyLogger.isInfoEnabled(); - } - - /** - * Returns true for warn enabled, or false for not - * @return boolean - */ - @Override - public boolean isWarnEnabled(){ - return PolicyLogger.isWarnEnabled(); - } - - /** - * Returns true for error enabled, or false for not - * @return boolean - */ - @Override - public boolean isErrorEnabled(){ - return PolicyLogger.isErrorEnabled(); - } - - /** - * Returns true for audit enabled, or false for not - * @return boolean - */ - @Override - public boolean isAuditEnabled(){ - if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ - return false; - }else { - return true; - } - } - - /** - * Returns true for metrics enabled, or false for not - * @return boolean - */ - @Override - public boolean isMetricsEnabled(){ - if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ - return false; - }else { - return true; - } - } - - /** - * Returns true for trace enabled, or false for not - * @return boolean - */ - @Override - public boolean isTraceEnabled(){ - return PolicyLogger.isDebugEnabled(); - } - - /** - * Records an audit message - * @param arg0 - */ - @Override - public void audit(Object arg0) { - PolicyLogger.audit(className, ""+ arg0); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void debug(Object message, Throwable t) { - PolicyLogger.debug(MessageCodes.GENERAL_INFO, t, message.toString()); - } - - /** - * Records an error message - * @param message - * @param t - */ - @Override - public void error(Object message, Throwable t) { - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, t, message.toString()); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void info(Object message, Throwable t) { - PolicyLogger.info(MessageCodes.GENERAL_INFO, t, message.toString()); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void warn(Object message, Throwable t) { - PolicyLogger.warn(MessageCodes.GENERAL_WARNING, t, message.toString()); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void trace(Object message, Throwable t) { - PolicyLogger.trace(message); - } - - /** - * Records an audit message - * @param arg0 - * @param t - */ - @Override - public void audit(Object arg0, Throwable t) { - PolicyLogger.audit(arg0); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(String eventId) { - PolicyLogger.recordAuditEventStart(eventId); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(UUID eventId) { - PolicyLogger.recordAuditEventStart(eventId); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { - PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(String eventId, String rule) { - PolicyLogger.recordAuditEventEnd(eventId, rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule) { - PolicyLogger.recordAuditEventEnd(eventId, rule); - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(String eventId, String arg1) { - PolicyLogger.recordMetricEvent(eventId, arg1); - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(UUID eventId, String arg1) { - PolicyLogger.recordMetricEvent(eventId, arg1); - } - - /** - * Records a metrics message - * @param arg0 - */ - @Override - public void metrics(Object arg0) { - PolicyLogger.metrics(className, arg0); - } - - /** - * Records an error message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void error(MessageCodes msg, Throwable arg0, String... arguments){ - PolicyLogger.error(msg, className, arg0, arguments); - } - - /** - * Records an error message - * @param msg - * @param arguments - */ - @Override - public void error(MessageCodes msg, String... arguments){ - PolicyLogger.error(msg, arguments); - } - - /** - * Populates MDC Info - * @param transId - */ - @Override - public String postMDCInfoForEvent(String transId) { - return PolicyLogger.postMDCInfoForEvent(transId); - - } - - /** - * Records a message - * @param msg - * @param arguments - */ - @Override - public void warn(MessageCodes msg, String... arguments){ - PolicyLogger.warn(msg, className, arguments); - } - - /** - * Records a message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void warn(MessageCodes msg, Throwable arg0, String... arguments){ - PolicyLogger.warn(msg, className, arg0, arguments); - } - - /** - * Populates MDC Info for the rule triggered - * @param transId - */ - @Override - public void postMDCInfoForTriggeredRule(String transId){ - PolicyLogger.postMDCInfoForTriggeredRule(transId); - } - - /** - * Populates MDC Info - * @param o - */ - @Override - public void postMDCInfoForEvent(Object o){ - PolicyLogger.postMDCInfoForEvent(o); - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLogger.java deleted file mode 100644 index 3db40f1e..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLogger.java +++ /dev/null @@ -1,330 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.Date; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.PropertyUtil.Listener; - -/** - * - * FlexLogger acts as factory to generate instances of Logger based on logger type - * - */ -public class FlexLogger extends SecurityManager{ - - private static LoggerType loggerType = LoggerType.EELF; - private static ConcurrentHashMap logger4JMap = new ConcurrentHashMap(); - private static ConcurrentHashMap eelfLoggerMap = new ConcurrentHashMap(); - private static ConcurrentHashMap systemOutMap = new ConcurrentHashMap(); - //--- init logger first - static { - loggerType = initlogger(); - } - - /** - * Returns an instance of Logger - * @param clazz - */ - static public Logger getLogger(Class clazz) { - Logger logger = null; - System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(clazz, false); - break; - case LOG4J: - logger = getLog4JLogger(clazz); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(null); - break; - } - - return logger; - - } - - /** - * Returns an instance of Logger - * @param s - */ - static public Logger getLogger(String s) { - Logger logger = null; - System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(null,false); - break; - case LOG4J: - logger = getLog4JLogger(s); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(null); - break; - } - - return logger; - - } - - /** - * Returns an instance of Logger - * @param clazz - * @param isNewTransaction - */ - static public Logger getLogger(Class clazz, boolean isNewTransaction) { - Logger logger = null; - System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(clazz, isNewTransaction); - break; - case LOG4J: - logger = getLog4JLogger(clazz); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(null); - break; - } - - return logger; - - } - - /** - * Returns an instance of Logger - * @param s - * @param isNewTransaction - */ - static public Logger getLogger(String s, boolean isNewTransaction) { - Logger logger = null; - System.out.println("FlexLogger:getLogger : loggerType = " + loggerType); - switch (loggerType) { - - case EELF: - logger = getEelfLogger(null, isNewTransaction); - break; - case LOG4J: - logger = getLog4JLogger(s); - break; - case SYSTEMOUT: - logger = getSystemOutLogger(null); - break; - } - - return logger; - } - - /** - * Returns the calling class name - */ - public String getClassName(){ - System.out.println("getClassContext()[3].getName() " + getClassContext()[3].getName()); - return getClassContext()[3].getName(); - } - - /** - * Returns an instance of Logger4J - * @param clazz - */ - private static Logger4J getLog4JLogger(Class clazz){ - String className = new FlexLogger().getClassName(); - - if(!logger4JMap.containsKey(className)){ - //for 1610 release use the default debug.log for log4j - Logger4J logger = new Logger4J("debugLogger", className); - logger4JMap.put(className, logger); - } - - return logger4JMap.get(className); - } - - /** - * Returns an instance of Logger4J - * @param s - */ - private static Logger4J getLog4JLogger(String s){ - String className = new FlexLogger().getClassName(); - - if(!logger4JMap.containsKey(className)){ - Logger4J logger = new Logger4J(s, className); - logger4JMap.put(className, logger); - } - - return logger4JMap.get(className); - } - - /** - * Returns an instance of EelfLogger - * @param clazz - * @param isNewTransaction - */ - private static EelfLogger getEelfLogger(Class clazz, boolean isNewTransaction){ - - String className = ""; - EelfLogger logger = null; - if(clazz != null){ - className = clazz.getName(); - }else{ - className = new FlexLogger().getClassName(); - } - - if(!eelfLoggerMap.containsKey(className)){ - logger = new EelfLogger(clazz, isNewTransaction); - eelfLoggerMap.put(className, logger); - }else{ - logger = eelfLoggerMap.get(className); - if(logger == null){ - logger = new EelfLogger(clazz, isNewTransaction); - eelfLoggerMap.put(className, logger); - } - //installl already created but it is new transaction - if(isNewTransaction){ - String transId = PolicyLogger.postMDCInfoForEvent(null); - logger.setTransId(transId); - } - } - System.out.println("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className); - return logger; - } - - /** - * Returns an instance of SystemOutLogger - * @param clazz - */ - private static SystemOutLogger getSystemOutLogger(Class clazz){ - - String className = new FlexLogger().getClassName(); - - if(!systemOutMap.containsKey(className)){ - SystemOutLogger logger = new SystemOutLogger(className); - systemOutMap.put(className, logger); - } - - return systemOutMap.get(className); - } - - /** - * loads the logger properties - */ - private static LoggerType initlogger() { - LoggerType loggerType = LoggerType.EELF; - String overrideLogbackLevel = "FALSE"; - String loggerTypeString = ""; - Properties properties = null; - - try { - properties = PropertyUtil.getProperties("config/policyLogger.properties"); - System.out.println("FlexLogger:properties => " + properties); - - if(properties != null) { - overrideLogbackLevel = properties.getProperty("override.logback.level.setup"); - System.out.println("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel); - loggerTypeString = properties.getProperty("logger.type"); - if (loggerTypeString != null){ - if (loggerTypeString.equalsIgnoreCase("EELF")){ - loggerType = LoggerType.EELF; - if (overrideLogbackLevel != null && - overrideLogbackLevel.equalsIgnoreCase("TRUE")) { - System.out.println("FlexLogger: start listener."); - properties = PropertyUtil.getProperties - ("config/policyLogger.properties", - new PropertiesCallBack("FlexLogger-CallBack")); - } - }else if (loggerTypeString.equalsIgnoreCase("LOG4J")){ - loggerType = LoggerType.LOG4J; - }else if (loggerTypeString.equalsIgnoreCase("SYSTEMOUT")){ - loggerType = LoggerType.SYSTEMOUT; - } - - System.out.println("FlexLogger.logger_Type value: " + loggerTypeString); - } - } - } catch (IOException e1) { - System.out.println("initlogger" + e1); - } finally { - // OK to pass no properties (null) - loggerType = PolicyLogger.init(properties); - } - - return loggerType; - } - - /** - * PropertiesCallBack is listening any updates on the policyLogger.properties - */ - static public class PropertiesCallBack implements Listener { - String name; - - public PropertiesCallBack(String name) { - this.name = name; - } - - /** - * This method will be called automatically if he policyLogger.properties got updated - */ - public void propertiesChanged(Properties properties, - Set changedKeys) { - - String debugLevel = properties.getProperty("debugLogger.level"); - String metricsLevel = properties.getProperty("metricsLogger.level"); - String auditLevel = properties.getProperty("audit.level"); - String errorLevel = properties.getProperty("error.level"); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00"); - Instant startTime = Instant.now(); - String formatedTime = sdf.format(Date.from(startTime)); - System.out.println("FlexLogger.propertiesChanged : called at time : " + formatedTime); - System.out.println("FlexLogger.propertiesChanged : debugLevel : " + debugLevel); - - if (changedKeys != null) { - - if (changedKeys.contains("debugLogger.level")) { - PolicyLogger.setDebugLevel(debugLevel); - } - - if (changedKeys.contains("metricsLogger.level")) { - PolicyLogger.setMetricsLevel(metricsLevel); - } - - if (changedKeys.contains("error.level")) { - PolicyLogger.setErrorLevel(errorLevel); - } - - if (changedKeys.contains("audit.level")) { - PolicyLogger.setAuditLevel(auditLevel); - } - } - } - } - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLoggerTester.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLoggerTester.java deleted file mode 100644 index 3e0d558a..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/FlexLoggerTester.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -import java.util.UUID; - -public class FlexLoggerTester { - - - public void testLogging(){ - - // get an instance of logger - Logger logger = FlexLogger.getLogger(FlexLoggerTester.class); - - //logger.info("this is a testing of FlexLogger with logger type:" + FlexLogger.loggerType); - - logger.info("logger.isAuditEnabled():" + logger.isAuditEnabled()); - logger.info("logger.isDebugEnabled():" + logger.isDebugEnabled()); - logger.info("logger.isErrorEnabled():" + logger.isErrorEnabled()); - logger.info("logger.isInfoEnabled():" + logger.isInfoEnabled()); - logger.info("logger.isMetricsEnabled():" + logger.isMetricsEnabled()); - logger.info("logger.isWarnEnabled():" + logger.isWarnEnabled()); - - if(logger.isDebugEnabled()) - logger.debug("this is from logger.debug call"); - else - logger.info("this is from logger.info call"); - - if(logger.isMetricsEnabled()) logger.metrics("this is from logger.metrics call"); - - logger.error("this is from logger.error call"); - if(logger.isAuditEnabled()) - logger.audit("this is from logger.audit call"); - else{ - logger.audit("shouldn't see this line in audit log"); - logger.info("shouldn't see this line in audit log"); - } - - if(logger.isMetricsEnabled()) - logger.metrics("this is from logger.metrics call"); - else{ - logger.metrics("shouldn't see this line in metrics log"); - logger.info("shouldn't see this line in metrics log"); - } - - if(logger.isErrorEnabled()) { - logger.error("this is from logger.error call"); - }else{ - logger.error("shouldn't see this logger.error call in error.log"); - logger.info("error is not enabled"); - } - - logger.info("logger.isDebugEnabled() returned value:" + logger.isDebugEnabled()); - logger.recordAuditEventEnd("123345456464998", "from recordAuditEventEnd call", "12345"); - logger.recordAuditEventEnd(UUID.randomUUID(), "from recordAuditEventEnd call", "abcdf"); - logger.recordAuditEventStart("from recordAuditEventStart call"); - logger.recordAuditEventStart(UUID.randomUUID().toString()); - logger.recordMetricEvent("123345456464998", "from recordMetricEvent call"); - logger.recordMetricEvent(UUID.randomUUID(), "from recordMetricEvent call"); - logger.trace("from trace call"); - - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger.java deleted file mode 100644 index 8cfee16c..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger.java +++ /dev/null @@ -1,221 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -import java.util.UUID; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; - -/** - * - * Interface Logger - implemented by Logger4J, EelfLogger and SystemOutLogger - * - */ -public interface Logger { - - /** - * Prints messages with the level.DEBUG - */ - public void debug(Object message); - - /** - * Prints messages with the level.ERROR - */ - public void error(Object message); - - /** - * Prints messages with the level.ERROR - */ - public void error(MessageCodes msg, Throwable arg0, String... arguments); - - /** - * Prints messages with the level.INFO - */ - public void info(Object message); - - /** - * Prints messages with the level.WARN - */ - public void warn(Object message); - - /** - * Prints messages with the level.TRACE - */ - public void trace(Object message); - - /** - * Prints messages in audit log with the level.INFO - */ - public void audit(Object arg0); - - /** - * Prints messages with the level.DEBUG - */ - public void debug(Object message, Throwable t); - - /** - * Prints messages with the level.ERROR - */ - public void error(Object message, Throwable t); - - /** - * Prints messages with the level.INFO - */ - public void info(Object message, Throwable t); - - /** - * Prints messages with the level.WARN - */ - public void warn(Object message, Throwable t); - - /** - * Prints messages with the level.TRACE - */ - public void trace(Object message, Throwable t); - - /** - * Prints messages in audit log with the level.INFO - */ - public void audit(Object arg0, Throwable t); - - /** - * Records event Id in audit log with the level.INFO - */ - public void recordAuditEventStart(String eventId); - - /** - * Records the starting time of the event with its request Id as the key - */ - public void recordAuditEventStart(UUID eventId); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(String eventId, String rule, String policyVersion ); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(String eventId, String rule); - - /** - * Records the ending time of the event with its request Id as the key - */ - public void recordAuditEventEnd(UUID eventId, String rule); - - - /** - * Records the Metrics with event Id and log message - */ - public void recordMetricEvent(String eventId, String arg1); - - /** - * Records the Metrics with event Id and log message - */ - public void recordMetricEvent(UUID eventId, String arg1); - - /** - * Records the Metrics log message - */ - public void metrics(Object arg0); - - /** - * Returns a boolean value, true for debug logging enabled, false for not enabled - */ - public boolean isDebugEnabled(); - - /** - * Returns a boolean value, true for error logging enabled, false for not enabled - */ - public boolean isErrorEnabled(); - - /** - * Returns a boolean value, true for warn logging enabled, false for not enabled - */ - public boolean isWarnEnabled(); - - /** - * Returns a boolean value, true for info logging enabled, false for not enabled - */ - public boolean isInfoEnabled(); - - /** - * Returns a boolean value, true for error logging enabled, false for not enabled - */ - public boolean isAuditEnabled(); - - /** - * Returns a boolean value, true for warn logging enabled, false for not enabled - */ - public boolean isMetricsEnabled(); - - /** - * Returns a boolean value, true for trace logging enabled, false for not enabled - */ - public boolean isTraceEnabled(); - - - /** - * Populates MDC info - */ - public String postMDCInfoForEvent(String transId); - - /** - * Prints messages with the level.WARN - */ - public void warn(MessageCodes msg, String... arguments) ; - - /** - * Prints messages with the level.WARN - */ - public void warn(MessageCodes msg, Throwable arg0, String... arguments) ; - - /** - * Prints messages with the level.ERROR - */ - public void error(MessageCodes msg, String... arguments) ; - - /** - * Sets transaction Id - */ - public void setTransId(String transId); - - /** - * Returns transaction Id - */ - String getTransId(); - - /** - * Populates MDC Info for the rule triggered - */ - public void postMDCInfoForTriggeredRule(String transId); - - /** - * Populates MDC Info - */ - public void postMDCInfoForEvent(Object o); - -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger4J.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger4J.java deleted file mode 100644 index 506e1ea7..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/Logger4J.java +++ /dev/null @@ -1,488 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.UUID; - -import org.apache.log4j.Logger; -import org.apache.log4j.Priority; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import com.att.eelf.configuration.EELFLogger.Level; - -/** - * - * Logger4J implements all the methods of interface Logger by calling org.apache.log4j.Logger - * - */ -public class Logger4J implements org.openecomp.policy.common.logging.flexlogger.Logger, Serializable { - - /** - * - */ - private static final long serialVersionUID = 3183729429888828471L; - private Logger log = null; - private String methodName = ""; - private String className = ""; - private String transId = UUID.randomUUID().toString(); - - /** - * Constructor - * @param clazz - */ - public Logger4J (Class clazz){ - System.out.println("create instance of Logger4J"); - if(clazz != null){ - log = Logger.getLogger(clazz); - className = clazz.getName(); - } - } - - /** - * Constructor - * @param s - * @param className - */ - public Logger4J (String s, String className){ - System.out.println("create instance of Logger4J"); - if(s != null){ - log = Logger.getLogger(s); - } - this.className = className; - } - - /** - * Sets transaction Id - */ - @Override - public void setTransId(String transId){ - log.info(transId); - this.transId = transId; - } - - /** - * Returns transaction Id - */ - @Override - public String getTransId(){ - return transId; - } - - /** - * Records a message - * @param message - */ - @Override - public void debug(Object message) { - if(isDebugEnabled()){ - log.debug(transId + "|" + message); - } - } - - /** - * Records an error message - * @param message - */ - @Override - public void error(Object message) { - log.error( transId + "|" + className +"|" + message); - } - - /** - * Records a message - * @param message - */ - @Override - public void info(Object message) { - log.info( transId + "|" + className +"|" + message); - } - - /** - * Records a message - * @param message - */ - @Override - public void warn(Object message) { - log.warn( transId + "|" + className +"|" + message); - } - - /** - * Records a message - * @param message - */ - @Override - public void trace(Object message) { - log.trace(transId + "|"+ className +"|" + message); - } - - /** - * Returns true for debug enabled, or false for not - * @return boolean - */ - @Override - public boolean isDebugEnabled(){ - return log.isDebugEnabled(); - } - - /** - * Returns true for error enabled, or false for not - * @return boolean - */ - @SuppressWarnings("deprecation") - @Override - public boolean isErrorEnabled(){ - return log.isEnabledFor(Priority.ERROR); - } - - /** - * Returns true for info enabled, or false for not - * @return boolean - */ - @Override - public boolean isInfoEnabled(){ - return log.isInfoEnabled(); - } - - /** - * Returns true for warn enabled, or false for not - * @return boolean - */ - @SuppressWarnings("deprecation") - @Override - public boolean isWarnEnabled(){ - //return log4j value - return log.isEnabledFor(Priority.WARN); - } - - /** - * Returns true for audit enabled, or false for not - * @return boolean - */ - @Override - public boolean isAuditEnabled(){ - if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ - return false; - }else { - return true; - } - } - - /** - * Returns true for metrics enabled, or false for not - * @return boolean - */ - @Override - public boolean isMetricsEnabled(){ - if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ - return false; - }else { - return true; - } - } - - /** - * Records an audit message - * @param arg0 - */ - @Override - public void audit(Object arg0) { - log.info(className +"|" +arg0); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(String eventId) { - log.info(className +"|recordAuditEventStart with eventId " + eventId); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(UUID eventId) { - if(eventId != null){ - recordAuditEventStart(eventId.toString()); - } - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { - log.info(className +"|"+ eventId + ":" + rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - if(eventId != null){ - recordAuditEventEnd(eventId.toString(), rule, policyVersion); - }else{ - recordAuditEventEnd(eventId, rule, policyVersion); - } - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(String eventId, String rule) { - log.info(className +"|" +eventId + ":" + rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule) { - if(eventId != null){ - recordAuditEventEnd(eventId.toString(), rule); - }else{ - recordAuditEventEnd(eventId, rule); - } - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(String eventId, String arg1) { - log.info(className +"|" +eventId + ":" + arg1); - - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(UUID eventId, String arg1) { - if(eventId != null){ - recordMetricEvent(eventId.toString(), arg1); - }else{ - recordMetricEvent(eventId, arg1); - } - } - - /** - * Records a metrics message - * @param arg0 - */ - @Override - public void metrics(Object arg0) { - log.info(arg0); - } - - /** - * Records an error message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void error(MessageCodes msg, Throwable arg0, String... arguments){ - log.error(transId + "|" + className +"|" + "MessageCodes :" + msg + arguments); - - } - - /** - * Records an error message - * @param msg - * @param arguments - */ - @Override - public void error(MessageCodes msg, String... arguments){ - log.error(transId + "|" + className +"|" + "MessageCode:" + msg + arguments); - } - - /** - * Returns transaction Id - * @param transId - */ - @Override - public String postMDCInfoForEvent(String transId) { - if(transId == null || transId.isEmpty()){ - transId = UUID.randomUUID().toString(); - } - - return transId; - } - - /** - * Records a message - * @param msg - * @param arguments - */ - @Override - public void warn(MessageCodes msg, String... arguments){ - log.warn(className +"|" +"MessageCodes:" + msg + arguments); - } - - /** - * Records a message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void warn(MessageCodes msg, Throwable arg0, String... arguments){ - log.warn(className +"|" +"MessageCodes:" + msg + arguments); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void debug(Object message, Throwable t) { - log.debug(message, t); - } - - /** - * Records an error message - * @param message - * @param t - */ - @Override - public void error(Object message, Throwable t) { - log.error(message, t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void info(Object message, Throwable t) { - log.info(message, t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void warn(Object message, Throwable t) { - log.warn(message, t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void trace(Object message, Throwable t) { - log.trace(message, t); - } - - /** - * Records an audit message - * @param arg0 - * @param t - */ - - @Override - public void audit(Object arg0, Throwable t) { - log.info(arg0, t); - } - - /** - * Returns true for trace enabled, or false for not - * @return boolean - */ - @Override - public boolean isTraceEnabled() { - return log.isTraceEnabled(); - } - - /** - * Records transaction Id - * @param transId - */ - @Override - public void postMDCInfoForTriggeredRule(String transId){ - log.info(transId); - } - - /** - * Records transaction Id - * @param o - */ - @Override - public void postMDCInfoForEvent(Object o){ - log.info(o); - } - - /* ============================================================ */ - - /* - * Support for 'Serializable' -- - * the default rules don't work for the 'log' field - */ - - private void writeObject(ObjectOutputStream out) throws IOException { - // write out 'methodName', 'className', 'transId' strings - out.writeObject(methodName); - out.writeObject(className); - out.writeObject(transId); - } - - private void readObject(ObjectInputStream in) - throws IOException, ClassNotFoundException { - - // read in 'methodName', 'className', 'transId' strings - methodName = (String)(in.readObject()); - className = (String)(in.readObject()); - transId = (String)(in.readObject()); - - // look up associated logger - log = Logger.getLogger(className); - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/LoggerType.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/LoggerType.java deleted file mode 100644 index 8fe55b29..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/LoggerType.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -/** - * - * Logger types - * - */ -public enum LoggerType { - EELF, LOG4J, SYSTEMOUT -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/PropertyUtil.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/PropertyUtil.java deleted file mode 100644 index 462e10cb..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/PropertyUtil.java +++ /dev/null @@ -1,403 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Properties; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; - -/** - * This class provides utilities to read properties from a properties - * file, and optionally get notifications of future changes - */ -public class PropertyUtil -{ - /** - * Read in a properties file - * @param file the properties file - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - static public Properties getProperties(File file) throws IOException - { - // create an InputStream (may throw a FileNotFoundException) - FileInputStream fis = new FileInputStream(file); - try - { - // create the properties instance - Properties rval = new Properties(); - - // load properties (may throw an IOException) - rval.load(fis); - return(rval); - } - finally - { - // close input stream - fis.close(); - } - } - - /** - * Read in a properties file - * @param fileName the properties file - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - static public Properties getProperties(String fileName) throws IOException - { - return(getProperties(new File(fileName))); - } - - /* ============================================================ */ - - // timer thread used for polling for property file changes - private static Timer timer = null; - - /** - * This is the callback interface, used for sending notifications of - * changes in the properties file. - */ - public interface Listener - { - /** - * Notification of a properties file change - * @param properties the new properties - * @param the set of property names that have changed, including - * additions and removals - */ - void propertiesChanged(Properties properties, Set changedKeys); - } - - // this table maps canonical file into a 'ListenerRegistration' instance - static private HashMap registrations = - new HashMap(); - - /** - * This is an internal class - one instance of this exists for each - * property file that is being monitored. Note that multiple listeners - * can be registered for the same file. - */ - private static class ListenerRegistration - { - // the canonical path of the file being monitored - File file; - - // the most recent value of 'file.lastModified()' - long lastModified; - - // the most recent set of properties - Properties properties; - - // the set of listeners monitoring this file - LinkedList listeners; - - // the 'TimerTask' instance, used for periodic polling - TimerTask timerTask; - - /** - * Constructor - create a 'ListenerRegistration' instance for this - * file, but with no listeners - */ - ListenerRegistration(File file) throws IOException - { - this.file = file; - - // The initial value of 'lastModified' is set to 0 to ensure that we - // correctly handle the case where the file is modified within the - // same second that polling begins. - lastModified = 0; - - // fetch current properties - properties = getProperties(file); - - // no listeners yet - listeners = new LinkedList(); - - // add to static table, so this instance can be shared - registrations.put(file, this); - - if (timer == null) - { - // still need to create a timer thread - synchronized(PropertyUtil.class) - { - // an additional check is added inside the 'synchronized' block, - // just in case someone beat us to it - if (timer == null) - { - timer = new Timer("PropertyUtil-Timer", true); - } - } - } - - // create and schedule the timer task, so this is periodically polled - timerTask = new TimerTask() - { - public void run() - { - try - { - poll(); - } - catch (Exception e) - { - System.err.println(e); - } - } - }; - timer.schedule(timerTask, 10000L, 10000L); - } - - /** - * Add a listener to the notification list - * @param listener this is the listener to add to the list - * @return the properties at the moment the listener was added to the list - */ - synchronized Properties addListener(Listener listener) - { - listeners.add(listener); - return((Properties)properties.clone()); - } - - /** - * Remove a listener from the notification list - * @param listener this is the listener to remove - */ - synchronized void removeListener(Listener listener) - { - listeners.remove(listener); - - // See if we need to remove this 'ListenerRegistration' instance - // from the table. The 'synchronized' block is needed in case - // another listener is being added at about the same time that this - // one is being removed. - synchronized(registrations) - { - if (listeners.size() == 0) - { - timerTask.cancel(); - registrations.remove(file); - } - } - } - - /** - * This method is periodically called to check for property list updates - * @throws IOException if there is an error in reading the properties file - */ - synchronized void poll() throws IOException - { - long timestamp = file.lastModified(); - if (timestamp != lastModified) - { - // update the record, and send out the notifications - lastModified = timestamp; - - // Save old set, and initial set of changed properties. - Properties oldProperties = properties; - HashSet changedProperties = - new HashSet(oldProperties.stringPropertyNames()); - - // Fetch the list of listeners that we will potentially notify, - // and the new properties. Note that this is in a 'synchronized' - // block to ensure that all listeners receiving notifications - // actually have a newer list of properties than the one - // returned on the initial 'getProperties' call. - properties = getProperties(file); - - Set newPropertyNames = properties.stringPropertyNames(); - changedProperties.addAll(newPropertyNames); - - // At this point, 'changedProperties' is the union of all properties - // in both the old and new properties files. Iterate through all - // of the entries in the new properties file - if the entry - // matches the one in the old file, remove it from - // 'changedProperties'. - for (String name : newPropertyNames) - { - if (properties.getProperty(name).equals - (oldProperties.getProperty(name))) - { - // Apparently, any property that exists must be of type - // 'String', and can't be null. For this reason, we don't - // need to worry about the case where - // 'properties.getProperty(name)' returns 'null'. Note that - // 'oldProperties.getProperty(name)' may be 'null' if the - // old property does not exist. - changedProperties.remove(name); - } - } - - // 'changedProperties' should be correct at this point - if (changedProperties.size() != 0) - { - // there were changes - notify everyone in 'listeners' - for (final Listener notify : listeners) - { - // Copy 'properties' and 'changedProperties', so it doesn't - // cause problems if the recipient makes changes. - final Properties tmpProperties = - (Properties)(properties.clone()); - final HashSet tmpChangedProperties = - new HashSet(changedProperties); - - // Do the notification in a separate thread, so blocking - // won't cause any problems. - new Thread() - { - public void run() - { - notify.propertiesChanged - (tmpProperties, tmpChangedProperties); - } - }.start(); - } - } - } - } - } - - /** - * Read in a properties file, and register for update notifications. - * NOTE: it is possible that the first callback will occur while this - * method is still in progress. To avoid this problem, use 'synchronized' - * blocks around this invocation and in the callback -- that will ensure - * that the processing of the initial properties complete before any - * updates are processed. - * - * @param file the properties file - * @param notify if not null, this is a callback interface that is used for - * notifications of changes - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - static public Properties getProperties(File file, Listener listener) - throws IOException - { - if (listener == null) - { - // no listener specified -- just fetch the properties - return(getProperties(file)); - } - - // Convert the file to a canonical form in order to avoid the situation - // where different names refer to the same file. - file = file.getCanonicalFile(); - - // See if there is an existing registration. The 'synchronized' block - // is needed to handle the case where a new listener is added at about - // the same time that another one is being removed. - synchronized(registrations) - { - ListenerRegistration reg = registrations.get(file); - if (reg == null) - { - // a new registration is needed - reg = new ListenerRegistration(file); - } - return(reg.addListener(listener)); - } - } - - /** - * Read in a properties file, and register for update notifications. - * NOTE: it is possible that the first callback will occur while this - * method is still in progress. To avoid this problem, use 'synchronized' - * blocks around this invocation and in the callback -- that will ensure - * that the processing of the initial properties complete before any - * updates are processed. - * - * @param fileName the properties file - * @param notify if not null, this is a callback interface that is used for - * notifications of changes - * @return a Properties object, containing the associated properties - * @throws IOException - subclass 'FileNotFoundException' if the file - * does not exist or can't be opened, and 'IOException' if there is - * a problem loading the properties file. - */ - static public Properties getProperties(String fileName, Listener listener) - throws IOException - { - return(getProperties(new File(fileName), listener)); - } - - /** - * Stop listenening for updates - * @param file the properties file - * @param notify if not null, this is a callback interface that was used for - * notifications of changes - */ - static public void stopListening(File file, Listener listener) - { - if (listener != null) - { - ListenerRegistration reg = registrations.get(file); - if (reg != null) - { - reg.removeListener(listener); - } - } - } - - /** - * Stop listenening for updates - * @param fileName the properties file - * @param notify if not null, this is a callback interface that was used for - * notifications of changes - */ - static public void stopListening(String fileName, Listener listener) - { - stopListening(new File(fileName), listener); - } - - /* ============================================================ */ - - // TEMPORARY - used to test callback interface - static public class Test implements Listener - { - String name; - - public Test(String name) - { - this.name = name; - } - - public void propertiesChanged(Properties properties, Set changedKeys) - { - System.out.println("Test(" + name + ")\nproperties = " + properties - + "\nchangedKeys = " + changedKeys); - } - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/SystemOutLogger.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/SystemOutLogger.java deleted file mode 100644 index 596914a2..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/flexlogger/SystemOutLogger.java +++ /dev/null @@ -1,502 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.flexlogger; - -import java.io.Serializable; -import java.util.UUID; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import com.att.eelf.configuration.EELFLogger.Level; - -/** - * - * SystemOutLogger implements all the methods of interface Logger by calling System.out.println - * - */ -public class SystemOutLogger implements Logger, Serializable { - - /** - * - */ - private static final long serialVersionUID = 4956408061058933929L; - private String className = ""; - private boolean isDebugEnabled = true; - private boolean isInfoEnabled = true; - private boolean isWarnEnabled = true; - private boolean isErrorEnabled = true; - private boolean isAuditEnabled = true; - private boolean isMetricsEnabled = true; - private String transId = UUID.randomUUID().toString(); - - /** - * Constructor - * @param clazz - */ - public SystemOutLogger (Class clazz){ - System.out.println("create instance of SystemOutLogger"); - if(clazz != null){ - className = clazz.getName(); - } - initLevel(); - } - - /** - * Constructor - * @param s - */ - public SystemOutLogger (String s){ - System.out.println("create instance of SystemOutLogger"); - if(s != null){ - className = s; - } - initLevel(); - } - - /** - * Sets logging levels - */ - private void initLevel(){ - - if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.DEBUG.toString())){ - isDebugEnabled = true; - isInfoEnabled = true; - isWarnEnabled = true; - }else{ - isDebugEnabled = false; - } - - if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.INFO.toString())){ - isInfoEnabled = true; - isWarnEnabled = true; - isDebugEnabled = false; - } - - if(PolicyLogger.DEBUG_LEVEL != null && PolicyLogger.DEBUG_LEVEL.toString().equals(Level.OFF.toString())){ - isInfoEnabled = false; - isWarnEnabled = false; - isDebugEnabled = false; - } - - if(PolicyLogger.ERROR_LEVEL != null && PolicyLogger.ERROR_LEVEL.toString().equals(Level.OFF.toString())){ - isErrorEnabled = false; - } - - if(PolicyLogger.AUDIT_LEVEL != null && PolicyLogger.AUDIT_LEVEL.toString().equals(Level.OFF.toString())){ - isAuditEnabled = false; - } - - if(PolicyLogger.METRICS_LEVEL != null && PolicyLogger.METRICS_LEVEL.toString().equals(Level.OFF.toString())){ - isMetricsEnabled = false; - } - } - - /** - * Sets transaction Id - */ - @Override - public void setTransId(String transId){ - - System.out.println(transId); - this.transId = transId; - } - - /** - * Returns transaction Id - */ - @Override - public String getTransId(){ - - return transId; - } - - /** - * Records a message - * @param message - */ - @Override - public void debug(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Records an error message - * @param message - */ - @Override - public void error(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void info(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - - } - - /** - * Records a message - * @param message - */ - @Override - public void warn(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Records a message - * @param message - */ - @Override - public void trace(Object message) { - - System.out.println(transId + "|" + className+" : "+message); - } - - /** - * Returns true for debug enabled, or false for not - * @return boolean - */ - @Override - public boolean isDebugEnabled(){ - - return isDebugEnabled; - } - - /** - * Returns true for warn enabled, or false for not - * @return boolean - */ - @Override - public boolean isWarnEnabled(){ - - return isWarnEnabled; - } - - /** - * Returns true for info enabled, or false for not - * @return boolean - */ - @Override - public boolean isInfoEnabled(){ - - return isInfoEnabled; - } - - /** - * Returns true for error enabled, or false for not - * @return boolean - */ - @Override - public boolean isErrorEnabled(){ - - return isErrorEnabled; - } - - /** - * Returns true for audit enabled, or false for not - * @return boolean - */ - @Override - public boolean isAuditEnabled(){ - - return isAuditEnabled; - } - - /** - * Returns true for metrics enabled, or false for not - * @return boolean - */ - @Override - public boolean isMetricsEnabled(){ - - return isMetricsEnabled; - } - - /** - * Records an audit message - * @param arg0 - */ - @Override - public void audit(Object arg0) { - - System.out.println(transId + "|" +className+" : "+arg0); - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(String eventId) { - - System.out.println(transId + "|" +className+" : "+eventId); - - } - - /** - * Records an audit message - * @param eventId - */ - @Override - public void recordAuditEventStart(UUID eventId) { - - System.out.println(eventId); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(String eventId, String rule, String policyVersion) { - - System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - * @param policyVersion - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) { - - System.out.println(className+" : "+eventId + ":" + rule + ":" + policyVersion); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(String eventId, String rule) { - - System.out.println(className+" : "+eventId + ":" + rule); - } - - /** - * Records an audit message - * @param eventId - * @param rule - */ - @Override - public void recordAuditEventEnd(UUID eventId, String rule) { - - System.out.println(className+" : "+eventId + ":" + rule); - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(String eventId, String arg1) { - - System.out.println(className+" : "+"eventId:" + ":" + eventId + "message:" + arg1); - - } - - /** - * Records a metrics message - * @param eventId - * @param arg1 - */ - @Override - public void recordMetricEvent(UUID eventId, String arg1) { - - System.out.println(className+" : "+eventId + ":" + arg1); - } - - /** - * Records a metrics message - * @param arg0 - */ - @Override - public void metrics(Object arg0) { - - System.out.println(className+" : "+arg0); - } - - /** - * Records an error message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void error(MessageCodes msg, Throwable arg0, String... arguments){ - - System.out.println(className+" : "+"MessageCodes :" + msg + arguments); - - } - - /** - * Records an error message - * @param msg - * @param arguments - */ - @Override - public void error(MessageCodes msg, String... arguments){ - - System.out.println(transId + "|" + className+" : "+"MessageCode:" + msg + arguments); - } - - /** - * Returns transaction Id - * @param transId - */ - @Override - public String postMDCInfoForEvent(String transId) { - - if(transId == null || transId.isEmpty()){ - transId = UUID.randomUUID().toString(); - } - - return transId; - } - - /** - * Records a message - * @param msg - * @param arguments - */ - @Override - public void warn(MessageCodes msg, String... arguments){ - - System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + arguments); - } - - /** - * Records a message - * @param msg - * @param arg0 - * @param arguments - */ - @Override - public void warn(MessageCodes msg, Throwable arg0, String... arguments){ - - System.out.println(transId + "|" + className+" : "+"MessageCodes:" + msg + arguments); - - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void debug(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records an error message - * @param message - * @param t - */ - @Override - public void error(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void info(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void warn(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records a message - * @param message - * @param t - */ - @Override - public void trace(Object message, Throwable t) { - System.out.println(transId + "|" + className+" : "+ message + ":" + t); - } - - /** - * Records an audit message - * @param arg0 - * @param t - */ - @Override - public void audit(Object arg0, Throwable t) { - System.out.println(transId + "|" + className+" : "+ arg0 + ":" + t); - } - - /** - * Returns true for trace enabled, or false for not - * @return boolean - */ - @Override - public boolean isTraceEnabled() { - // default - return false; - } - - /** - * Records transaction Id - * @param transId - */ - @Override - public void postMDCInfoForTriggeredRule(String transId){ - - System.out.println(transId); - } - - /** - * Records transaction Id - * @param o - */ - @Override - public void postMDCInfoForEvent(Object o){ - System.out.println(o); - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContext.java deleted file mode 100644 index 56f6686a..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContext.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.nsa; - -/** - * An interface for providing data into the underlying logging context. Systems should use - * this interface rather than log system specific MDC solutions in order to reduce dependencies. - * - * A LoggingContext is specific to the calling thread. - * - */ -public interface LoggingContext -{ - /** - * Put a key/value pair into the logging context, replacing an entry with the same key. - * @param key - * @param value - */ - void put ( String key, String value ); - - /** - * Put a key/value pair into the logging context, replacing an entry with the same key. - * @param key - * @param value - */ - void put ( String key, long value ); - - /** - * Get a string value, returning the default value if the value is missing. - * @param key - * @param defaultValue - * @return a string value - */ - String get ( String key, String defaultValue ); - - /** - * Get a long value, returning the default value if the value is missing or not a long. - * @param key - * @param defaultValue - * @return a long value - */ - long get ( String key, long defaultValue ); -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContextFactory.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContextFactory.java deleted file mode 100644 index b8fce10c..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/LoggingContextFactory.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.nsa; - - -import org.openecomp.policy.common.logging.nsa.impl.SharedContext; -import org.openecomp.policy.common.logging.nsa.impl.Slf4jLoggingContext; - -/** - * A factory for setting up a LoggingContext - * - */ -public class LoggingContextFactory -{ - public static class Builder - { - public Builder withBaseContext ( LoggingContext lc ) - { - fBase = lc; - return this; - } - - public Builder forSharing () - { - fShared = true; - return this; - } - - public LoggingContext build () - { - return fShared ? new SharedContext ( fBase ) : new Slf4jLoggingContext ( fBase ); - } - - private LoggingContext fBase = null; - private boolean fShared = false; - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/SharedLoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/SharedLoggingContext.java deleted file mode 100644 index 2ecbcb0a..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/SharedLoggingContext.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.nsa; - -/** - * A logging context must be thread-specific. Contexts that implement SharedLoggingContext - * are expected to be shared across threads, and they have to be able to populate another - * logging context with their data. - * - */ -public interface SharedLoggingContext extends LoggingContext -{ - /** - * Copy this context's data to the given context. This must work across threads so that - * a base context can be shared in another thread. - * @param lc - */ - void transferTo ( SharedLoggingContext lc ); -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/SharedContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/SharedContext.java deleted file mode 100644 index 96ffbf64..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/SharedContext.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.nsa.impl; - -import java.util.HashMap; -import java.util.Map.Entry; - -import org.openecomp.policy.common.logging.nsa.LoggingContext; -import org.openecomp.policy.common.logging.nsa.SharedLoggingContext; - -/** - * A shared logging context for SLF4J - * - */ -public class SharedContext extends Slf4jLoggingContext implements SharedLoggingContext -{ - public SharedContext ( LoggingContext base ) - { - super ( base ); - fMap = new HashMap (); - } - - @Override - public void put ( String key, String value ) - { - super.put ( key, value ); - fMap.put ( key, value ); - } - - @Override - public void transferTo ( SharedLoggingContext lc ) - { - for ( Entry e : fMap.entrySet () ) - { - lc.put ( e.getKey(), e.getValue() ); - } - } - - private final HashMap fMap; -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/Slf4jLoggingContext.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/Slf4jLoggingContext.java deleted file mode 100644 index de31af98..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/impl/Slf4jLoggingContext.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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.openecomp.policy.common.logging.nsa.impl; - -import org.slf4j.MDC; - -import org.openecomp.policy.common.logging.nsa.LoggingContext; - -/** - * A logging context for SLF4J - * - */ -public class Slf4jLoggingContext implements LoggingContext -{ - public Slf4jLoggingContext ( LoggingContext base ) - { - } - - @Override - public void put ( String key, String value ) - { - MDC.put ( key, value ); - } - - public void put ( String key, long value ) - { - put ( key, "" + value ); - } - - - public String get ( String key, String defaultValue ) - { - String result = MDC.get ( key ); - if ( result == null ) - { - result = defaultValue; - } - return result; - } - - public long get ( String key, long defaultValue ) - { - final String str = get ( key, "" + defaultValue ); - try - { - return Long.parseLong ( str ); - } - catch ( NumberFormatException x ) - { - return defaultValue; - } - } -} diff --git a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/package-info.java b/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/package-info.java deleted file mode 100644 index e1ef710b..00000000 --- a/common-logging/src/main/java/org/openecomp/policy/common/logging/nsa/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-Logging - * ================================================================================ - * 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========================================================= - */ - -/** - * This package provides a logging context infrastructure and a corresponding - * implementation based on the SLF4J/Log4j "MDC" (Mapped Diagnostic Context) feature. - * - */ -package org.openecomp.policy.common.logging.nsa; - diff --git a/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties b/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties new file mode 100644 index 00000000..b41dbb26 --- /dev/null +++ b/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties @@ -0,0 +1,245 @@ +### +# ============LICENSE_START======================================================= +# ONAP-Logging +# ================================================================================ +# 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========================================================= +### + +#Resource key=Error Code|Message text|Resolution text |Description text +####### +# {APP}-{4-digit}{classification} + +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +###### +#Error code classification category +#100-199 Permission/Security Related +#200-299 Availability/Timeout Related +#300-399 Data Access/Integrity Related +#400-499 Schema Interface type/validation Related +#500-599 Business/Flow Processing Related +#900-999 Unknown errors +# +#{classification} description +# I = Information +# W = Warning +# E = Error +# F = Fatal + +######################################################################## + +GENERAL_INFO=\ + POLICY-500I|\ + INFO: {0}|\ + No resolution needed|\ + General flow processing info +GENERAL_WARNING=\ + POLICY-501W|\ + WARNING: {0}|\ + Please check other logs for more information|\ + General warning +UPDATE_ERROR=\ + POLICY-502E|\ + ERROR: Could not update {0}|\ + Please check other logs for more information|\ + Exception caught during server management + +EXCEPTION_ERROR=\ + POLICY-503E|\ + ERROR: Error Message: {0}|\ + Please check other logs for more information|\ + Exception caught during server management + +MISS_PROPERTY_ERROR=\ + POLICY-504E|\ + ERROR: {0} property not set in {1}.properties|\ + Please check other logs for more information|\ + Exception caught during server management + +BAD_TYPE_WARNING=\ + POLICY-505W|\ + WARNING: Bad types for Double Metric: {0} path: {1}|\ + Please check other logs for more information|\ + General warning + +MISS_PROPERTY_INFO=\ + POLICY-506I|\ + INFO: report: {0} not set|\ + No resolution needed|\ + General flow processing info + +RULE_AUDIT_EXEC_INFO=\ + POLICY-507I|\ + Service Name: {0}:Executing rule: {1}|\ + No resolution needed|\ + Executing method + +RULE_AUDIT_BEGIN_INFO=\ + POLICY-508I|\ + Service Name: {0}:Entering rule: {1}|\ + No resolution needed|\ + Entering method + +RULE_AUDIT_END_INFO=\ + POLICY-509I|\ + Service Name: {0}:Exiting rule: {1}|\ + No resolution needed|\ + Exiting method + +RULE_METRICS_INFO=\ + POLICY-510I|\ + Service Name: {0}:Executing method: {1}|\ + No resolution needed|\ + Generate information for Metric events + +UEB_AUDIT_EXEC_INFO=\ + POLICY-511I|\ + Service Name: {0}:Executing UEB: {1}|\ + No resolution needed|\ + Executing method + +UEB_AUDIT_BEGIN_INFO=\ + POLICY-512I|\ + Service Name: {0}:Entering UEB: {1}|\ + No resolution needed|\ + Entering method + +UEB_AUDIT_END_INFO=\ + POLICY-513I|\ + Service Name: {0}:Exiting UEB: {1}|\ + No resolution needed|\ + Exiting method + + + +RULE_AUDIT_START_END_INFO=\ + POLICY-514I|\ + Service Name: {0}:Executing rule:{1}:Starting Time:{2}:Ending Time:{3}:Executing Time:{4}:Policy version:{5}|\ + No resolution needed|\ + Executing method + +GENERAL_ERROR=\ + POLICY-515E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during server management + +ERROR_SYSTEM_ERROR=\ + POLICY-516E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during server management + +ERROR_DATA_ISSUE=\ + POLICY-517E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during server management + +ERROR_PERMISSIONS=\ + POLICY-100E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during server management + +ERROR_PROCESS_FLOW=\ + POLICY-518E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during server management + +ERROR_SCHEMA-INVALID=\ + POLICY-400E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during server management + +ERROR_UNKNOWN=\ + POLICY-519E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during server management + +ERROR_AUDIT=\ + POLICY-520E|\ + ERROR: {0}|\ + Please check other logs for more information|\ + error caught during audit process + +######################################################################## +######################################################################## +######################################################################## +#---------------- The message codes below should not be used anymore since 1607 release ----------------------------- + +MESSAGE_SAMPLE_NOARGS=\ + APP1234I|\ + App1 message text sample1|\ + App1 resolution text sample1|\ + App1 description text sample1 + +MESSAGE_SAMPLE_ONEARGUMENT=\ + APP3456I|\ + App1 msg smpl w arg: {0}|\ + App1 resolution text sample2|\ + App1 description text sample2 + +AUDIT_MESSAGE_ONEARGUMENT=\ + AUD0000I|\ + Audit msg: {0}|\ + Audit resolution text sample2|\ + Audit description text sample2 + +ERROR_MESSAGE_ONEARGUMENT=\ + ERR0000E|\ + Error msg: {0}|\ + Error resolution text sample2|\ + Error description text sample2 + +METRICS_MESSAGE_ONEARGUMENT=\ + MET0000I|\ + Metrics msg: {0}|\ + Metrics resolution text sample2|\ + Metrics description text sample2 + +DUBUG_MESSAGE_ONEARGUMENT=\ + DEB0000I|\ + Debug msg: {0}|\ + Debug resolution text sample2|\ + Debug description text sample2 +MESSAGE_SAMPLE_TWOARGUMENTS=\ + APP4567I|\ + App1 message text sample with argument {0} and {1}|\ + App1 resolution text sample3|\ + App1 description text sample3 + +MESSAGE_SAMPLE_EXCEPTION=\ + APP6789E|\ + App1 message text sample4|\ + App1 resolution text sample4|\ + App1 description text sample4 + +MESSAGE_SAMPLE_EXCEPTION_ONEARGUMENT=\ + APP6790E|\ + This is the text exception in method {0}|\ + App1 resolution text sample5|\ + App1 description text sample5 + diff --git a/common-logging/src/main/resources/org/openecomp/policy/common/logging/eelf/Resources.properties b/common-logging/src/main/resources/org/openecomp/policy/common/logging/eelf/Resources.properties deleted file mode 100644 index c79061b4..00000000 --- a/common-logging/src/main/resources/org/openecomp/policy/common/logging/eelf/Resources.properties +++ /dev/null @@ -1,245 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-Logging -# ================================================================================ -# 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========================================================= -### - -#Resource key=Error Code|Message text|Resolution text |Description text -####### -# {APP}-{4-digit}{classification} - -#Newlines can be utilized to add some clarity ensuring continuing line -#has atleast one leading space -#ResourceKey=\ -# ERR0000E\ -# Sample error msg txt\ -# Sample resolution msg\ -# Sample description txt -# -###### -#Error code classification category -#100-199 Permission/Security Related -#200-299 Availability/Timeout Related -#300-399 Data Access/Integrity Related -#400-499 Schema Interface type/validation Related -#500-599 Business/Flow Processing Related -#900-999 Unknown errors -# -#{classification} description -# I = Information -# W = Warning -# E = Error -# F = Fatal - -######################################################################## - -GENERAL_INFO=\ - POLICY-500I|\ - INFO: {0}|\ - No resolution needed|\ - General flow processing info -GENERAL_WARNING=\ - POLICY-501W|\ - WARNING: {0}|\ - Please check other logs for more information|\ - General warning -UPDATE_ERROR=\ - POLICY-502E|\ - ERROR: Could not update {0}|\ - Please check other logs for more information|\ - Exception caught during server management - -EXCEPTION_ERROR=\ - POLICY-503E|\ - ERROR: Error Message: {0}|\ - Please check other logs for more information|\ - Exception caught during server management - -MISS_PROPERTY_ERROR=\ - POLICY-504E|\ - ERROR: {0} property not set in {1}.properties|\ - Please check other logs for more information|\ - Exception caught during server management - -BAD_TYPE_WARNING=\ - POLICY-505W|\ - WARNING: Bad types for Double Metric: {0} path: {1}|\ - Please check other logs for more information|\ - General warning - -MISS_PROPERTY_INFO=\ - POLICY-506I|\ - INFO: report: {0} not set|\ - No resolution needed|\ - General flow processing info - -RULE_AUDIT_EXEC_INFO=\ - POLICY-507I|\ - Service Name: {0}:Executing rule: {1}|\ - No resolution needed|\ - Executing method - -RULE_AUDIT_BEGIN_INFO=\ - POLICY-508I|\ - Service Name: {0}:Entering rule: {1}|\ - No resolution needed|\ - Entering method - -RULE_AUDIT_END_INFO=\ - POLICY-509I|\ - Service Name: {0}:Exiting rule: {1}|\ - No resolution needed|\ - Exiting method - -RULE_METRICS_INFO=\ - POLICY-510I|\ - Service Name: {0}:Executing method: {1}|\ - No resolution needed|\ - Generate information for Metric events - -UEB_AUDIT_EXEC_INFO=\ - POLICY-511I|\ - Service Name: {0}:Executing UEB: {1}|\ - No resolution needed|\ - Executing method - -UEB_AUDIT_BEGIN_INFO=\ - POLICY-512I|\ - Service Name: {0}:Entering UEB: {1}|\ - No resolution needed|\ - Entering method - -UEB_AUDIT_END_INFO=\ - POLICY-513I|\ - Service Name: {0}:Exiting UEB: {1}|\ - No resolution needed|\ - Exiting method - - - -RULE_AUDIT_START_END_INFO=\ - POLICY-514I|\ - Service Name: {0}:Executing rule:{1}:Starting Time:{2}:Ending Time:{3}:Executing Time:{4}:Policy version:{5}|\ - No resolution needed|\ - Executing method - -GENERAL_ERROR=\ - POLICY-515E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during server management - -ERROR_SYSTEM_ERROR=\ - POLICY-516E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during server management - -ERROR_DATA_ISSUE=\ - POLICY-517E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during server management - -ERROR_PERMISSIONS=\ - POLICY-100E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during server management - -ERROR_PROCESS_FLOW=\ - POLICY-518E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during server management - -ERROR_SCHEMA-INVALID=\ - POLICY-400E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during server management - -ERROR_UNKNOWN=\ - POLICY-519E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during server management - -ERROR_AUDIT=\ - POLICY-520E|\ - ERROR: {0}|\ - Please check other logs for more information|\ - error caught during audit process - -######################################################################## -######################################################################## -######################################################################## -#---------------- The message codes below should not be used anymore since 1607 release ----------------------------- - -MESSAGE_SAMPLE_NOARGS=\ - APP1234I|\ - App1 message text sample1|\ - App1 resolution text sample1|\ - App1 description text sample1 - -MESSAGE_SAMPLE_ONEARGUMENT=\ - APP3456I|\ - App1 msg smpl w arg: {0}|\ - App1 resolution text sample2|\ - App1 description text sample2 - -AUDIT_MESSAGE_ONEARGUMENT=\ - AUD0000I|\ - Audit msg: {0}|\ - Audit resolution text sample2|\ - Audit description text sample2 - -ERROR_MESSAGE_ONEARGUMENT=\ - ERR0000E|\ - Error msg: {0}|\ - Error resolution text sample2|\ - Error description text sample2 - -METRICS_MESSAGE_ONEARGUMENT=\ - MET0000I|\ - Metrics msg: {0}|\ - Metrics resolution text sample2|\ - Metrics description text sample2 - -DUBUG_MESSAGE_ONEARGUMENT=\ - DEB0000I|\ - Debug msg: {0}|\ - Debug resolution text sample2|\ - Debug description text sample2 -MESSAGE_SAMPLE_TWOARGUMENTS=\ - APP4567I|\ - App1 message text sample with argument {0} and {1}|\ - App1 resolution text sample3|\ - App1 description text sample3 - -MESSAGE_SAMPLE_EXCEPTION=\ - APP6789E|\ - App1 message text sample4|\ - App1 resolution text sample4|\ - App1 description text sample4 - -MESSAGE_SAMPLE_EXCEPTION_ONEARGUMENT=\ - APP6790E|\ - This is the text exception in method {0}|\ - App1 resolution text sample5|\ - App1 description text sample5 - diff --git a/integrity-audit/pom.xml b/integrity-audit/pom.xml index 51e2cca0..0e6fbb1e 100644 --- a/integrity-audit/pom.xml +++ b/integrity-audit/pom.xml @@ -1,6 +1,6 @@ org.eclipse.persistence.jpa.PersistenceProvider - org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity - org.openecomp.policy.common.ia.test.jpa.IaTestEntity + org.onap.policy.common.ia.jpa.IntegrityAuditEntity + org.onap.policy.common.ia.test.jpa.IaTestEntity NONE @@ -37,7 +37,7 @@ org.eclipse.persistence.jpa.PersistenceProvider - org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity + org.onap.policy.common.ia.jpa.IntegrityAuditEntity NONE diff --git a/integrity-audit/src/main/resources/logback.xml b/integrity-audit/src/main/resources/logback.xml index 426adf9e..c3b2f9f6 100644 --- a/integrity-audit/src/main/resources/logback.xml +++ b/integrity-audit/src/main/resources/logback.xml @@ -27,7 +27,7 @@ + ::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> 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 new file mode 100644 index 00000000..52f847cf --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/AuditPeriodTest.java @@ -0,0 +1,480 @@ +/*- + * ============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. + */ +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.isUnitTesting = true; + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("-1")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1", "pdp2", "pdp3")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1", "pdp2", "pdp3")); + ArrayList delegates = new ArrayList(); + 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/DbAuditCompareEntriesTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditCompareEntriesTest.java new file mode 100644 index 00000000..8a811366 --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditCompareEntriesTest.java @@ -0,0 +1,617 @@ +/*- + * ============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.FileOutputStream; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +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.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.IntegrityAuditEntity; +import org.onap.policy.common.ia.test.jpa.IaTestEntity; +import org.onap.policy.common.ia.test.jpa.PersonTest; +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. + */ +public class DbAuditCompareEntriesTest { + + 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"; + + @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(); + + logger.info("setUp: Entering"); + + IntegrityAudit.isUnitTesting = true; + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); + properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); + properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); + + dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; + dbUrl = IntegrityAuditProperties.DEFAULT_DB_URL; + dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; + dbPwd = IntegrityAuditProperties.DEFAULT_DB_PWD; + siteName = "SiteA"; + nodeType = "pdp_xacml"; + persistenceUnit = "testPU"; + resourceName = "pdp1"; + + logger.info("setUp: Exiting"); + } + + /* + * Clean up DB after each test. + */ + @After + public void tearDown() throws Exception { + logger.info("tearDown: Entering"); + + logger.info("tearDown: Exiting"); + } + + /* + * Tests that a comparison between hashsets is successful if + * the entries match + */ + @Ignore + @Test + public void testSuccessfulComparison() throws Exception { + logger.info("testSuccessfulComparison: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + String className = null; + //There is only one entry IntegrityAuditEntity, but we will check anyway + HashSet classNameSet = dbDAO.getPersistenceClassNames(); + 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 + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(persistenceUnit); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(false); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(persistenceUnit); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + HashSet result = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there are no mismatches returned + */ + assertTrue(result.isEmpty()); + + logger.info("testSuccessfulComparison: Exit"); + } + + /* + * Tests that an error is detected if an entry in one hashset doesn't + * match the other + */ + @Ignore + @Test + public void testComparisonError() throws Exception { + logger.info("testComparisonError: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + 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 + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(persistenceUnit); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(true); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(persistenceUnit); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + HashSet result = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there was one mismatch + */ + assertEquals(1, result.size()); + + logger.info("testComparisonError: Exit"); + } + + /* + * Tests that a mismatch/miss entry is detected if there are missing entries in + * one or both of the hashsets + */ + @Ignore + @Test + public void testCompareMissingEntries() throws Exception { + logger.info("testCompareMissingEntries: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + 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 + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(persistenceUnit); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(true); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(persistenceUnit); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + entry3.setDesignated(false); + entry3.setJdbcDriver(dbDriver); + entry3.setJdbcPassword(dbPwd); + entry3.setJdbcUrl(dbUrl); + entry3.setJdbcUser(dbUser); + entry3.setLastUpdated(date); + entry3.setNodeType(nodeType); + entry3.setPersistenceUnit(persistenceUnit); + entry3.setResourceName(resourceName2); + entry3.setSite("SiteB"); + + entry4.setDesignated(false); + entry4.setJdbcDriver(dbDriver); + entry4.setJdbcPassword(dbPwd); + entry4.setJdbcUrl(dbUrl); + entry4.setJdbcUser(dbUser); + entry4.setLastUpdated(date); + entry4.setNodeType(nodeType); + entry4.setPersistenceUnit(persistenceUnit); + entry4.setResourceName(resourceName2); + entry4.setSite("SiteB"); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("0", entry1); + myEntries.put("1", entry3); + theirEntries.put("0", entry2); + theirEntries.put("2", entry4); + + HashSet mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert 3 mismatches/missing entries were found + */ + assertEquals(3, mismatchResult.size()); + + logger.info("testCompareMissingEntries: Exit"); + } + + /* + * Tests that comparison algorithm works for each entity in the hashsets + */ + @Ignore + @Test + public void testCompareAllHashEntities() throws Exception { + logger.info("testCompareAllHashEntities: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + HashSet classNameSet = dbDAO.getPersistenceClassNames(); + HashSet mismatchResult = new HashSet(); + 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 + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(persistenceUnit); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(false); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(persistenceUnit); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + 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")) { + 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 myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + 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 + */ + @Ignore + @Test + public void testCompareAllDbEntities() throws Exception { + logger.info("testCompareAllDbEntities: Entering"); + + logger.info("Setting up DB"); + + IntegrityAudit.isUnitTesting = true; + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/iaTest2"); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); + properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); + properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); + + dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; + dbUrl = IntegrityAuditProperties.DEFAULT_DB_URL; + dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; + dbPwd = IntegrityAuditProperties.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(); + + // commit transaction + et2.commit(); + + et2.begin(); + + // Clean the IaTestEntity table + em2.createQuery("Delete from IaTestEntity").executeUpdate(); + + // 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); + DbAudit dbAudit = new DbAudit(dbDAO); + + // Add entries into DB2 + DbDAO dbDAO3 = new DbDAO(resourceName, persistenceUnit, properties2); + new DbDAO("pdp2", persistenceUnit, properties2); + + // Pull all entries and compare + HashSet classNameSet = dbDAO.getPersistenceClassNames(); + HashMap myEntries; + HashMap theirEntries; + HashSet mismatchResult = new HashSet(); + String className; + for(String c : classNameSet) { + className = c; + logger.info("classNameSet entry = " + c); + myEntries = dbDAO.getAllEntries(persistenceUnit, properties, className); + theirEntries = dbDAO3.getAllEntries(persistenceUnit, properties2, className); + mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); + if(className.contains("IntegrityAuditEntity")){ + break; + } + } + + // Assert that there is 2 mismatches between IntegrityAuditEntity tables + assertEquals(2, mismatchResult.size()); + + logger.info("testCompareAllDbEntities: Exit"); + } + + /* + * Tests that differences in embedded classes are still caught + */ + @Ignore + @Test + public void testEmbeddedClass() throws Exception { + logger.info("testEmbeddedClasses: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + String className = null; + //There is only one entry IntegrityAuditEntity, but we will check anyway + HashSet classNameSet = dbDAO.getPersistenceClassNames(); + for(String c : classNameSet){ + if (c.equals("org.onap.policy.common.ia.test.jpa.IaTestEntity")){ + className = c; + } + } + + IaTestEntity iate = new IaTestEntity(); + IaTestEntity iate2 = new IaTestEntity(); + + Date date = new Date(); + + PersonTest person = new PersonTest("Ford", "Prefect", 21); + PersonTest person2 = new PersonTest("Zaphod", "Beeblebrox", 25); + + /* + * Two entries, 1 mismatch + */ + iate.setCreatedBy("Ford"); + iate.setModifiedBy("Zaphod"); + iate.setModifiedDate(date); + iate.setPersonTest(person); + + iate2.setCreatedBy("Ford"); + iate2.setModifiedBy("Zaphod"); + iate2.setModifiedDate(date); + iate2.setPersonTest(person2); + + dbAudit.writeAuditDebugLog(className, "resource1", "resource2", iate, iate2); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("0", iate); + theirEntries.put("0", iate2); + + HashSet 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/test/DbAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditTest.java new file mode 100644 index 00000000..fd1172a8 --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbAuditTest.java @@ -0,0 +1,753 @@ +/*- + * ============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.Ignore; +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. + */ +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.isUnitTesting = true; + IntegrityAuditEntity.isUnitTesting = true; + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); + properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); + properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); + + dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; + dbUrl = IntegrityAuditProperties.DEFAULT_DB_URL; + dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; + dbPwd = IntegrityAuditProperties.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 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/iaTest2"); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 new file mode 100644 index 00000000..983e8911 --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/DbDAOTest.java @@ -0,0 +1,735 @@ +/*- + * ============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.*; + +/* + * 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.HashMap; +import java.util.HashSet; +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.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.Ignore; +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. + */ +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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); + properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); + properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); + + persistenceUnit = "integrityAuditPU"; + 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 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()); + } 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 + HashMap 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 cq = cb.createQuery(); + Root rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); + CriteriaQuery all = cq.select(rootEntry); + TypedQuery allQuery = em.createQuery(all); + List objectList = allQuery.getResultList(); + HashSet resultSet = new HashSet(); + PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); + for (Object o: objectList){ + Object key = util.getIdentifier(o); + resultSet.add(key); + } + + // Obtain a hash with the persisted objects + HashMap 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 + HashMap 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 cq = cb.createQuery(); + Root rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); + CriteriaQuery all = cq.select(rootEntry); + TypedQuery allQuery = em.createQuery(all); + List objectList = allQuery.getResultList(); + HashSet resultSet = new HashSet(); + PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); + for (Object o: objectList){ + Object key = util.getIdentifier(o); + resultSet.add(key); + } + + // Obtain a hash with the persisted objects + HashMap 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 + HashMap 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 + HashSet 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 new file mode 100644 index 00000000..f74b354b --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/IntegrityAuditDesignationTest.java @@ -0,0 +1,1109 @@ +/*- + * ============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. + */ +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.isUnitTesting = true; + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp1")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp1", "pdp2")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp1")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties4.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties4.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties4.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp4", "pdp1", "pdp2")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties4.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties4.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties4.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp4", "pdp1", "pdp2", "pdp4")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties4.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties4.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties4.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp3", "pdp3")); + ArrayList delegates = new ArrayList(); + 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); + properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1")); + ArrayList delegates = new ArrayList(); + 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/jpa/IaTestEntity.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/IaTestEntity.java new file mode 100644 index 00000000..53289e50 --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/IaTestEntity.java @@ -0,0 +1,157 @@ +/*- + * ============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.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="IaTestEntity") +@NamedQueries({ + @NamedQuery(name=" IaTestEntity.findAll", query="SELECT e FROM IaTestEntity e "), + @NamedQuery(name="IaTestEntity.deleteAll", query="DELETE FROM IaTestEntity WHERE 1=1") +}) +//@SequenceGenerator(name="seqImTest", initialValue=1, allocationSize=1) + +public class IaTestEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + //@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqImTest") + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="ImTestId") + private long imTestId; + + @Column(name="created_by", nullable=false, length=255) + private String createdBy = "guest"; + + @Column(name="person", nullable=false, length=255) + private PersonTest person; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="modified_by", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + public IaTestEntity() { + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + /** + * @return the Id + */ + public long getImTestId() { + return imTestId; + } + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + + /** + * @param modifiedBy the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + + /** + * @param modifiedDate the modifiedDate to set + */ + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @param the person to set + */ + public void setPersonTest(PersonTest p) { + this.person = p; + } + + /** + * @return the person + */ + public PersonTest getPersonTest() { + return person; + } +} diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/PersonTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/PersonTest.java new file mode 100644 index 00000000..0ca986bc --- /dev/null +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/test/jpa/PersonTest.java @@ -0,0 +1,64 @@ +/*- + * ============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.jpa; + +import java.io.Serializable; + +public class PersonTest implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + private String firstName; + private String lastName; + private int age; + + public PersonTest(String first, String last, int age) { + this.firstName = first; + this.lastName = last; + this.age = age; + } + + public String getFirstName() { + return this.firstName; + } + + public void setFirstName(String name) { + this.firstName = name; + } + + public String getLasttName() { + return this.lastName; + } + + public void setLastName(String name) { + this.lastName = name; + } + + public int getAge() { + return this.age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/AuditPeriodTest.java b/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/AuditPeriodTest.java deleted file mode 100644 index d0c64065..00000000 --- a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/AuditPeriodTest.java +++ /dev/null @@ -1,480 +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.openecomp.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.openecomp.policy.common.ia.AuditThread; -import org.openecomp.policy.common.ia.IntegrityAudit; -import org.openecomp.policy.common.ia.IntegrityAuditProperties; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.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. - */ -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.isUnitTesting = true; - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("-1")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1", "pdp2", "pdp3")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1", "pdp2", "pdp3")); - ArrayList delegates = new ArrayList(); - 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/openecomp/policy/common/ia/test/DbAuditCompareEntriesTest.java b/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbAuditCompareEntriesTest.java deleted file mode 100644 index e2fd922d..00000000 --- a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbAuditCompareEntriesTest.java +++ /dev/null @@ -1,617 +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.openecomp.policy.common.ia.test; - -import static org.junit.Assert.*; - -import java.io.FileOutputStream; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -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.openecomp.policy.common.ia.DbAudit; -import org.openecomp.policy.common.ia.DbDAO; -import org.openecomp.policy.common.ia.IntegrityAudit; -import org.openecomp.policy.common.ia.IntegrityAuditProperties; -import org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity; -import org.openecomp.policy.common.ia.test.jpa.IaTestEntity; -import org.openecomp.policy.common.ia.test.jpa.PersonTest; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.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. - */ -public class DbAuditCompareEntriesTest { - - 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"; - - @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(); - - logger.info("setUp: Entering"); - - IntegrityAudit.isUnitTesting = true; - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; - dbUrl = IntegrityAuditProperties.DEFAULT_DB_URL; - dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; - dbPwd = IntegrityAuditProperties.DEFAULT_DB_PWD; - siteName = "SiteA"; - nodeType = "pdp_xacml"; - persistenceUnit = "testPU"; - resourceName = "pdp1"; - - logger.info("setUp: Exiting"); - } - - /* - * Clean up DB after each test. - */ - @After - public void tearDown() throws Exception { - logger.info("tearDown: Entering"); - - logger.info("tearDown: Exiting"); - } - - /* - * Tests that a comparison between hashsets is successful if - * the entries match - */ - @Ignore - @Test - public void testSuccessfulComparison() throws Exception { - logger.info("testSuccessfulComparison: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - String className = null; - //There is only one entry IntegrityAuditEntity, but we will check anyway - HashSet classNameSet = dbDAO.getPersistenceClassNames(); - for(String c : classNameSet){ - if (c.equals("org.openecomp.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 - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(false); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - HashSet result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there are no mismatches returned - */ - assertTrue(result.isEmpty()); - - logger.info("testSuccessfulComparison: Exit"); - } - - /* - * Tests that an error is detected if an entry in one hashset doesn't - * match the other - */ - @Ignore - @Test - public void testComparisonError() throws Exception { - logger.info("testComparisonError: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - 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 - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(true); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - HashSet result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there was one mismatch - */ - assertEquals(1, result.size()); - - logger.info("testComparisonError: Exit"); - } - - /* - * Tests that a mismatch/miss entry is detected if there are missing entries in - * one or both of the hashsets - */ - @Ignore - @Test - public void testCompareMissingEntries() throws Exception { - logger.info("testCompareMissingEntries: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - 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 - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(true); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - entry3.setDesignated(false); - entry3.setJdbcDriver(dbDriver); - entry3.setJdbcPassword(dbPwd); - entry3.setJdbcUrl(dbUrl); - entry3.setJdbcUser(dbUser); - entry3.setLastUpdated(date); - entry3.setNodeType(nodeType); - entry3.setPersistenceUnit(persistenceUnit); - entry3.setResourceName(resourceName2); - entry3.setSite("SiteB"); - - entry4.setDesignated(false); - entry4.setJdbcDriver(dbDriver); - entry4.setJdbcPassword(dbPwd); - entry4.setJdbcUrl(dbUrl); - entry4.setJdbcUser(dbUser); - entry4.setLastUpdated(date); - entry4.setNodeType(nodeType); - entry4.setPersistenceUnit(persistenceUnit); - entry4.setResourceName(resourceName2); - entry4.setSite("SiteB"); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("0", entry1); - myEntries.put("1", entry3); - theirEntries.put("0", entry2); - theirEntries.put("2", entry4); - - HashSet mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert 3 mismatches/missing entries were found - */ - assertEquals(3, mismatchResult.size()); - - logger.info("testCompareMissingEntries: Exit"); - } - - /* - * Tests that comparison algorithm works for each entity in the hashsets - */ - @Ignore - @Test - public void testCompareAllHashEntities() throws Exception { - logger.info("testCompareAllHashEntities: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - HashSet classNameSet = dbDAO.getPersistenceClassNames(); - HashSet mismatchResult = new HashSet(); - for(String c : classNameSet) { - if (c.equals("org.openecomp.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 - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(false); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(persistenceUnit); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - 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.openecomp.policy.common.ia.test.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 myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - 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 - */ - @Ignore - @Test - public void testCompareAllDbEntities() throws Exception { - logger.info("testCompareAllDbEntities: Entering"); - - logger.info("Setting up DB"); - - IntegrityAudit.isUnitTesting = true; - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/iaTest2"); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); - properties2.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties2.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; - dbUrl = IntegrityAuditProperties.DEFAULT_DB_URL; - dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; - dbPwd = IntegrityAuditProperties.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(); - - // commit transaction - et2.commit(); - - et2.begin(); - - // Clean the IaTestEntity table - em2.createQuery("Delete from IaTestEntity").executeUpdate(); - - // 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); - DbAudit dbAudit = new DbAudit(dbDAO); - - // Add entries into DB2 - DbDAO dbDAO3 = new DbDAO(resourceName, persistenceUnit, properties2); - new DbDAO("pdp2", persistenceUnit, properties2); - - // Pull all entries and compare - HashSet classNameSet = dbDAO.getPersistenceClassNames(); - HashMap myEntries; - HashMap theirEntries; - HashSet mismatchResult = new HashSet(); - String className; - for(String c : classNameSet) { - className = c; - logger.info("classNameSet entry = " + c); - myEntries = dbDAO.getAllEntries(persistenceUnit, properties, className); - theirEntries = dbDAO3.getAllEntries(persistenceUnit, properties2, className); - mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - if(className.contains("IntegrityAuditEntity")){ - break; - } - } - - // Assert that there is 2 mismatches between IntegrityAuditEntity tables - assertEquals(2, mismatchResult.size()); - - logger.info("testCompareAllDbEntities: Exit"); - } - - /* - * Tests that differences in embedded classes are still caught - */ - @Ignore - @Test - public void testEmbeddedClass() throws Exception { - logger.info("testEmbeddedClasses: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - String className = null; - //There is only one entry IntegrityAuditEntity, but we will check anyway - HashSet classNameSet = dbDAO.getPersistenceClassNames(); - for(String c : classNameSet){ - if (c.equals("org.openecomp.policy.common.ia.test.jpa.IaTestEntity")){ - className = c; - } - } - - IaTestEntity iate = new IaTestEntity(); - IaTestEntity iate2 = new IaTestEntity(); - - Date date = new Date(); - - PersonTest person = new PersonTest("Ford", "Prefect", 21); - PersonTest person2 = new PersonTest("Zaphod", "Beeblebrox", 25); - - /* - * Two entries, 1 mismatch - */ - iate.setCreatedBy("Ford"); - iate.setModifiedBy("Zaphod"); - iate.setModifiedDate(date); - iate.setPersonTest(person); - - iate2.setCreatedBy("Ford"); - iate2.setModifiedBy("Zaphod"); - iate2.setModifiedDate(date); - iate2.setPersonTest(person2); - - dbAudit.writeAuditDebugLog(className, "resource1", "resource2", iate, iate2); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("0", iate); - theirEntries.put("0", iate2); - - HashSet 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/openecomp/policy/common/ia/test/DbAuditTest.java b/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbAuditTest.java deleted file mode 100644 index 82ea8669..00000000 --- a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbAuditTest.java +++ /dev/null @@ -1,753 +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.openecomp.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.Ignore; -import org.junit.Test; - -import org.openecomp.policy.common.ia.DbAudit; -import org.openecomp.policy.common.ia.DbAuditException; -import org.openecomp.policy.common.ia.DbDAO; -import org.openecomp.policy.common.ia.DbDaoTransactionException; -import org.openecomp.policy.common.ia.IntegrityAudit; -import org.openecomp.policy.common.ia.IntegrityAuditProperties; -import org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.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. - */ -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.isUnitTesting = true; - IntegrityAuditEntity.isUnitTesting = true; - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; - dbUrl = IntegrityAuditProperties.DEFAULT_DB_URL; - dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; - dbPwd = IntegrityAuditProperties.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 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/iaTest2"); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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/openecomp/policy/common/ia/test/DbDAOTest.java b/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbDAOTest.java deleted file mode 100644 index 3bd847c2..00000000 --- a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/DbDAOTest.java +++ /dev/null @@ -1,735 +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.openecomp.policy.common.ia.test; - -import static org.junit.Assert.*; - -/* - * 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.HashMap; -import java.util.HashSet; -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.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.Ignore; -import org.junit.Test; - -import org.openecomp.policy.common.ia.DbDAO; -import org.openecomp.policy.common.ia.DbDaoTransactionException; -import org.openecomp.policy.common.ia.IntegrityAuditProperties; -import org.openecomp.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. - */ -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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_xacml"); - - persistenceUnit = "integrityAuditPU"; - 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 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()); - } 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 - HashMap entries = d.getAllMyEntries("org.openecomp.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 cq = cb.createQuery(); - Root rootEntry = cq.from(Class.forName("org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity")); - CriteriaQuery all = cq.select(rootEntry); - TypedQuery allQuery = em.createQuery(all); - List objectList = allQuery.getResultList(); - HashSet resultSet = new HashSet(); - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - for (Object o: objectList){ - Object key = util.getIdentifier(o); - resultSet.add(key); - } - - // Obtain a hash with the persisted objects - HashMap entries = d.getAllMyEntries("org.openecomp.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 - HashMap entries = d.getAllEntries("integrityAuditPU", properties, "org.openecomp.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 cq = cb.createQuery(); - Root rootEntry = cq.from(Class.forName("org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity")); - CriteriaQuery all = cq.select(rootEntry); - TypedQuery allQuery = em.createQuery(all); - List objectList = allQuery.getResultList(); - HashSet resultSet = new HashSet(); - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - for (Object o: objectList){ - Object key = util.getIdentifier(o); - resultSet.add(key); - } - - // Obtain a hash with the persisted objects - HashMap entries = d.getAllEntries("integrityAuditPU", properties, "org.openecomp.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 - HashMap entries = d.getAllEntries(persistenceUnit, properties, "org.openecomp.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 - HashSet result = d.getPersistenceClassNames(); - assertEquals(1, result.size()); - } -} diff --git a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/IntegrityAuditDesignationTest.java b/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/IntegrityAuditDesignationTest.java deleted file mode 100644 index 69936bfe..00000000 --- a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/IntegrityAuditDesignationTest.java +++ /dev/null @@ -1,1109 +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.openecomp.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.openecomp.policy.common.ia.AuditThread; -import org.openecomp.policy.common.ia.DbDAO; -import org.openecomp.policy.common.ia.IntegrityAudit; -import org.openecomp.policy.common.ia.IntegrityAuditProperties; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.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. - */ -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.isUnitTesting = true; - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 ECOMPD2TD-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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp1")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp1", "pdp2")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp1")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties4.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties4.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties4.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp4", "pdp1", "pdp2")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties4.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties4.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties4.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp4", "pdp1", "pdp2", "pdp4")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties4.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties4.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties4.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp3", "pdp3")); - ArrayList delegates = new ArrayList(); - 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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties2.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties2.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties2.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties3.put(IntegrityAuditProperties.DB_URL, IntegrityAuditProperties.DEFAULT_DB_URL); - properties3.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties3.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.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 expectedResult = new ArrayList(Arrays.asList("pdp1", "pdp2", "pdp3", "pdp1")); - ArrayList delegates = new ArrayList(); - 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/openecomp/policy/common/ia/test/jpa/IaTestEntity.java b/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/jpa/IaTestEntity.java deleted file mode 100644 index 21b09460..00000000 --- a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/jpa/IaTestEntity.java +++ /dev/null @@ -1,157 +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.openecomp.policy.common.ia.test.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="IaTestEntity") -@NamedQueries({ - @NamedQuery(name=" IaTestEntity.findAll", query="SELECT e FROM IaTestEntity e "), - @NamedQuery(name="IaTestEntity.deleteAll", query="DELETE FROM IaTestEntity WHERE 1=1") -}) -//@SequenceGenerator(name="seqImTest", initialValue=1, allocationSize=1) - -public class IaTestEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - //@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqImTest") - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="ImTestId") - private long imTestId; - - @Column(name="created_by", nullable=false, length=255) - private String createdBy = "guest"; - - @Column(name="person", nullable=false, length=255) - private PersonTest person; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - public IaTestEntity() { - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - /** - * @return the Id - */ - public long getImTestId() { - return imTestId; - } - - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @param the person to set - */ - public void setPersonTest(PersonTest p) { - this.person = p; - } - - /** - * @return the person - */ - public PersonTest getPersonTest() { - return person; - } -} diff --git a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/jpa/PersonTest.java b/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/jpa/PersonTest.java deleted file mode 100644 index 7ec5e294..00000000 --- a/integrity-audit/src/test/java/org/openecomp/policy/common/ia/test/jpa/PersonTest.java +++ /dev/null @@ -1,64 +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.openecomp.policy.common.ia.test.jpa; - -import java.io.Serializable; - -public class PersonTest implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - private String firstName; - private String lastName; - private int age; - - public PersonTest(String first, String last, int age) { - this.firstName = first; - this.lastName = last; - this.age = age; - } - - public String getFirstName() { - return this.firstName; - } - - public void setFirstName(String name) { - this.firstName = name; - } - - public String getLasttName() { - return this.lastName; - } - - public void setLastName(String name) { - this.lastName = name; - } - - public int getAge() { - return this.age; - } - - public void setAge(int age) { - this.age = age; - } - -} diff --git a/integrity-audit/src/test/resources/logback.xml b/integrity-audit/src/test/resources/logback.xml index 78de63a3..9086aa9d 100644 --- a/integrity-audit/src/test/resources/logback.xml +++ b/integrity-audit/src/test/resources/logback.xml @@ -29,7 +29,7 @@ + ::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> diff --git a/integrity-monitor/pom.xml b/integrity-monitor/pom.xml index af87572f..4a31a522 100644 --- a/integrity-monitor/pom.xml +++ b/integrity-monitor/pom.xml @@ -1,6 +1,6 @@ org.eclipse.persistence.jpa.PersistenceProvider - org.openecomp.policy.common.im.jpa.ImTestEntity - org.openecomp.policy.common.im.jpa.StateManagementEntity - org.openecomp.policy.common.im.jpa.ForwardProgressEntity - org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity + org.onap.policy.common.im.jpa.ImTestEntity + org.onap.policy.common.im.jpa.StateManagementEntity + org.onap.policy.common.im.jpa.ForwardProgressEntity + org.onap.policy.common.im.jpa.ResourceRegistrationEntity NONE @@ -39,10 +39,10 @@ org.eclipse.persistence.jpa.PersistenceProvider - org.openecomp.policy.common.im.jpa.ImTestEntity - org.openecomp.policy.common.im.jpa.StateManagementEntity - org.openecomp.policy.common.im.jpa.ForwardProgressEntity - org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity + org.onap.policy.common.im.jpa.ImTestEntity + org.onap.policy.common.im.jpa.StateManagementEntity + org.onap.policy.common.im.jpa.ForwardProgressEntity + org.onap.policy.common.im.jpa.ResourceRegistrationEntity NONE diff --git a/integrity-monitor/src/main/resources/logback.xml b/integrity-monitor/src/main/resources/logback.xml index 1c888097..2fa92a09 100644 --- a/integrity-monitor/src/main/resources/logback.xml +++ b/integrity-monitor/src/main/resources/logback.xml @@ -27,7 +27,7 @@ + ::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/test/IntegrityMonitorTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/IntegrityMonitorTest.java new file mode 100644 index 00000000..afa2ca94 --- /dev/null +++ b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/IntegrityMonitorTest.java @@ -0,0 +1,1232 @@ +/*- + * ============LICENSE_START======================================================= + * Integrity Monitor + * ================================================================================ + * 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.im.test; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +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 javax.persistence.TemporalType; + +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.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; + + + +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.IntegrityMonitorProperties; +import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.im.jpa.ForwardProgressEntity; +import org.onap.policy.common.im.jpa.ResourceRegistrationEntity; +import org.onap.policy.common.im.jpa.StateManagementEntity; +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. + */ +public class IntegrityMonitorTest { + private static Logger logger = FlexLogger.getLogger(IntegrityMonitorTest.class); + private static Properties myProp; + private static EntityManagerFactory emf; + private static EntityManager em; + private static EntityTransaction et; + private static String resourceName; + private static Properties systemProps; + + @BeforeClass + public static void setUpClass() throws Exception { + + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + IntegrityMonitor.isUnitTesting = true; + + myProp = new Properties(); + myProp.put(IntegrityMonitorProperties.DB_DRIVER, IntegrityMonitorProperties.DEFAULT_DB_DRIVER); + myProp.put(IntegrityMonitorProperties.DB_URL, IntegrityMonitorProperties.DEFAULT_DB_URL); + myProp.put(IntegrityMonitorProperties.DB_USER, IntegrityMonitorProperties.DEFAULT_DB_USER); + myProp.put(IntegrityMonitorProperties.DB_PWD, IntegrityMonitorProperties.DEFAULT_DB_PWD); + myProp.put(IntegrityMonitorProperties.SITE_NAME, "SiteA"); + myProp.put(IntegrityMonitorProperties.NODE_TYPE, "pap"); + + // set JMX remote port in system properties + systemProps = System.getProperties(); + systemProps.put("com.sun.management.jmxremote.port", "9797"); + + resourceName = "siteA.pap1"; + + //Create the data schema and entity manager factory + emf = Persistence.createEntityManagerFactory("schemaPU", myProp); + + // Create an entity manager to use the DB + em = emf.createEntityManager(); + + } + + + @After + public void tearDown() throws Exception { + // clear jmx remote port setting + systemProps.remove("com.sun.management.jmxremote.port"); + } + + /* + * The following runs all tests and controls the order of execution. If you allow + * the tests to execute individually, you cannot predict the order and some + * conflicts occur. + */ + @Ignore + @Test + public void runAllTests() throws Exception{ + //testSanityJmx(); + //testIM(); + //testSanityState(); + testRefreshStateAudit(); + //testStateCheck(); + //testGetAllForwardProgressEntity(); + //testStateAudit(); + } + + /* + * The following test verifies the following test cases: + * New Install + * New Install - Bad Dependency data + * Recovery from bad dependency data + * Lock + * Lock restart + * Unlock + * Unlock restart + */ + public void testSanityJmx() throws Exception { + System.out.println("\nIntegrityMonitorTest: Entering testSanityJmx\n\n"); + + String dependent = "group1_logparser"; + + // parameters are passed via a properties file + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, dependent); + myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "true"); + IntegrityMonitor.updateProperties(myProp); + + IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); + System.out.println("\n\ntestSanityJmx starting im state" + + "\nAdminState = " + im.getStateManager().getAdminState() + + "\nOpState() = " + im.getStateManager().getOpState() + + "\nAvailStatus = " + im.getStateManager().getAvailStatus() + + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() + + "\n"); + // add an entry to Resource registration table in the DB for the dependent resource + + + et = em.getTransaction(); + et.begin(); + Query rquery = em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn"); + rquery.setParameter("rn", dependent); + + @SuppressWarnings("rawtypes") + List rrList = rquery.getResultList(); + ResourceRegistrationEntity rrx = null; + if(rrList.isEmpty()){ + // register resource by adding entry to table in DB + System.out.println("Adding resource " + dependent + " to ResourceRegistration table"); + rrx = new ResourceRegistrationEntity(); + // set columns in entry + rrx.setResourceName(dependent); + rrx.setResourceUrl("service:jmx:somewhere:9999"); + rrx.setNodeType("logparser"); + rrx.setSite("siteA"); + } + em.persist(rrx); + // flush to the DB + em.flush(); + + // commit transaction + et.commit(); + + Thread.sleep(15000); //sleep 15 sec so the FPManager has time to call evaluateSanty() + + boolean sanityPass = true; + try { + im.evaluateSanity(); + } catch (Exception e) { + System.out.println("evaluateSanity exception: " + e); + sanityPass = false; + } + assertFalse(sanityPass); // expect sanity test to fail + + // undo dependency groups and jmx test properties settings + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); + myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); + IntegrityMonitor.updateProperties(myProp); + + System.out.println("\ntestSantityJmx ending properties: " + myProp); + + //We know at this point that the IM is disable-dependency. We want to be + //sure it will recover from this condition since the properties were + //updated. + + + System.out.println("\n\ntestSanityJmx ending im state" + + "\nAdminState = " + im.getStateManager().getAdminState() + + "\nOpState() = " + im.getStateManager().getOpState() + + "\nAvailStatus = " + im.getStateManager().getAvailStatus() + + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() + + "\n"); + + //Destroy the instance + System.out.println("\ntestSanityJmx restarting the IntegrityMonitor"); + IntegrityMonitor.deleteInstance(); + //Create a new instance. It should recover from the disabled-dependency condition + im = IntegrityMonitor.getInstance(resourceName, myProp); + + System.out.println("\n\ntestSanityJmx state after creating new im" + + "\nAdminState = " + im.getStateManager().getAdminState() + + "\nOpState() = " + im.getStateManager().getOpState() + + "\nAvailStatus = " + im.getStateManager().getAvailStatus() + + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() + + "\n"); + + //Verify the state + assertEquals(im.getStateManager().getAdminState(), StateManagement.UNLOCKED); + assertEquals(im.getStateManager().getOpState(), StateManagement.ENABLED); + assertEquals(im.getStateManager().getAvailStatus(), StateManagement.NULL_VALUE); + assertEquals(im.getStateManager().getStandbyStatus(), StateManagement.NULL_VALUE); + + //Test state manager via the IntegrityMonitor + StateManagement sm = im.getStateManager(); + + // Verify lock state + sm.lock(); + System.out.println("\n\nsm.lock()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAdminState().equals(StateManagement.LOCKED)); + + //Verify lock persists across a restart + //Destroy the instance + System.out.println("\ntestSanityJmx restarting the IntegrityMonitor"); + IntegrityMonitor.deleteInstance(); + //Create a new instance. It should come up with the admin state locked + im = IntegrityMonitor.getInstance(resourceName, myProp); + sm = im.getStateManager(); + System.out.println("\n\ntestSanityJmx restart with AdminState=locked" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAdminState().equals(StateManagement.LOCKED)); + + // Verify unlock + sm.unlock(); + System.out.println("\n\ntestSanityJmx sm.unlock" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAdminState().equals(StateManagement.UNLOCKED)); + + // Verify unlock restart + //Destroy the instance + System.out.println("\ntestSanityJmx restarting the IntegrityMonitor"); + IntegrityMonitor.deleteInstance(); + //Create a new instance. It should come up with the admin state locked + im = IntegrityMonitor.getInstance(resourceName, myProp); + sm = im.getStateManager(); + System.out.println("\n\ntestSanityJmx restart with AdminState=unlocked" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAdminState().equals(StateManagement.UNLOCKED)); + + System.out.println("\n\ntestSanityJmx: Exit\n\n"); + } + + + public void testIM() throws Exception { + System.out.println("\nIntegrityMonitorTest: Entering testIM\n\n"); + + // parameters are passed via a properties file + + /* + * Create an IntegrityMonitor + * NOTE: This uses the database that was created above. So, this MUST follow the creation + * of the DB + */ + IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); + + System.out.println("\n\nim before sleep" + + "\nAdminState = " + im.getStateManager().getAdminState() + + "\nOpState() = " + im.getStateManager().getOpState() + + "\nAvailStatus = " + im.getStateManager().getAvailStatus() + + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() + + "\n"); + + // wait for test transactions to fire and increment fpc + Thread.sleep(20000); + + System.out.println("\n\nim after sleep" + + "\nAdminState = " + im.getStateManager().getAdminState() + + "\nOpState() = " + im.getStateManager().getOpState() + + "\nAvailStatus = " + im.getStateManager().getAvailStatus() + + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() + + "\n"); + + // test evaluate sanity + boolean sanityPass = true; + try { + im.evaluateSanity(); + } catch (Exception e) { + System.out.println("evaluateSanity exception: " + e); + sanityPass = false; + } + assertTrue(sanityPass); // expect sanity test to pass + + //Test startTransaction - should works since it is unlocked + boolean transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(transPass); + + //Test state manager via the IntegrityMonitor + StateManagement sm = im.getStateManager(); + + sm.lock(); + System.out.println("\n\nsm.lock()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAdminState().equals(StateManagement.LOCKED)); + + //test startTransaction. It should fail since it is locked + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(!transPass); //expect it to fail + + sm.unlock(); + System.out.println("\n\nsm.unlock()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAdminState().equals(StateManagement.UNLOCKED)); + + //test startTransaction. It should succeed + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(transPass); //expect it to succeed + + sm.disableDependency(); + System.out.println("\n\nsm.disableDependency()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getOpState().equals(StateManagement.DISABLED)); + assert(sm.getAvailStatus().equals(StateManagement.DEPENDENCY)); + + //test startTransaction. It should succeed since standby status is null and unlocked + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(transPass); //expect it to succeed + + sm.enableNoDependency(); + System.out.println("\n\nsm.enableNoDependency()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getOpState().equals(StateManagement.ENABLED)); + //test startTransaction. It should succeed since standby status is null and unlocked + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(transPass); //expect it to succeed + + + sm.disableFailed(); + System.out.println("\n\nsm.disableFailed()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getOpState().equals(StateManagement.DISABLED)); + assert(sm.getAvailStatus().equals(StateManagement.FAILED)); + //test startTransaction. It should succeed since standby status is null and unlocked + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(transPass); //expect it to succeed + + sm.enableNotFailed(); + System.out.println("\n\nsm.enabledNotFailed()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getOpState().equals(StateManagement.ENABLED)); + //test startTransaction. It should succeed since standby status is null and unlocked + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(transPass); //expect it to succeed + + sm.demote(); + System.out.println("\n\nsm.demote()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); + + //test startTransaction. It should fail since it is standby + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(!transPass); //expect it to fail + + sm.promote(); + System.out.println("\n\nsm.promote()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + //test startTransaction. It should succeed since it is providing service + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(transPass); //expect it to succeed + + + //Test the multi-valued availability status + sm.disableDependency(); + sm.disableFailed(); + System.out.println("\n\nsm.disableDependency(), sm.disableFailed" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAvailStatus().equals(StateManagement.DEPENDENCY_FAILED)); + + //Test startTransaction. Should fail since standby status is cold standby + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(!transPass); //expect it to fail + + sm.enableNoDependency(); + System.out.println("\n\nsm.enableNoDependency()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAvailStatus().equals(StateManagement.FAILED)); + //Test startTransaction. Should fail since standby status is cold standby + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(!transPass); //expect it to fail + + sm.disableDependency(); + sm.enableNotFailed(); + System.out.println("\n\nsm.disableDependency(),sm.enableNotFailed()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getAvailStatus().equals(StateManagement.DEPENDENCY)); + //Test startTransaction. Should fail since standby status is cold standby + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(!transPass); //expect it to fail + + sm.enableNoDependency(); + System.out.println("\n\nsm.enableNoDependency()" + + "\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + assert(sm.getOpState().equals(StateManagement.ENABLED)); + //test startTransaction. It should fail since standby status is hot standby + transPass = true; + try{ + im.startTransaction(); + } catch (Exception e){ + System.out.println("startTransaction exception: " + e); + transPass = false; + } + assertTrue(!transPass); //expect it to fail + + System.out.println("\n\ntestIM: Exit\n\n"); + } + + + public void testSanityState() throws Exception { + System.out.println("\nIntegrityMonitorTest: Entering testSanityState\n\n"); + + // parameters are passed via a properties file + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "group1_dep1,group1_dep2; group2_dep1"); + IntegrityMonitor.updateProperties(myProp); + + IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); + + // Add a group1 dependent resources to put an entry in the forward progress table + ForwardProgressEntity fpe = new ForwardProgressEntity(); + ForwardProgressEntity fpe2 = new ForwardProgressEntity(); + fpe.setFpcCount(0); + fpe.setResourceName("group1_dep1"); + fpe2.setFpcCount(0); + fpe2.setResourceName("group1_dep2"); + et = em.getTransaction(); + et.begin(); + em.persist(fpe); + em.persist(fpe2); + em.flush(); + et.commit(); + + + // Add a group2 dependent resource to the StateManagementEntity DB table and set its admin state to locked + // Expect sanity test to fail. + StateManagement stateManager = new StateManagement(emf, "group2_dep1"); + stateManager.lock(); + + new StateManagement(emf, "group1_dep1"); + new StateManagement(emf, "group1_dep2"); + + boolean sanityPass = true; + Thread.sleep(15000); + try { + im.evaluateSanity(); + } catch (Exception e) { + System.out.println("evaluateSanity exception: " + e); + sanityPass = false; + } + assertFalse(sanityPass); // expect sanity test to fail + + // undo dependency groups and jmx test properties settings + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); + myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); + IntegrityMonitor.updateProperties(myProp); + + et = em.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + System.out.println("\n\ntestSanityState: Exit\n\n"); + } + + public void testRefreshStateAudit() throws Exception { + logger.debug("\nIntegrityMonitorTest: testRefreshStateAudit Enter\n\n"); + + // parameters are passed via a properties file + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); + myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); + myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "60000"); + IntegrityMonitor.updateProperties(myProp); + + et = em.getTransaction(); + et.begin(); + + // Make sure we leave the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + IntegrityMonitor.deleteInstance(); + + IntegrityMonitor.getInstance(resourceName, myProp); + + //the state here is unlocked, enabled, null, null + StateManagementEntity sme = null; + + Query query = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); + + query.setParameter("resource", resourceName); + + //Just test that we are retrieving the right object + @SuppressWarnings("rawtypes") + List resourceList = query.getResultList(); + if (!resourceList.isEmpty()) { + // exist + sme = (StateManagementEntity) resourceList.get(0); + em.refresh(sme); + + logger.debug("??? -- Retrieve StateManagementEntity from database --" + + "\nsme.getResourceName() = " + sme.getResourceName() + + "\nsme.getAdminState() = " + sme.getAdminState() + + "\nsme.getOpState() = " + sme.getOpState() + + "\nsme.getAvailStatus() = " + sme.getAvailStatus() + + "\nsme.getStandbyStatus() = " + sme.getStandbyStatus()); + + assertTrue(sme.getAdminState().equals(StateManagement.UNLOCKED)); + assertTrue(sme.getOpState().equals(StateManagement.ENABLED)); + assertTrue(sme.getAvailStatus().equals(StateManagement.NULL_VALUE)); + assertTrue(sme.getStandbyStatus().equals(StateManagement.NULL_VALUE)); + logger.debug("--"); + } else { + logger.debug("Record not found, resourceName: " + resourceName); + assertTrue(false); + } + + et = em.getTransaction(); + et.begin(); + + sme.setStandbyStatus(StateManagement.COLD_STANDBY); + em.persist(sme); + em.flush(); + et.commit(); + + Thread.sleep(65000); + + //The refreshStateAudit should run and change the state to unlocked,enabled,null,hotstandby + StateManagementEntity sme1 = null; + + Query query1 = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); + + query1.setParameter("resource", resourceName); + + //Just test that we are retrieving the right object + @SuppressWarnings("rawtypes") + List resourceList1 = query1.getResultList(); + if (!resourceList1.isEmpty()) { + // exist + sme1 = (StateManagementEntity) resourceList1.get(0); + em.refresh(sme1); + logger.debug("??? -- Retrieve StateManagementEntity from database --" + + "\nsme1.getResourceName() = " + sme1.getResourceName() + + "\nsme1.getAdminState() = " + sme1.getAdminState() + + "\nsme1.getOpState() = " + sme1.getOpState() + + "\nsme1.getAvailStatus() = " + sme1.getAvailStatus() + + "\nsme1.getStandbyStatus() = " + sme1.getStandbyStatus()); + + assertTrue(sme1.getAdminState().equals(StateManagement.UNLOCKED)); + assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); + assertTrue(sme1.getAvailStatus().equals(StateManagement.NULL_VALUE)); + assertTrue(sme1.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); + logger.debug("--"); + } else { + logger.debug("Record not found, resourceName: " + resourceName); + assertTrue(false); + } + + et = em.getTransaction(); + et.begin(); + + // Make sure we leave the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + IntegrityMonitor.deleteInstance(); + + logger.debug("\nIntegrityMonitorTest: testRefreshStateAudit Exit\n\n"); + } + + public void testStateCheck() throws Exception { + System.out.println("\nIntegrityMonitorTest: Entering testStateCheck\n\n"); + + // parameters are passed via a properties file + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "group1_dep1"); + myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); + myProp.put(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, "1"); + myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "10"); + IntegrityMonitor.updateProperties(myProp); + /* + * The default monitorInterval is 30 and the default failedCounterThreshold is 3 + * Since stateCheck() uses the faileCounterThreshold * monitorInterval to determine + * if an entry is stale, it will be stale after 30 seconds. + */ + + et = em.getTransaction(); + et.begin(); + + // Make sure we start with the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + IntegrityMonitor.deleteInstance(); + + IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); + + // Add a group1 dependent resources to put an entry in the forward progress table + // This sets lastUpdated to the current time + ForwardProgressEntity fpe = new ForwardProgressEntity(); + fpe.setFpcCount(0); + fpe.setResourceName("group1_dep1"); + et = em.getTransaction(); + et.begin(); + em.persist(fpe); + em.flush(); + et.commit(); + + new StateManagement(emf, "group1_dep1"); + + boolean sanityPass = true; + //Thread.sleep(15000); + Thread.sleep(5000); + try { + im.evaluateSanity(); + } catch (Exception e) { + System.out.println("testStateCheck: After 15 sec sleep - evaluateSanity exception: " + e); + sanityPass = false; + } + assertTrue(sanityPass); // expect sanity test to pass + + //now wait 30 seconds. The dependency entry should now be stale and the sanitry check should fail + + sanityPass = true; + //Thread.sleep(30000); + Thread.sleep(10000); + try { + im.evaluateSanity(); + } catch (Exception e) { + System.out.println("testStateCheck: After 10 sec sleep - evaluateSanity exception: " + e); + sanityPass = false; + } + assertFalse(sanityPass); // expect sanity test to fail + + // undo dependency groups, jmx test properties settings and failed counter threshold + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); + myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); + myProp.put(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, Integer.toString(IntegrityMonitorProperties.DEFAULT_FAILED_COUNTER_THRESHOLD)); + myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, Integer.toString(IntegrityMonitorProperties.DEFAULT_MONITOR_INTERVAL)); + IntegrityMonitor.updateProperties(myProp); + + et = em.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + System.out.println("\n\ntestStateCheck: Exit\n\n"); + } + + public void testGetAllForwardProgressEntity() throws Exception{ + System.out.println("\nIntegrityMonitorTest: Entering testGetAllForwardProgressEntity\n\n"); + logger.debug("\nIntegrityMonitorTest: Entering testGetAllForwardProgressEntity\n\n"); + + // parameters are passed via a properties file + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); + IntegrityMonitor.updateProperties(myProp); + + et = em.getTransaction(); + et.begin(); + + // Make sure we start with the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + + IntegrityMonitor.deleteInstance(); + IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); + + logger.debug("\nIntegrityMonitorTest: Creating ForwardProgressEntity entries\n\n"); + // Add a resources to put an entry in the forward progress table + ForwardProgressEntity fpe = new ForwardProgressEntity(); + ForwardProgressEntity fpe2 = new ForwardProgressEntity(); + ForwardProgressEntity fpe3 = new ForwardProgressEntity(); + fpe.setFpcCount(0); + fpe.setResourceName("siteA_pap2"); + fpe2.setFpcCount(0); + fpe2.setResourceName("siteB_pap1"); + fpe3.setFpcCount(0); + fpe3.setResourceName("siteB_pap2"); + et = em.getTransaction(); + et.begin(); + em.persist(fpe); + em.persist(fpe2); + em.persist(fpe3); + em.flush(); + et.commit(); + + logger.debug("\nIntegrityMonitorTest:testGetAllForwardProgressEntity Calling im.getAllForwardProgressEntity()\n\n"); + ArrayList fpeList = im.getAllForwardProgressEntity(); + + assertTrue(fpeList.size()==4); + + et = em.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + logger.debug("\nIntegrityMonitorTest: Exit testGetAllForwardProgressEntity\n\n"); + System.out.println("\n\ntestGetAllForwardProgressEntity: Exit\n\n"); + } + + public void testStateAudit() throws Exception{ + System.out.println("\nIntegrityMonitorTest: Entering testStateAudit\n\n"); + logger.debug("\nIntegrityMonitorTest: Entering testStateAudit\n\n"); + + // parameters are passed via a properties file + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); + myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "100"); + IntegrityMonitor.updateProperties(myProp); + + et = em.getTransaction(); + et.begin(); + + // Make sure we start with the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + + IntegrityMonitor.deleteInstance(); + IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); + + logger.debug("\nIntegrityMonitorTest: Creating ForwardProgressEntity entries\n\n"); + // Add resources to put an entry in the forward progress table + Date staleDate = new Date(0); + ForwardProgressEntity fpe1 = new ForwardProgressEntity(); + ForwardProgressEntity fpe2 = new ForwardProgressEntity(); + ForwardProgressEntity fpe3 = new ForwardProgressEntity(); + fpe1.setFpcCount(0); + fpe1.setResourceName("siteA_pap2"); + fpe2.setFpcCount(0); + fpe2.setResourceName("siteB_pap1"); + fpe3.setFpcCount(0); + fpe3.setResourceName("siteB_pap2"); + logger.debug("\nIntegrityMonitorTest: Creating StateManagementEntity entries\n\n"); + StateManagementEntity sme1 = new StateManagementEntity(); + StateManagementEntity sme2 = new StateManagementEntity(); + StateManagementEntity sme3= new StateManagementEntity(); + sme1.setResourceName("siteA_pap2"); + sme1.setAdminState(StateManagement.UNLOCKED); + sme1.setOpState(StateManagement.ENABLED); + sme1.setAvailStatus(StateManagement.NULL_VALUE); + sme1.setStandbyStatus(StateManagement.NULL_VALUE); + sme2.setResourceName("siteB_pap1"); + sme2.setAdminState(StateManagement.UNLOCKED); + sme2.setOpState(StateManagement.ENABLED); + sme2.setAvailStatus(StateManagement.NULL_VALUE); + sme2.setStandbyStatus(StateManagement.NULL_VALUE); + sme3.setResourceName("siteB_pap2"); + sme3.setAdminState(StateManagement.UNLOCKED); + sme3.setOpState(StateManagement.ENABLED); + sme3.setAvailStatus(StateManagement.NULL_VALUE); + sme3.setStandbyStatus(StateManagement.NULL_VALUE); + et = em.getTransaction(); + et.begin(); + em.persist(fpe1); + em.persist(fpe2); + em.persist(fpe3); + em.persist(sme1); + em.persist(sme2); + em.persist(sme3); + em.flush(); + et.commit(); + + Query updateQuery = em.createQuery("UPDATE ForwardProgressEntity f " + + "SET f.lastUpdated = :newDate " + + "WHERE f.resourceName=:resource"); + updateQuery.setParameter("newDate", staleDate, TemporalType.TIMESTAMP); + updateQuery.setParameter("resource", fpe1.getResourceName()); + + et = em.getTransaction(); + et.begin(); + updateQuery.executeUpdate(); + et.commit(); + + logger.debug("\nIntegrityMonitorTest:testStateAudit Calling im.getAllForwardProgressEntity()\n\n"); + ArrayList fpeList = im.getAllForwardProgressEntity(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:ForwardProgressEntity entries"); + for(ForwardProgressEntity myFpe : fpeList){ + logger.debug("\n ResourceName: " + myFpe.getResourceName() + + "\n LastUpdated: " + myFpe.getLastUpdated()); + } + logger.debug("\n\n"); + + logger.debug("\nIntegrityMonitorTest:testStateAudit getting list of StateManagementEntity entries\n\n"); + Query query = em.createQuery("SELECT s FROM StateManagementEntity s"); + List smeList = query.getResultList(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity entries"); + for(Object mySme : smeList){ + StateManagementEntity tmpSme = (StateManagementEntity) mySme; + em.refresh(tmpSme); + logger.debug("\n ResourceName: " + tmpSme.getResourceName() + + "\n AdminState: " + tmpSme.getAdminState() + + "\n OpState: " + tmpSme.getOpState() + + "\n AvailStatus: " + tmpSme.getAvailStatus() + + "\n StandbyStatus: " + tmpSme.getStandbyStatus() + ); + } + logger.debug("\n\n"); + + logger.debug("IntegrityMonitorTest:testStateAudit: sleeping 2 sec"); + Thread.sleep(3000); + logger.debug("IntegrityMonitorTest:testStateAudit: Awake!"); + + logger.debug("\nIntegrityMonitorTest:testStateAudit getting list of StateManagementEntity entries\n\n"); + smeList = query.getResultList(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity entries"); + for(Object mySme : smeList){ + StateManagementEntity tmpSme = (StateManagementEntity) mySme; + em.refresh(tmpSme); + logger.debug("\n ResourceName: " + tmpSme.getResourceName() + + "\n AdminState: " + tmpSme.getAdminState() + + "\n OpState: " + tmpSme.getOpState() + + "\n AvailStatus: " + tmpSme.getAvailStatus() + + "\n StandbyStatus: " + tmpSme.getStandbyStatus() + ); + } + logger.debug("\n\n"); + + em.refresh(sme1); + assertTrue(sme1.getOpState().equals(StateManagement.DISABLED)); + + + //Now lock this IM + StateManagement sm = im.getStateManager(); + sm.lock(); + + //Give it time to write the db + Thread.sleep(2000); + + //Put things back to their starting condition + et = em.getTransaction(); + et.begin(); + sme1.setOpState(StateManagement.ENABLED); + sme1.setAvailStatus(StateManagement.NULL_VALUE); + em.persist(sme1); + et.commit(); + + //Now it should not update sme1 + logger.debug("IntegrityMonitorTest:testStateAudit: 2nd sleeping 2 sec"); + Thread.sleep(2000); + logger.debug("IntegrityMonitorTest:testStateAudit: 2nd Awake!"); + + logger.debug("\nIntegrityMonitorTest:testStateAudit 2nd getting list of StateManagementEntity entries\n\n"); + smeList = query.getResultList(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity 2nd entries"); + for(Object mySme : smeList){ + StateManagementEntity tmpSme = (StateManagementEntity) mySme; + em.refresh(tmpSme); + logger.debug("\n 2nd ResourceName: " + tmpSme.getResourceName() + + "\n AdminState: " + tmpSme.getAdminState() + + "\n OpState: " + tmpSme.getOpState() + + "\n AvailStatus: " + tmpSme.getAvailStatus() + + "\n StandbyStatus: " + tmpSme.getStandbyStatus() + ); + } + logger.debug("\n\n"); + + em.refresh(sme1); + assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); + + //Now create a reason for this IM to be disabled. Add a bogus dependency + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "Bogus_Node"); + IntegrityMonitor.updateProperties(myProp); + + //Restart the IM + IntegrityMonitor.deleteInstance(); + im = IntegrityMonitor.getInstance(resourceName, myProp); + + //Give it time to initialize and check dependencies + logger.debug("IntegrityMonitorTest:testStateAudit: (restart) sleeping 10 sec"); + Thread.sleep(7000); + logger.debug("IntegrityMonitorTest:testStateAudit: (restart) Awake!"); + + //Now unlock this IM. Now it should be unlocked, but disabled due to dependency + sm.unlock(); + + //Now check its state + logger.debug("\nIntegrityMonitorTest:testStateAudit (restart) getting list of StateManagementEntity entries\n\n"); + smeList = query.getResultList(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart) entries"); + for(Object mySme : smeList){ + StateManagementEntity tmpSme = (StateManagementEntity) mySme; + em.refresh(tmpSme); + logger.debug("\n (restart) ResourceName: " + tmpSme.getResourceName() + + "\n AdminState: " + tmpSme.getAdminState() + + "\n OpState: " + tmpSme.getOpState() + + "\n AvailStatus: " + tmpSme.getAvailStatus() + + "\n StandbyStatus: " + tmpSme.getStandbyStatus() + ); + } + logger.debug("\n\n"); + + em.refresh(sme1); + assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); + + //Now lock this IM so it will not audit when it comes back up + sm.lock(); + + //Remove the bogus dependency and restart it + myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); + IntegrityMonitor.updateProperties(myProp); + + //Restart the IM + IntegrityMonitor.deleteInstance(); + im = IntegrityMonitor.getInstance(resourceName, myProp); + + //Give it time to initialize and check dependencies + logger.debug("IntegrityMonitorTest:testStateAudit: (restart2) sleeping 10 sec"); + Thread.sleep(7000); + logger.debug("IntegrityMonitorTest:testStateAudit: (restart2) Awake!"); + + //Now check its state + logger.debug("\nIntegrityMonitorTest:testStateAudit (restart2) getting list of StateManagementEntity entries\n\n"); + smeList = query.getResultList(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart2) entries"); + for(Object mySme : smeList){ + StateManagementEntity tmpSme = (StateManagementEntity) mySme; + em.refresh(tmpSme); + logger.debug("\n (restart2) ResourceName: " + tmpSme.getResourceName() + + "\n AdminState: " + tmpSme.getAdminState() + + "\n OpState: " + tmpSme.getOpState() + + "\n AvailStatus: " + tmpSme.getAvailStatus() + + "\n StandbyStatus: " + tmpSme.getStandbyStatus() + ); + } + logger.debug("\n\n"); + + em.refresh(sme1); + assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); + + //Make this IM coldstandby + sm.demote(); + //Give it time to write the DB + Thread.sleep(2000); + //unlock it + sm.unlock(); + //Give it time to write the DB + Thread.sleep(2000); + + //Now check its state + logger.debug("\nIntegrityMonitorTest:testStateAudit (restart3) getting list of StateManagementEntity entries\n\n"); + smeList = query.getResultList(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart3) entries"); + for(Object mySme : smeList){ + StateManagementEntity tmpSme = (StateManagementEntity) mySme; + em.refresh(tmpSme); + logger.debug("\n (restart3) ResourceName: " + tmpSme.getResourceName() + + "\n AdminState: " + tmpSme.getAdminState() + + "\n OpState: " + tmpSme.getOpState() + + "\n AvailStatus: " + tmpSme.getAvailStatus() + + "\n StandbyStatus: " + tmpSme.getStandbyStatus() + ); + } + logger.debug("\n\n"); + + //sme1 should not be changed because this IM is hotstandby and cannot change its state + em.refresh(sme1); + assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); + + //Now let's add sme2 to the mix + updateQuery = em.createQuery("UPDATE ForwardProgressEntity f " + + "SET f.lastUpdated = :newDate " + + "WHERE f.resourceName=:resource"); + updateQuery.setParameter("newDate", staleDate, TemporalType.TIMESTAMP); + updateQuery.setParameter("resource", fpe2.getResourceName()); + + et = em.getTransaction(); + et.begin(); + updateQuery.executeUpdate(); + et.commit(); + + //Finally, we want to promote this IM so it will disable sme1 + sm.promote(); + //Give it a chance to write the DB and run the audit + logger.debug("IntegrityMonitorTest:testStateAudit: (restart4) sleeping 2 sec"); + Thread.sleep(3000); + logger.debug("IntegrityMonitorTest:testStateAudit: (restart4) Awake!"); + + //Now check its state + logger.debug("\nIntegrityMonitorTest:testStateAudit (restart4) getting list of StateManagementEntity entries\n\n"); + smeList = query.getResultList(); + + logger.debug("\n\n"); + logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart4) entries"); + for(Object mySme : smeList){ + StateManagementEntity tmpSme = (StateManagementEntity) mySme; + em.refresh(tmpSme); + logger.debug("\n (restart4) ResourceName: " + tmpSme.getResourceName() + + "\n AdminState: " + tmpSme.getAdminState() + + "\n OpState: " + tmpSme.getOpState() + + "\n AvailStatus: " + tmpSme.getAvailStatus() + + "\n StandbyStatus: " + tmpSme.getStandbyStatus() + ); + } + logger.debug("\n\n"); + + em.refresh(sme1); + assertTrue(sme1.getOpState().equals(StateManagement.DISABLED)); + + em.refresh(sme2); + assertTrue(sme2.getOpState().equals(StateManagement.DISABLED)); + + et = em.getTransaction(); + et.begin(); + // Make sure we leave the DB clean + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + + em.flush(); + et.commit(); + + logger.debug("\nIntegrityMonitorTest: Exit testStateAudit\n\n"); + System.out.println("\n\ntestStateAudit: Exit\n\n"); + } +} diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementEntityTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementEntityTest.java new file mode 100644 index 00000000..ec5efc02 --- /dev/null +++ b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementEntityTest.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * Integrity Monitor + * ================================================================================ + * 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.im.test; + +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.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; + +import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.im.jpa.StateManagementEntity; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class StateManagementEntityTest { + private static Logger logger = FlexLogger.getLogger(StateManagementEntityTest.class); + + private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; + private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/smTest"; + //private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/xacml"; + private static final String DEFAULT_DB_USER = "sa"; + private static final String DEFAULT_DB_PWD = ""; + + /* + private static final String DEFAULT_DB_DRIVER = "org.mariadb.jdbc.Driver"; + private static final String DEFAULT_DB_URL = "jdbc:mariadb://localhost:3306/xacml"; + private static final String DEFAULT_DB_USER = "policy_user"; + private static final String DEFAULT_DB_PWD = "policy_user"; + */ + + private static final String DB_DRIVER = "javax.persistence.jdbc.driver"; + private static final String DB_URL = "javax.persistence.jdbc.url"; + private static final String DB_USER = "javax.persistence.jdbc.user"; + private static final String DB_PWD = "javax.persistence.jdbc.password"; + + @BeforeClass + public static void setUpClass() throws Exception { + + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Ignore + @Test + public void testJPA() throws Exception { + System.out.println("\n??? logger.infor StateManagementEntityTest: Entering\n\n"); + + Properties myProp = new Properties(); + myProp.put(DB_DRIVER, DEFAULT_DB_DRIVER); + myProp.put(DB_URL, DEFAULT_DB_URL); + myProp.put(DB_USER, DEFAULT_DB_USER); + myProp.put(DB_PWD, DEFAULT_DB_PWD); + + System.out.println("??? " + DB_DRIVER + "=" + DEFAULT_DB_DRIVER); + System.out.println("??? " + DB_URL + "=" + DEFAULT_DB_URL); + System.out.println("??? " + DB_USER + "=" + DEFAULT_DB_USER); + System.out.println("??? " + DB_PWD + "=" + DEFAULT_DB_PWD); + + //Create the data schema and entity manager factory + System.out.println("??? createEntityManagerFactory for schemaPU"); + EntityManagerFactory emf = Persistence.createEntityManagerFactory("schemaPU", myProp); + + // Create an entity manager to use the DB + System.out.println("??? createEntityManager"); + EntityManager em = emf.createEntityManager(); + System.out.println("??? getTransaction"); + EntityTransaction et = em.getTransaction(); + et.begin(); + // Make sure the DB is clean + System.out.println("??? clean StateManagementEntity"); + em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + + //Define the resourceName for the StateManagement constructor + String resourceName = "test_resource1"; + + // + System.out.println("Create StateManagementEntity, resourceName: " + resourceName); + System.out.println("??? instantiate StateManagementEntity object"); + StateManagementEntity sme = new StateManagementEntity(); + + System.out.println("??? setResourceName : " + resourceName); + sme.setResourceName(resourceName); + System.out.println("??? getResourceName : " + sme.getResourceName()); + + System.out.println("??? setAdminState : " + StateManagement.UNLOCKED); + sme.setAdminState(StateManagement.UNLOCKED); + System.out.println("??? getAdminState : " + sme.getAdminState()); + + System.out.println("??? setOpState : " + StateManagement.ENABLED); + sme.setOpState(StateManagement.ENABLED); + System.out.println("??? getOpState : " + sme.getOpState()); + + System.out.println("??? setAvailStatus : " + StateManagement.NULL_VALUE); + sme.setAvailStatus(StateManagement.NULL_VALUE); + System.out.println("??? getAvailStatus : " + sme.getAvailStatus()); + + System.out.println("??? setStandbyStatus: " + StateManagement.COLD_STANDBY); + sme.setStandbyStatus(StateManagement.COLD_STANDBY); + System.out.println("??? getStandbyStatus: " + sme.getStandbyStatus()); + + System.out.println("??? before persist"); + em.persist(sme); + System.out.println("??? after persist"); + + em.flush(); + System.out.println("??? after flush"); + + et.commit(); + System.out.println("??? after commit"); + + try { + Query query = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); + + query.setParameter("resource", resourceName); + + //Just test that we are retrieving the right object + @SuppressWarnings("rawtypes") + List resourceList = query.getResultList(); + if (!resourceList.isEmpty()) { + // exist + StateManagementEntity sme2 = (StateManagementEntity) resourceList.get(0); + System.out.println("??? -- Retrieve StateManagementEntity from database --" + + "\n\nsme.getResourceName() = " + sme.getResourceName() + + "\nsme2getResourceName() = " + sme2.getResourceName() + + "\n\nsme.getAdminState() = " + sme.getAdminState() + + "\nsme2.getAdminState() = " + sme2.getAdminState() + + "\n\nsme.getOpState() = " + sme.getOpState() + + "\nsme2.getOpState() = " + sme2.getOpState() + + "\n\nsme.getAvailStatus() = " + sme.getAvailStatus() + + "\nsme2.getAvailStatus() = " + sme.getAvailStatus() + + "\n\nsme.getStandbyStatus() = " + sme.getStandbyStatus() + + "\nsme2.getStandbyStatus() = " + sme2.getStandbyStatus()); + + + assert(sme2.getResourceName().equals(sme.getResourceName())); + assert(sme2.getAdminState().equals(sme.getAdminState())); + assert(sme2.getOpState().equals(sme.getOpState())); + assert(sme2.getAvailStatus().equals(sme.getAvailStatus())); + assert(sme2.getStandbyStatus().equals(sme.getStandbyStatus())); + System.out.println("--"); + } else { + System.out.println("Record not found, resourceName: " + resourceName); + } + } catch(Exception ex) { + logger.error("Exception on select query: " + ex.toString()); + } + + em.close(); + System.out.println("\n??? after close"); + System.out.println("\n\nJpaTest: Exit\n\n"); + } +} diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementTest.java new file mode 100644 index 00000000..98ee0645 --- /dev/null +++ b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateManagementTest.java @@ -0,0 +1,321 @@ +/*- + * ============LICENSE_START======================================================= + * Integrity Monitor + * ================================================================================ + * 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.im.test; + +import java.util.Properties; +import javax.persistence.EntityManagerFactory; +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.im.StateManagement; +import org.onap.policy.common.im.StandbyStatusException; +import org.onap.policy.common.im.StateChangeNotifier; +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. + */ +public class StateManagementTest { + private static Logger logger = FlexLogger.getLogger(StateManagementTest.class); + + private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; + private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/smTest"; + private static final String DEFAULT_DB_USER = "sa"; + private static final String DEFAULT_DB_PWD = ""; + + private static final String DB_DRIVER = "javax.persistence.jdbc.driver"; + private static final String DB_URL = "javax.persistence.jdbc.url"; + private static final String DB_USER = "javax.persistence.jdbc.user"; + private static final String DB_PWD = "javax.persistence.jdbc.password"; + // + + @BeforeClass + public static void setUpClass() throws Exception { + + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Ignore + @Test + public void testJPA() throws Exception { + logger.info("\n\nlogger.infor StateManagementTest: Entering\n\n"); + String resourceName = "test_resource1"; + boolean standbyExceptionThrown = false; + + //These parameters are in a properties file + EntityManagerFactory emf = null; + try { + Properties myProp = new Properties(); + myProp.put(DB_DRIVER, DEFAULT_DB_DRIVER); + myProp.put(DB_URL, DEFAULT_DB_URL); + myProp.put(DB_USER, DEFAULT_DB_USER); + myProp.put(DB_PWD, DEFAULT_DB_PWD); + + //Create the data schema and entity manager factory + emf = Persistence.createEntityManagerFactory("schemaPU", myProp); + + StateManagement sm = new StateManagement(emf, resourceName); + System.out.println("\n\ntest lock()"); + displayState(resourceName, sm); + logger.info("\n??? test lock()"); + logger.info(resourceName + " before adminState = " + sm.getAdminState()); + logger.info(resourceName + " before opState = " + sm.getOpState()); + logger.info(resourceName + " before availStatus = " + sm.getAvailStatus()); + logger.info(resourceName + " before standbyStatus= " + sm.getStandbyStatus()); + sm.lock(); + System.out.println("\n\nafter lock()"); + displayState(resourceName, sm); + logger.info(resourceName + " after adminState = " + sm.getAdminState()); + logger.info(resourceName + " after opState = " + sm.getOpState()); + logger.info(resourceName + " after availStatus = " + sm.getAvailStatus()); + logger.info(resourceName + " after standbyStatus= " + sm.getStandbyStatus()); + + logger.info("\n??? test unlock()"); + sm.unlock(); + System.out.println("\n\nafter unlock()"); + displayState(resourceName, sm); + logger.info(resourceName + " adminState = " + sm.getAdminState()); + logger.info(resourceName + " opState = " + sm.getOpState()); + logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); + logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); + + logger.info("\n??? test enableNotFailed()"); + sm.enableNotFailed(); + System.out.println("\n\nafter enableNotFailed()"); + displayState(resourceName, sm); + logger.info(resourceName + " adminState = " + sm.getAdminState()); + logger.info(resourceName + " opState = " + sm.getOpState()); + logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); + logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); + + logger.info("\n??? test disableFailed()"); + sm.disableFailed(); + System.out.println("\n\nafter disableFailed()"); + displayState(resourceName, sm); + logger.info(resourceName + " adminState = " + sm.getAdminState()); + logger.info(resourceName + " opState = " + sm.getOpState()); + logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); + logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); + + // P4 If promote() is called while either the opState is disabled or the adminState is locked, + // the standbystatus shall transition to coldstandby and a StandbyStatusException shall be thrown + logger.info("\n??? promote() test case P4"); + try { + sm.disableFailed(); + sm.lock(); + System.out.println("\n\nafter lock() and disableFailed"); + displayState(resourceName, sm); + logger.info(resourceName + " adminState = " + sm.getAdminState()); + logger.info(resourceName + " opState = " + sm.getOpState()); + logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); + sm.promote(); + System.out.println("\n\nafter promote"); + displayState(resourceName, sm); + } catch(StandbyStatusException ex) { + standbyExceptionThrown = true; + logger.info("StandbyStatusException thrown and catched"); + } catch(Exception ex) { + logger.info("??? Exception: " + ex.toString()); + } + assert(standbyExceptionThrown); + assert(sm.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); + standbyExceptionThrown = false; + + // P3 If promote() is called while standbyStatus is coldstandby, the state shall not transition + // and a StandbyStatusException shall be thrown + logger.info("\n??? promote() test case P3"); + try { + logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); + sm.promote(); + } catch(StandbyStatusException ex) { + standbyExceptionThrown = true; + logger.info("StandbyStatusException thrown and catched"); + } catch(Exception ex) { + logger.info("??? Exception: " + ex.toString()); + } + assert(standbyExceptionThrown); + assert(sm.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); + System.out.println("\n\nP3 after promote()"); + displayState(resourceName, sm); + standbyExceptionThrown = false; + + // P2 If promote() is called while the standbyStatus is null and the opState is enabled and adminState is unlocked, + // the state shall transition to providingservice + logger.info("\n??? promote() test case P2"); + resourceName = "test_resource2"; + StateManagement sm2 = new StateManagement(emf, resourceName); + sm2.enableNotFailed(); + sm2.unlock(); + System.out.println("\n\nafter sm2.enableNotFailed() and sm2.unlock()"); + displayState(resourceName, sm2); + logger.info(resourceName + " adminState = " + sm2.getAdminState()); + logger.info(resourceName + " opState = " + sm2.getOpState()); + logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); + sm2.promote(); + System.out.println("\n\nP2 after sm2.promote"); + displayState(resourceName, sm2); + assert(sm2.getAdminState().equals(StateManagement.UNLOCKED)); + assert(sm2.getOpState().equals(StateManagement.ENABLED)); + assert(sm2.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + // P5 If promote() is called while standbyStatus is providingservice, no action is taken + logger.info("\n??? promote() test case P5"); + logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); + sm2.promote(); + System.out.println("\n\nP5 after sm2.promote()"); + displayState(resourceName, sm2); + assert(sm2.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + // D1 If demote() is called while standbyStatus is providingservice, the state shall transition to hotstandby + logger.info("\n??? demote() test case D1"); + logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); + sm2.demote(); + System.out.println("\n\nD1 after sm2.demote()"); + displayState(resourceName, sm2); + assert(sm2.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); + + // D4 If demote() is called while standbyStatus is hotstandby, no action is taken + logger.info("\n??? demote() test case D4"); + logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); + sm2.demote(); + System.out.println("\n\nD4 after sm2.demote()"); + displayState(resourceName, sm2); + assert(sm2.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); + + // D3 If demote() is called while standbyStatus is null and adminState is locked or opState is disabled, + // the state shall transition to coldstandby + logger.info("\n??? demote() test case D3"); + resourceName = "test_resource3"; + StateManagement sm3 = new StateManagement(emf, resourceName); + sm3.lock(); + sm3.disableFailed(); + System.out.println("\n\nD3 after sm3.lock() and sm3.disableFailed()"); + displayState(resourceName, sm3); + logger.info(resourceName + " adminState = " + sm3.getAdminState()); + logger.info(resourceName + " opState = " + sm3.getOpState()); + logger.info(resourceName + " standbyStatus= " + sm3.getStandbyStatus()); + sm3.demote(); + System.out.println("\n\nD3 after sm3.demote()"); + displayState(resourceName, sm3); + assert(sm3.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); + + // D5 If demote() is called while standbyStatus is coldstandby, no action is taken + logger.info("\n??? demote() test case D5"); + logger.info(resourceName + " standbyStatus= " + sm3.getStandbyStatus()); + sm3.demote(); + System.out.println("\n\nD5 after sm3.demote()"); + displayState(resourceName, sm3); + assert(sm3.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); + + // D2 If demote() is called while standbyStatus is null and adminState is unlocked and opState is enabled, + // the state shall transition to hotstandby + logger.info("\n??? demote() test case D2"); + resourceName = "test_resource4"; + StateManagement sm4 = new StateManagement(emf, resourceName); + sm4.unlock(); + sm4.enableNotFailed(); + System.out.println("\n\nD2 after sm4.unlock() and sm4.enableNotFailed()"); + displayState(resourceName, sm4); + logger.info(resourceName + " adminState = " + sm4.getAdminState()); + logger.info(resourceName + " opState = " + sm4.getOpState()); + logger.info(resourceName + " standbyStatus= " + sm4.getStandbyStatus()); + sm4.demote(); + assert(sm4.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); + + // P1 If promote() is called while standbyStatus is hotstandby, the state shall transition to providingservice. + logger.info("\n??? promote() test case P1"); + logger.info(resourceName + " standbyStatus= " + sm4.getStandbyStatus()); + sm4.promote(); + System.out.println("\n\nP1 after sm4.promote()"); + displayState(resourceName, sm4); + assert(sm4.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + // State change notification + logger.info("\n??? State change notification test case 1 - lock()"); + StateChangeNotifier stateChangeNotifier = new StateChangeNotifier(); + sm.addObserver(stateChangeNotifier); + sm.lock(); + + logger.info("\n??? State change notification test case 2 - unlock()"); + sm.unlock(); + + logger.info("\n??? State change notification test case 3 - enabled()"); + sm.enableNotFailed(); + + logger.info("\n??? State change notification test case 4 - disableFailed()"); + sm.disableFailed(); + + logger.info("\n??? State change notification test case 5 - demote()"); + sm.demote(); + + logger.info("\n??? State change notification test case 6 - promote()"); + try { + sm.promote(); + } catch(Exception ex) { + logger.info("Exception from promote(): " + ex.toString()); + } + + if (emf.isOpen()) { + emf.close(); + } + } catch(Exception ex) { + logger.error("Exception: " + ex.toString()); + } finally { + if (emf.isOpen()) { + emf.close(); + } + } + + logger.info("\n\nStateManagementTest: Exit\n\n"); + } + + private void displayState(String resourceName, StateManagement sm) + { + System.out.println("\nAdminState = " + sm.getAdminState() + + "\nOpState() = " + sm.getOpState() + + "\nAvailStatus = " + sm.getAvailStatus() + + "\nStandbyStatus = " + sm.getStandbyStatus() + + "\n"); + logger.info(resourceName + " adminState = " + sm.getAdminState()); + logger.info(resourceName + " opState = " + sm.getOpState()); + logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); + logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); + } +} + diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateTransitionTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateTransitionTest.java new file mode 100644 index 00000000..80e393ee --- /dev/null +++ b/integrity-monitor/src/test/java/org/onap/policy/common/im/test/StateTransitionTest.java @@ -0,0 +1,2175 @@ +/*- + * ============LICENSE_START======================================================= + * Integrity Monitor + * ================================================================================ + * 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.im.test; + +import java.util.Properties; +import javax.persistence.EntityManagerFactory; +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.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; + +import org.onap.policy.common.im.StateTransition; +import org.onap.policy.common.im.StateElement; +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. + */ +public class StateTransitionTest { + private static Logger logger = FlexLogger.getLogger(StateTransitionTest.class); + + private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; + private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/smTest"; + private static final String DEFAULT_DB_USER = "sa"; + private static final String DEFAULT_DB_PWD = ""; + + private static final String DB_DRIVER = "javax.persistence.jdbc.driver"; + private static final String DB_URL = "javax.persistence.jdbc.url"; + private static final String DB_USER = "javax.persistence.jdbc.user"; + private static final String DB_PWD = "javax.persistence.jdbc.password"; + // + + @BeforeClass + public static void setUpClass() throws Exception { + + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Ignore + @Test + public void testJPA() throws Exception { + logger.info("\n\nlogger.infor StateTransitionTest: Entering\n\n"); + //These parameters are in a properties file + EntityManagerFactory emf = null; + try { + Properties myProp = new Properties(); + myProp.put(DB_DRIVER, DEFAULT_DB_DRIVER); + myProp.put(DB_URL, DEFAULT_DB_URL); + myProp.put(DB_USER, DEFAULT_DB_USER); + myProp.put(DB_PWD, DEFAULT_DB_PWD); + + logger.info("??? create a new StateTransition"); + StateTransition st = new StateTransition(); + + StateElement se = null; + try { + // bad test case + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "lock"); + // + logger.info("??? StateTransition testcase 1"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "lock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 2"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 3"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 4"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 5"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 6"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 7"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 8"); + se = st.getEndingState("unlocked", "enabled", "null", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 9"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 10"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 11"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 12"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 13"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 14"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 15"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 16"); + se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 17"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 18"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 19"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 20"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 21"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 22"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 23"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 24"); + se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 25"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 26"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 27"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 28"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 29"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 30"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 31"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 32"); + se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 33"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 34"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 35"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 36"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 37"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 38"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 39"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 40"); + se = st.getEndingState("unlocked", "enabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 41"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 42"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 43"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 44"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 45"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 46"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 47"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 48"); + se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 49"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 50"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 51"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 52"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 53"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 54"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 55"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 56"); + se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 57"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 58"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 59"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 60"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 61"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 62"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 63"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 64"); + se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 65"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 66"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 67"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 68"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 69"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 70"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 71"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 72"); + se = st.getEndingState("unlocked", "enabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 73"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 74"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 75"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 76"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 77"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 78"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 79"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 80"); + se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 81"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 82"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 83"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 84"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 85"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 86"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 87"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 88"); + se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 89"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 90"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 91"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 92"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 93"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 94"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 95"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 96"); + se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 97"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 98"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 99"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 100"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 101"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 102"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 103"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 104"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 105"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 106"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 107"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 108"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 109"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 110"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 111"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 112"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 113"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 114"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 115"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 116"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 117"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 118"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 119"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 120"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 121"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 122"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 123"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 124"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 125"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 126"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 127"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 128"); + se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 129"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 130"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 131"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 132"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 133"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 134"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 135"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 136"); + se = st.getEndingState("unlocked", "disabled", "null", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 137"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 138"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 139"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 140"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 141"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 142"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 143"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 144"); + se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 145"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 146"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 147"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 148"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 149"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 150"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 151"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 152"); + se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 153"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 154"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 155"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 156"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 157"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 158"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 159"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 160"); + se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 161"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 162"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 163"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 164"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 165"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 166"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 167"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 168"); + se = st.getEndingState("unlocked", "disabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 169"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 170"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 171"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 172"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 173"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 174"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 175"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 176"); + se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 177"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 178"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 179"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 180"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 181"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 182"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 183"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 184"); + se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 185"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 186"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 187"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 188"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 189"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 190"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 191"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 192"); + se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 193"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 194"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 195"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 196"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 197"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 198"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 199"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 200"); + se = st.getEndingState("unlocked", "disabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 201"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 202"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 203"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 204"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 205"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 206"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 207"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 208"); + se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 209"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 210"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 211"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 212"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 213"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 214"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 215"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 216"); + se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 217"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 218"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 219"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 220"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 221"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 222"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 223"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 224"); + se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 225"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 226"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 227"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 228"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 229"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 230"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 231"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 232"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 233"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 234"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 235"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 236"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 237"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 238"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 239"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 240"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 241"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 242"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 243"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 244"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 245"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 246"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 247"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 248"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 249"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 250"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 251"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 252"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 253"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 254"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 255"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 256"); + se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 257"); + se = st.getEndingState("locked", "enabled", "null", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 258"); + se = st.getEndingState("locked", "enabled", "null", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 259"); + se = st.getEndingState("locked", "enabled", "null", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 260"); + se = st.getEndingState("locked", "enabled", "null", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 261"); + se = st.getEndingState("locked", "enabled", "null", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 262"); + se = st.getEndingState("locked", "enabled", "null", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 263"); + se = st.getEndingState("locked", "enabled", "null", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 264"); + se = st.getEndingState("locked", "enabled", "null", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 265"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 266"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 267"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 268"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 269"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 270"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 271"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 272"); + se = st.getEndingState("locked", "enabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 273"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 274"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 275"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 276"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 277"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 278"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 279"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 280"); + se = st.getEndingState("locked", "enabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 281"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 282"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 283"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 284"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 285"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 286"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 287"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 288"); + se = st.getEndingState("locked", "enabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 289"); + se = st.getEndingState("locked", "enabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 290"); + se = st.getEndingState("locked", "enabled", "failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 291"); + se = st.getEndingState("locked", "enabled", "failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 292"); + se = st.getEndingState("locked", "enabled", "failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 293"); + se = st.getEndingState("locked", "enabled", "failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 294"); + se = st.getEndingState("locked", "enabled", "failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 295"); + se = st.getEndingState("locked", "enabled", "failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 296"); + se = st.getEndingState("locked", "enabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 297"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 298"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 299"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 300"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 301"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 302"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 303"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 304"); + se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 305"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 306"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 307"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 308"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 309"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 310"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 311"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 312"); + se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 313"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 314"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 315"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 316"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 317"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 318"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 319"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 320"); + se = st.getEndingState("locked", "enabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 321"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 322"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 323"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 324"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 325"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 326"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 327"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 328"); + se = st.getEndingState("locked", "enabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 329"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 330"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 331"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 332"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 333"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 334"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 335"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 336"); + se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 337"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 338"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 339"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 340"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 341"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 342"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 343"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 344"); + se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 345"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 346"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 347"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 348"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 349"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 350"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 351"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 352"); + se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 353"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 354"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 355"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 356"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 357"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 358"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 359"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 360"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 361"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 362"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 363"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 364"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 365"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 366"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 367"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 368"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 369"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 370"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 371"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 372"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 373"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 374"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 375"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 376"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 377"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 378"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 379"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 380"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 381"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 382"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 383"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 384"); + se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 385"); + se = st.getEndingState("locked", "disabled", "null", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 386"); + se = st.getEndingState("locked", "disabled", "null", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 387"); + se = st.getEndingState("locked", "disabled", "null", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 388"); + se = st.getEndingState("locked", "disabled", "null", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 389"); + se = st.getEndingState("locked", "disabled", "null", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 390"); + se = st.getEndingState("locked", "disabled", "null", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 391"); + se = st.getEndingState("locked", "disabled", "null", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 392"); + se = st.getEndingState("locked", "disabled", "null", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 393"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 394"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 395"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 396"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 397"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 398"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 399"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 400"); + se = st.getEndingState("locked", "disabled", "null", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 401"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 402"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 403"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 404"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 405"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 406"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 407"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 408"); + se = st.getEndingState("locked", "disabled", "null", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 409"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 410"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 411"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 412"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 413"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 414"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 415"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 416"); + se = st.getEndingState("locked", "disabled", "null", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 417"); + se = st.getEndingState("locked", "disabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 418"); + se = st.getEndingState("locked", "disabled", "failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 419"); + se = st.getEndingState("locked", "disabled", "failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 420"); + se = st.getEndingState("locked", "disabled", "failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 421"); + se = st.getEndingState("locked", "disabled", "failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 422"); + se = st.getEndingState("locked", "disabled", "failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 423"); + se = st.getEndingState("locked", "disabled", "failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 424"); + se = st.getEndingState("locked", "disabled", "failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 425"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 426"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 427"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 428"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 429"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 430"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 431"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 432"); + se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 433"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 434"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 435"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 436"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 437"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 438"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 439"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 440"); + se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 441"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 442"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 443"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 444"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 445"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 446"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 447"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 448"); + se = st.getEndingState("locked", "disabled", "failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 449"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 450"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 451"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 452"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 453"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 454"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 455"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 456"); + se = st.getEndingState("locked", "disabled", "dependency", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 457"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 458"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 459"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 460"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 461"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 462"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 463"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 464"); + se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 465"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 466"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 467"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 468"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 469"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 470"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 471"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 472"); + se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 473"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 474"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 475"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 476"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 477"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 478"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 479"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 480"); + se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 481"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 482"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 483"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 484"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 485"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 486"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 487"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 488"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 489"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 490"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 491"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 492"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 493"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 494"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 495"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 496"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 497"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 498"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 499"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 500"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 501"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 502"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 503"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 504"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 505"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 506"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "unlock"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 507"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "disableFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 508"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "enableNotFailed"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 509"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "disableDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 510"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "enableNoDependency"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 511"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "promote"); + if (se != null) displayEndingState(se); + + logger.info("??? StateTransition testcase 512"); + se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "demote"); + if (se != null) displayEndingState(se); + + } catch (Exception ex) { + logger.error("EndingState NOT found"); + throw new Exception("EndingState NOT found. " + ex); + } + + //if (emf.isOpen()) { + //emf.close(); + //} + } catch(Exception ex) { + logger.error("Exception: " + ex.toString()); + throw new Exception("Failure getting ending state. " + ex ); + } finally { + if (emf != null && emf.isOpen()) { + emf.close(); + } + } + + logger.info("\n\nStateTransitionTest: Exit\n\n"); + } + + private void displayEndingState(StateElement se) + { + String endingStandbyStatus = se.getEndingStandbyStatus(); + if (endingStandbyStatus != null) { + endingStandbyStatus.replace(".", ","); + } + logger.info("EndingAdminState = [" + se.getEndingAdminState() +"]"); + logger.info("EndingOpState = [" + se.getEndingOpState() +"]"); + logger.info("EndingAvailStatus = [" + se.getEndingAvailStatus() +"]"); + logger.info("EndingStandbyStatus= [" + endingStandbyStatus +"]"); + logger.info("Exception = [" + se.getException() +"]"); + } +} \ No newline at end of file diff --git a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/IntegrityMonitorTest.java b/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/IntegrityMonitorTest.java deleted file mode 100644 index 8e8720da..00000000 --- a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/IntegrityMonitorTest.java +++ /dev/null @@ -1,1232 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Monitor - * ================================================================================ - * 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.openecomp.policy.common.im.test; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -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 javax.persistence.TemporalType; - -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.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - - - -import org.openecomp.policy.common.im.IntegrityMonitor; -import org.openecomp.policy.common.im.IntegrityMonitorProperties; -import org.openecomp.policy.common.im.StateManagement; -import org.openecomp.policy.common.im.jpa.ForwardProgressEntity; -import org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity; -import org.openecomp.policy.common.im.jpa.StateManagementEntity; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.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. - */ -public class IntegrityMonitorTest { - private static Logger logger = FlexLogger.getLogger(IntegrityMonitorTest.class); - private static Properties myProp; - private static EntityManagerFactory emf; - private static EntityManager em; - private static EntityTransaction et; - private static String resourceName; - private static Properties systemProps; - - @BeforeClass - public static void setUpClass() throws Exception { - - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - IntegrityMonitor.isUnitTesting = true; - - myProp = new Properties(); - myProp.put(IntegrityMonitorProperties.DB_DRIVER, IntegrityMonitorProperties.DEFAULT_DB_DRIVER); - myProp.put(IntegrityMonitorProperties.DB_URL, IntegrityMonitorProperties.DEFAULT_DB_URL); - myProp.put(IntegrityMonitorProperties.DB_USER, IntegrityMonitorProperties.DEFAULT_DB_USER); - myProp.put(IntegrityMonitorProperties.DB_PWD, IntegrityMonitorProperties.DEFAULT_DB_PWD); - myProp.put(IntegrityMonitorProperties.SITE_NAME, "SiteA"); - myProp.put(IntegrityMonitorProperties.NODE_TYPE, "pap"); - - // set JMX remote port in system properties - systemProps = System.getProperties(); - systemProps.put("com.sun.management.jmxremote.port", "9797"); - - resourceName = "siteA.pap1"; - - //Create the data schema and entity manager factory - emf = Persistence.createEntityManagerFactory("schemaPU", myProp); - - // Create an entity manager to use the DB - em = emf.createEntityManager(); - - } - - - @After - public void tearDown() throws Exception { - // clear jmx remote port setting - systemProps.remove("com.sun.management.jmxremote.port"); - } - - /* - * The following runs all tests and controls the order of execution. If you allow - * the tests to execute individually, you cannot predict the order and some - * conflicts occur. - */ - @Ignore - @Test - public void runAllTests() throws Exception{ - //testSanityJmx(); - //testIM(); - //testSanityState(); - testRefreshStateAudit(); - //testStateCheck(); - //testGetAllForwardProgressEntity(); - //testStateAudit(); - } - - /* - * The following test verifies the following test cases: - * New Install - * New Install - Bad Dependency data - * Recovery from bad dependency data - * Lock - * Lock restart - * Unlock - * Unlock restart - */ - public void testSanityJmx() throws Exception { - System.out.println("\nIntegrityMonitorTest: Entering testSanityJmx\n\n"); - - String dependent = "group1_logparser"; - - // parameters are passed via a properties file - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, dependent); - myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "true"); - IntegrityMonitor.updateProperties(myProp); - - IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); - System.out.println("\n\ntestSanityJmx starting im state" - + "\nAdminState = " + im.getStateManager().getAdminState() - + "\nOpState() = " + im.getStateManager().getOpState() - + "\nAvailStatus = " + im.getStateManager().getAvailStatus() - + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() - + "\n"); - // add an entry to Resource registration table in the DB for the dependent resource - - - et = em.getTransaction(); - et.begin(); - Query rquery = em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn"); - rquery.setParameter("rn", dependent); - - @SuppressWarnings("rawtypes") - List rrList = rquery.getResultList(); - ResourceRegistrationEntity rrx = null; - if(rrList.isEmpty()){ - // register resource by adding entry to table in DB - System.out.println("Adding resource " + dependent + " to ResourceRegistration table"); - rrx = new ResourceRegistrationEntity(); - // set columns in entry - rrx.setResourceName(dependent); - rrx.setResourceUrl("service:jmx:somewhere:9999"); - rrx.setNodeType("logparser"); - rrx.setSite("siteA"); - } - em.persist(rrx); - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - Thread.sleep(15000); //sleep 15 sec so the FPManager has time to call evaluateSanty() - - boolean sanityPass = true; - try { - im.evaluateSanity(); - } catch (Exception e) { - System.out.println("evaluateSanity exception: " + e); - sanityPass = false; - } - assertFalse(sanityPass); // expect sanity test to fail - - // undo dependency groups and jmx test properties settings - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); - myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); - IntegrityMonitor.updateProperties(myProp); - - System.out.println("\ntestSantityJmx ending properties: " + myProp); - - //We know at this point that the IM is disable-dependency. We want to be - //sure it will recover from this condition since the properties were - //updated. - - - System.out.println("\n\ntestSanityJmx ending im state" - + "\nAdminState = " + im.getStateManager().getAdminState() - + "\nOpState() = " + im.getStateManager().getOpState() - + "\nAvailStatus = " + im.getStateManager().getAvailStatus() - + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() - + "\n"); - - //Destroy the instance - System.out.println("\ntestSanityJmx restarting the IntegrityMonitor"); - IntegrityMonitor.deleteInstance(); - //Create a new instance. It should recover from the disabled-dependency condition - im = IntegrityMonitor.getInstance(resourceName, myProp); - - System.out.println("\n\ntestSanityJmx state after creating new im" - + "\nAdminState = " + im.getStateManager().getAdminState() - + "\nOpState() = " + im.getStateManager().getOpState() - + "\nAvailStatus = " + im.getStateManager().getAvailStatus() - + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() - + "\n"); - - //Verify the state - assertEquals(im.getStateManager().getAdminState(), StateManagement.UNLOCKED); - assertEquals(im.getStateManager().getOpState(), StateManagement.ENABLED); - assertEquals(im.getStateManager().getAvailStatus(), StateManagement.NULL_VALUE); - assertEquals(im.getStateManager().getStandbyStatus(), StateManagement.NULL_VALUE); - - //Test state manager via the IntegrityMonitor - StateManagement sm = im.getStateManager(); - - // Verify lock state - sm.lock(); - System.out.println("\n\nsm.lock()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAdminState().equals(StateManagement.LOCKED)); - - //Verify lock persists across a restart - //Destroy the instance - System.out.println("\ntestSanityJmx restarting the IntegrityMonitor"); - IntegrityMonitor.deleteInstance(); - //Create a new instance. It should come up with the admin state locked - im = IntegrityMonitor.getInstance(resourceName, myProp); - sm = im.getStateManager(); - System.out.println("\n\ntestSanityJmx restart with AdminState=locked" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAdminState().equals(StateManagement.LOCKED)); - - // Verify unlock - sm.unlock(); - System.out.println("\n\ntestSanityJmx sm.unlock" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAdminState().equals(StateManagement.UNLOCKED)); - - // Verify unlock restart - //Destroy the instance - System.out.println("\ntestSanityJmx restarting the IntegrityMonitor"); - IntegrityMonitor.deleteInstance(); - //Create a new instance. It should come up with the admin state locked - im = IntegrityMonitor.getInstance(resourceName, myProp); - sm = im.getStateManager(); - System.out.println("\n\ntestSanityJmx restart with AdminState=unlocked" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAdminState().equals(StateManagement.UNLOCKED)); - - System.out.println("\n\ntestSanityJmx: Exit\n\n"); - } - - - public void testIM() throws Exception { - System.out.println("\nIntegrityMonitorTest: Entering testIM\n\n"); - - // parameters are passed via a properties file - - /* - * Create an IntegrityMonitor - * NOTE: This uses the database that was created above. So, this MUST follow the creation - * of the DB - */ - IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); - - System.out.println("\n\nim before sleep" - + "\nAdminState = " + im.getStateManager().getAdminState() - + "\nOpState() = " + im.getStateManager().getOpState() - + "\nAvailStatus = " + im.getStateManager().getAvailStatus() - + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() - + "\n"); - - // wait for test transactions to fire and increment fpc - Thread.sleep(20000); - - System.out.println("\n\nim after sleep" - + "\nAdminState = " + im.getStateManager().getAdminState() - + "\nOpState() = " + im.getStateManager().getOpState() - + "\nAvailStatus = " + im.getStateManager().getAvailStatus() - + "\nStandbyStatus = " + im.getStateManager().getStandbyStatus() - + "\n"); - - // test evaluate sanity - boolean sanityPass = true; - try { - im.evaluateSanity(); - } catch (Exception e) { - System.out.println("evaluateSanity exception: " + e); - sanityPass = false; - } - assertTrue(sanityPass); // expect sanity test to pass - - //Test startTransaction - should works since it is unlocked - boolean transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(transPass); - - //Test state manager via the IntegrityMonitor - StateManagement sm = im.getStateManager(); - - sm.lock(); - System.out.println("\n\nsm.lock()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAdminState().equals(StateManagement.LOCKED)); - - //test startTransaction. It should fail since it is locked - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(!transPass); //expect it to fail - - sm.unlock(); - System.out.println("\n\nsm.unlock()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAdminState().equals(StateManagement.UNLOCKED)); - - //test startTransaction. It should succeed - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(transPass); //expect it to succeed - - sm.disableDependency(); - System.out.println("\n\nsm.disableDependency()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getOpState().equals(StateManagement.DISABLED)); - assert(sm.getAvailStatus().equals(StateManagement.DEPENDENCY)); - - //test startTransaction. It should succeed since standby status is null and unlocked - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(transPass); //expect it to succeed - - sm.enableNoDependency(); - System.out.println("\n\nsm.enableNoDependency()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getOpState().equals(StateManagement.ENABLED)); - //test startTransaction. It should succeed since standby status is null and unlocked - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(transPass); //expect it to succeed - - - sm.disableFailed(); - System.out.println("\n\nsm.disableFailed()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getOpState().equals(StateManagement.DISABLED)); - assert(sm.getAvailStatus().equals(StateManagement.FAILED)); - //test startTransaction. It should succeed since standby status is null and unlocked - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(transPass); //expect it to succeed - - sm.enableNotFailed(); - System.out.println("\n\nsm.enabledNotFailed()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getOpState().equals(StateManagement.ENABLED)); - //test startTransaction. It should succeed since standby status is null and unlocked - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(transPass); //expect it to succeed - - sm.demote(); - System.out.println("\n\nsm.demote()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); - - //test startTransaction. It should fail since it is standby - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(!transPass); //expect it to fail - - sm.promote(); - System.out.println("\n\nsm.promote()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); - - //test startTransaction. It should succeed since it is providing service - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(transPass); //expect it to succeed - - - //Test the multi-valued availability status - sm.disableDependency(); - sm.disableFailed(); - System.out.println("\n\nsm.disableDependency(), sm.disableFailed" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAvailStatus().equals(StateManagement.DEPENDENCY_FAILED)); - - //Test startTransaction. Should fail since standby status is cold standby - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(!transPass); //expect it to fail - - sm.enableNoDependency(); - System.out.println("\n\nsm.enableNoDependency()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAvailStatus().equals(StateManagement.FAILED)); - //Test startTransaction. Should fail since standby status is cold standby - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(!transPass); //expect it to fail - - sm.disableDependency(); - sm.enableNotFailed(); - System.out.println("\n\nsm.disableDependency(),sm.enableNotFailed()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getAvailStatus().equals(StateManagement.DEPENDENCY)); - //Test startTransaction. Should fail since standby status is cold standby - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(!transPass); //expect it to fail - - sm.enableNoDependency(); - System.out.println("\n\nsm.enableNoDependency()" - + "\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - assert(sm.getOpState().equals(StateManagement.ENABLED)); - //test startTransaction. It should fail since standby status is hot standby - transPass = true; - try{ - im.startTransaction(); - } catch (Exception e){ - System.out.println("startTransaction exception: " + e); - transPass = false; - } - assertTrue(!transPass); //expect it to fail - - System.out.println("\n\ntestIM: Exit\n\n"); - } - - - public void testSanityState() throws Exception { - System.out.println("\nIntegrityMonitorTest: Entering testSanityState\n\n"); - - // parameters are passed via a properties file - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "group1_dep1,group1_dep2; group2_dep1"); - IntegrityMonitor.updateProperties(myProp); - - IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); - - // Add a group1 dependent resources to put an entry in the forward progress table - ForwardProgressEntity fpe = new ForwardProgressEntity(); - ForwardProgressEntity fpe2 = new ForwardProgressEntity(); - fpe.setFpcCount(0); - fpe.setResourceName("group1_dep1"); - fpe2.setFpcCount(0); - fpe2.setResourceName("group1_dep2"); - et = em.getTransaction(); - et.begin(); - em.persist(fpe); - em.persist(fpe2); - em.flush(); - et.commit(); - - - // Add a group2 dependent resource to the StateManagementEntity DB table and set its admin state to locked - // Expect sanity test to fail. - StateManagement stateManager = new StateManagement(emf, "group2_dep1"); - stateManager.lock(); - - new StateManagement(emf, "group1_dep1"); - new StateManagement(emf, "group1_dep2"); - - boolean sanityPass = true; - Thread.sleep(15000); - try { - im.evaluateSanity(); - } catch (Exception e) { - System.out.println("evaluateSanity exception: " + e); - sanityPass = false; - } - assertFalse(sanityPass); // expect sanity test to fail - - // undo dependency groups and jmx test properties settings - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); - myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); - IntegrityMonitor.updateProperties(myProp); - - et = em.getTransaction(); - - et.begin(); - // Make sure we leave the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - System.out.println("\n\ntestSanityState: Exit\n\n"); - } - - public void testRefreshStateAudit() throws Exception { - logger.debug("\nIntegrityMonitorTest: testRefreshStateAudit Enter\n\n"); - - // parameters are passed via a properties file - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); - myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); - myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "60000"); - IntegrityMonitor.updateProperties(myProp); - - et = em.getTransaction(); - et.begin(); - - // Make sure we leave the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - IntegrityMonitor.deleteInstance(); - - IntegrityMonitor.getInstance(resourceName, myProp); - - //the state here is unlocked, enabled, null, null - StateManagementEntity sme = null; - - Query query = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); - - query.setParameter("resource", resourceName); - - //Just test that we are retrieving the right object - @SuppressWarnings("rawtypes") - List resourceList = query.getResultList(); - if (!resourceList.isEmpty()) { - // exist - sme = (StateManagementEntity) resourceList.get(0); - em.refresh(sme); - - logger.debug("??? -- Retrieve StateManagementEntity from database --" - + "\nsme.getResourceName() = " + sme.getResourceName() - + "\nsme.getAdminState() = " + sme.getAdminState() - + "\nsme.getOpState() = " + sme.getOpState() - + "\nsme.getAvailStatus() = " + sme.getAvailStatus() - + "\nsme.getStandbyStatus() = " + sme.getStandbyStatus()); - - assertTrue(sme.getAdminState().equals(StateManagement.UNLOCKED)); - assertTrue(sme.getOpState().equals(StateManagement.ENABLED)); - assertTrue(sme.getAvailStatus().equals(StateManagement.NULL_VALUE)); - assertTrue(sme.getStandbyStatus().equals(StateManagement.NULL_VALUE)); - logger.debug("--"); - } else { - logger.debug("Record not found, resourceName: " + resourceName); - assertTrue(false); - } - - et = em.getTransaction(); - et.begin(); - - sme.setStandbyStatus(StateManagement.COLD_STANDBY); - em.persist(sme); - em.flush(); - et.commit(); - - Thread.sleep(65000); - - //The refreshStateAudit should run and change the state to unlocked,enabled,null,hotstandby - StateManagementEntity sme1 = null; - - Query query1 = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); - - query1.setParameter("resource", resourceName); - - //Just test that we are retrieving the right object - @SuppressWarnings("rawtypes") - List resourceList1 = query1.getResultList(); - if (!resourceList1.isEmpty()) { - // exist - sme1 = (StateManagementEntity) resourceList1.get(0); - em.refresh(sme1); - logger.debug("??? -- Retrieve StateManagementEntity from database --" - + "\nsme1.getResourceName() = " + sme1.getResourceName() - + "\nsme1.getAdminState() = " + sme1.getAdminState() - + "\nsme1.getOpState() = " + sme1.getOpState() - + "\nsme1.getAvailStatus() = " + sme1.getAvailStatus() - + "\nsme1.getStandbyStatus() = " + sme1.getStandbyStatus()); - - assertTrue(sme1.getAdminState().equals(StateManagement.UNLOCKED)); - assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); - assertTrue(sme1.getAvailStatus().equals(StateManagement.NULL_VALUE)); - assertTrue(sme1.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); - logger.debug("--"); - } else { - logger.debug("Record not found, resourceName: " + resourceName); - assertTrue(false); - } - - et = em.getTransaction(); - et.begin(); - - // Make sure we leave the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - IntegrityMonitor.deleteInstance(); - - logger.debug("\nIntegrityMonitorTest: testRefreshStateAudit Exit\n\n"); - } - - public void testStateCheck() throws Exception { - System.out.println("\nIntegrityMonitorTest: Entering testStateCheck\n\n"); - - // parameters are passed via a properties file - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "group1_dep1"); - myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); - myProp.put(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, "1"); - myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "10"); - IntegrityMonitor.updateProperties(myProp); - /* - * The default monitorInterval is 30 and the default failedCounterThreshold is 3 - * Since stateCheck() uses the faileCounterThreshold * monitorInterval to determine - * if an entry is stale, it will be stale after 30 seconds. - */ - - et = em.getTransaction(); - et.begin(); - - // Make sure we start with the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - IntegrityMonitor.deleteInstance(); - - IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); - - // Add a group1 dependent resources to put an entry in the forward progress table - // This sets lastUpdated to the current time - ForwardProgressEntity fpe = new ForwardProgressEntity(); - fpe.setFpcCount(0); - fpe.setResourceName("group1_dep1"); - et = em.getTransaction(); - et.begin(); - em.persist(fpe); - em.flush(); - et.commit(); - - new StateManagement(emf, "group1_dep1"); - - boolean sanityPass = true; - //Thread.sleep(15000); - Thread.sleep(5000); - try { - im.evaluateSanity(); - } catch (Exception e) { - System.out.println("testStateCheck: After 15 sec sleep - evaluateSanity exception: " + e); - sanityPass = false; - } - assertTrue(sanityPass); // expect sanity test to pass - - //now wait 30 seconds. The dependency entry should now be stale and the sanitry check should fail - - sanityPass = true; - //Thread.sleep(30000); - Thread.sleep(10000); - try { - im.evaluateSanity(); - } catch (Exception e) { - System.out.println("testStateCheck: After 10 sec sleep - evaluateSanity exception: " + e); - sanityPass = false; - } - assertFalse(sanityPass); // expect sanity test to fail - - // undo dependency groups, jmx test properties settings and failed counter threshold - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); - myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, "false"); - myProp.put(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, Integer.toString(IntegrityMonitorProperties.DEFAULT_FAILED_COUNTER_THRESHOLD)); - myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, Integer.toString(IntegrityMonitorProperties.DEFAULT_MONITOR_INTERVAL)); - IntegrityMonitor.updateProperties(myProp); - - et = em.getTransaction(); - - et.begin(); - // Make sure we leave the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - System.out.println("\n\ntestStateCheck: Exit\n\n"); - } - - public void testGetAllForwardProgressEntity() throws Exception{ - System.out.println("\nIntegrityMonitorTest: Entering testGetAllForwardProgressEntity\n\n"); - logger.debug("\nIntegrityMonitorTest: Entering testGetAllForwardProgressEntity\n\n"); - - // parameters are passed via a properties file - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); - IntegrityMonitor.updateProperties(myProp); - - et = em.getTransaction(); - et.begin(); - - // Make sure we start with the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - - IntegrityMonitor.deleteInstance(); - IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); - - logger.debug("\nIntegrityMonitorTest: Creating ForwardProgressEntity entries\n\n"); - // Add a resources to put an entry in the forward progress table - ForwardProgressEntity fpe = new ForwardProgressEntity(); - ForwardProgressEntity fpe2 = new ForwardProgressEntity(); - ForwardProgressEntity fpe3 = new ForwardProgressEntity(); - fpe.setFpcCount(0); - fpe.setResourceName("siteA_pap2"); - fpe2.setFpcCount(0); - fpe2.setResourceName("siteB_pap1"); - fpe3.setFpcCount(0); - fpe3.setResourceName("siteB_pap2"); - et = em.getTransaction(); - et.begin(); - em.persist(fpe); - em.persist(fpe2); - em.persist(fpe3); - em.flush(); - et.commit(); - - logger.debug("\nIntegrityMonitorTest:testGetAllForwardProgressEntity Calling im.getAllForwardProgressEntity()\n\n"); - ArrayList fpeList = im.getAllForwardProgressEntity(); - - assertTrue(fpeList.size()==4); - - et = em.getTransaction(); - - et.begin(); - // Make sure we leave the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - logger.debug("\nIntegrityMonitorTest: Exit testGetAllForwardProgressEntity\n\n"); - System.out.println("\n\ntestGetAllForwardProgressEntity: Exit\n\n"); - } - - public void testStateAudit() throws Exception{ - System.out.println("\nIntegrityMonitorTest: Entering testStateAudit\n\n"); - logger.debug("\nIntegrityMonitorTest: Entering testStateAudit\n\n"); - - // parameters are passed via a properties file - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); - myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "100"); - IntegrityMonitor.updateProperties(myProp); - - et = em.getTransaction(); - et.begin(); - - // Make sure we start with the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - - IntegrityMonitor.deleteInstance(); - IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp); - - logger.debug("\nIntegrityMonitorTest: Creating ForwardProgressEntity entries\n\n"); - // Add resources to put an entry in the forward progress table - Date staleDate = new Date(0); - ForwardProgressEntity fpe1 = new ForwardProgressEntity(); - ForwardProgressEntity fpe2 = new ForwardProgressEntity(); - ForwardProgressEntity fpe3 = new ForwardProgressEntity(); - fpe1.setFpcCount(0); - fpe1.setResourceName("siteA_pap2"); - fpe2.setFpcCount(0); - fpe2.setResourceName("siteB_pap1"); - fpe3.setFpcCount(0); - fpe3.setResourceName("siteB_pap2"); - logger.debug("\nIntegrityMonitorTest: Creating StateManagementEntity entries\n\n"); - StateManagementEntity sme1 = new StateManagementEntity(); - StateManagementEntity sme2 = new StateManagementEntity(); - StateManagementEntity sme3= new StateManagementEntity(); - sme1.setResourceName("siteA_pap2"); - sme1.setAdminState(StateManagement.UNLOCKED); - sme1.setOpState(StateManagement.ENABLED); - sme1.setAvailStatus(StateManagement.NULL_VALUE); - sme1.setStandbyStatus(StateManagement.NULL_VALUE); - sme2.setResourceName("siteB_pap1"); - sme2.setAdminState(StateManagement.UNLOCKED); - sme2.setOpState(StateManagement.ENABLED); - sme2.setAvailStatus(StateManagement.NULL_VALUE); - sme2.setStandbyStatus(StateManagement.NULL_VALUE); - sme3.setResourceName("siteB_pap2"); - sme3.setAdminState(StateManagement.UNLOCKED); - sme3.setOpState(StateManagement.ENABLED); - sme3.setAvailStatus(StateManagement.NULL_VALUE); - sme3.setStandbyStatus(StateManagement.NULL_VALUE); - et = em.getTransaction(); - et.begin(); - em.persist(fpe1); - em.persist(fpe2); - em.persist(fpe3); - em.persist(sme1); - em.persist(sme2); - em.persist(sme3); - em.flush(); - et.commit(); - - Query updateQuery = em.createQuery("UPDATE ForwardProgressEntity f " - + "SET f.lastUpdated = :newDate " - + "WHERE f.resourceName=:resource"); - updateQuery.setParameter("newDate", staleDate, TemporalType.TIMESTAMP); - updateQuery.setParameter("resource", fpe1.getResourceName()); - - et = em.getTransaction(); - et.begin(); - updateQuery.executeUpdate(); - et.commit(); - - logger.debug("\nIntegrityMonitorTest:testStateAudit Calling im.getAllForwardProgressEntity()\n\n"); - ArrayList fpeList = im.getAllForwardProgressEntity(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:ForwardProgressEntity entries"); - for(ForwardProgressEntity myFpe : fpeList){ - logger.debug("\n ResourceName: " + myFpe.getResourceName() - + "\n LastUpdated: " + myFpe.getLastUpdated()); - } - logger.debug("\n\n"); - - logger.debug("\nIntegrityMonitorTest:testStateAudit getting list of StateManagementEntity entries\n\n"); - Query query = em.createQuery("SELECT s FROM StateManagementEntity s"); - List smeList = query.getResultList(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity entries"); - for(Object mySme : smeList){ - StateManagementEntity tmpSme = (StateManagementEntity) mySme; - em.refresh(tmpSme); - logger.debug("\n ResourceName: " + tmpSme.getResourceName() - + "\n AdminState: " + tmpSme.getAdminState() - + "\n OpState: " + tmpSme.getOpState() - + "\n AvailStatus: " + tmpSme.getAvailStatus() - + "\n StandbyStatus: " + tmpSme.getStandbyStatus() - ); - } - logger.debug("\n\n"); - - logger.debug("IntegrityMonitorTest:testStateAudit: sleeping 2 sec"); - Thread.sleep(3000); - logger.debug("IntegrityMonitorTest:testStateAudit: Awake!"); - - logger.debug("\nIntegrityMonitorTest:testStateAudit getting list of StateManagementEntity entries\n\n"); - smeList = query.getResultList(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity entries"); - for(Object mySme : smeList){ - StateManagementEntity tmpSme = (StateManagementEntity) mySme; - em.refresh(tmpSme); - logger.debug("\n ResourceName: " + tmpSme.getResourceName() - + "\n AdminState: " + tmpSme.getAdminState() - + "\n OpState: " + tmpSme.getOpState() - + "\n AvailStatus: " + tmpSme.getAvailStatus() - + "\n StandbyStatus: " + tmpSme.getStandbyStatus() - ); - } - logger.debug("\n\n"); - - em.refresh(sme1); - assertTrue(sme1.getOpState().equals(StateManagement.DISABLED)); - - - //Now lock this IM - StateManagement sm = im.getStateManager(); - sm.lock(); - - //Give it time to write the db - Thread.sleep(2000); - - //Put things back to their starting condition - et = em.getTransaction(); - et.begin(); - sme1.setOpState(StateManagement.ENABLED); - sme1.setAvailStatus(StateManagement.NULL_VALUE); - em.persist(sme1); - et.commit(); - - //Now it should not update sme1 - logger.debug("IntegrityMonitorTest:testStateAudit: 2nd sleeping 2 sec"); - Thread.sleep(2000); - logger.debug("IntegrityMonitorTest:testStateAudit: 2nd Awake!"); - - logger.debug("\nIntegrityMonitorTest:testStateAudit 2nd getting list of StateManagementEntity entries\n\n"); - smeList = query.getResultList(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity 2nd entries"); - for(Object mySme : smeList){ - StateManagementEntity tmpSme = (StateManagementEntity) mySme; - em.refresh(tmpSme); - logger.debug("\n 2nd ResourceName: " + tmpSme.getResourceName() - + "\n AdminState: " + tmpSme.getAdminState() - + "\n OpState: " + tmpSme.getOpState() - + "\n AvailStatus: " + tmpSme.getAvailStatus() - + "\n StandbyStatus: " + tmpSme.getStandbyStatus() - ); - } - logger.debug("\n\n"); - - em.refresh(sme1); - assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); - - //Now create a reason for this IM to be disabled. Add a bogus dependency - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "Bogus_Node"); - IntegrityMonitor.updateProperties(myProp); - - //Restart the IM - IntegrityMonitor.deleteInstance(); - im = IntegrityMonitor.getInstance(resourceName, myProp); - - //Give it time to initialize and check dependencies - logger.debug("IntegrityMonitorTest:testStateAudit: (restart) sleeping 10 sec"); - Thread.sleep(7000); - logger.debug("IntegrityMonitorTest:testStateAudit: (restart) Awake!"); - - //Now unlock this IM. Now it should be unlocked, but disabled due to dependency - sm.unlock(); - - //Now check its state - logger.debug("\nIntegrityMonitorTest:testStateAudit (restart) getting list of StateManagementEntity entries\n\n"); - smeList = query.getResultList(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart) entries"); - for(Object mySme : smeList){ - StateManagementEntity tmpSme = (StateManagementEntity) mySme; - em.refresh(tmpSme); - logger.debug("\n (restart) ResourceName: " + tmpSme.getResourceName() - + "\n AdminState: " + tmpSme.getAdminState() - + "\n OpState: " + tmpSme.getOpState() - + "\n AvailStatus: " + tmpSme.getAvailStatus() - + "\n StandbyStatus: " + tmpSme.getStandbyStatus() - ); - } - logger.debug("\n\n"); - - em.refresh(sme1); - assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); - - //Now lock this IM so it will not audit when it comes back up - sm.lock(); - - //Remove the bogus dependency and restart it - myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, ""); - IntegrityMonitor.updateProperties(myProp); - - //Restart the IM - IntegrityMonitor.deleteInstance(); - im = IntegrityMonitor.getInstance(resourceName, myProp); - - //Give it time to initialize and check dependencies - logger.debug("IntegrityMonitorTest:testStateAudit: (restart2) sleeping 10 sec"); - Thread.sleep(7000); - logger.debug("IntegrityMonitorTest:testStateAudit: (restart2) Awake!"); - - //Now check its state - logger.debug("\nIntegrityMonitorTest:testStateAudit (restart2) getting list of StateManagementEntity entries\n\n"); - smeList = query.getResultList(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart2) entries"); - for(Object mySme : smeList){ - StateManagementEntity tmpSme = (StateManagementEntity) mySme; - em.refresh(tmpSme); - logger.debug("\n (restart2) ResourceName: " + tmpSme.getResourceName() - + "\n AdminState: " + tmpSme.getAdminState() - + "\n OpState: " + tmpSme.getOpState() - + "\n AvailStatus: " + tmpSme.getAvailStatus() - + "\n StandbyStatus: " + tmpSme.getStandbyStatus() - ); - } - logger.debug("\n\n"); - - em.refresh(sme1); - assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); - - //Make this IM coldstandby - sm.demote(); - //Give it time to write the DB - Thread.sleep(2000); - //unlock it - sm.unlock(); - //Give it time to write the DB - Thread.sleep(2000); - - //Now check its state - logger.debug("\nIntegrityMonitorTest:testStateAudit (restart3) getting list of StateManagementEntity entries\n\n"); - smeList = query.getResultList(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart3) entries"); - for(Object mySme : smeList){ - StateManagementEntity tmpSme = (StateManagementEntity) mySme; - em.refresh(tmpSme); - logger.debug("\n (restart3) ResourceName: " + tmpSme.getResourceName() - + "\n AdminState: " + tmpSme.getAdminState() - + "\n OpState: " + tmpSme.getOpState() - + "\n AvailStatus: " + tmpSme.getAvailStatus() - + "\n StandbyStatus: " + tmpSme.getStandbyStatus() - ); - } - logger.debug("\n\n"); - - //sme1 should not be changed because this IM is hotstandby and cannot change its state - em.refresh(sme1); - assertTrue(sme1.getOpState().equals(StateManagement.ENABLED)); - - //Now let's add sme2 to the mix - updateQuery = em.createQuery("UPDATE ForwardProgressEntity f " - + "SET f.lastUpdated = :newDate " - + "WHERE f.resourceName=:resource"); - updateQuery.setParameter("newDate", staleDate, TemporalType.TIMESTAMP); - updateQuery.setParameter("resource", fpe2.getResourceName()); - - et = em.getTransaction(); - et.begin(); - updateQuery.executeUpdate(); - et.commit(); - - //Finally, we want to promote this IM so it will disable sme1 - sm.promote(); - //Give it a chance to write the DB and run the audit - logger.debug("IntegrityMonitorTest:testStateAudit: (restart4) sleeping 2 sec"); - Thread.sleep(3000); - logger.debug("IntegrityMonitorTest:testStateAudit: (restart4) Awake!"); - - //Now check its state - logger.debug("\nIntegrityMonitorTest:testStateAudit (restart4) getting list of StateManagementEntity entries\n\n"); - smeList = query.getResultList(); - - logger.debug("\n\n"); - logger.debug("IntegrityMonitorTest:testStateAudit:StateManagementEntity (restart4) entries"); - for(Object mySme : smeList){ - StateManagementEntity tmpSme = (StateManagementEntity) mySme; - em.refresh(tmpSme); - logger.debug("\n (restart4) ResourceName: " + tmpSme.getResourceName() - + "\n AdminState: " + tmpSme.getAdminState() - + "\n OpState: " + tmpSme.getOpState() - + "\n AvailStatus: " + tmpSme.getAvailStatus() - + "\n StandbyStatus: " + tmpSme.getStandbyStatus() - ); - } - logger.debug("\n\n"); - - em.refresh(sme1); - assertTrue(sme1.getOpState().equals(StateManagement.DISABLED)); - - em.refresh(sme2); - assertTrue(sme2.getOpState().equals(StateManagement.DISABLED)); - - et = em.getTransaction(); - et.begin(); - // Make sure we leave the DB clean - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - em.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - em.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - - em.flush(); - et.commit(); - - logger.debug("\nIntegrityMonitorTest: Exit testStateAudit\n\n"); - System.out.println("\n\ntestStateAudit: Exit\n\n"); - } -} diff --git a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementEntityTest.java b/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementEntityTest.java deleted file mode 100644 index 6116ef07..00000000 --- a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementEntityTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Monitor - * ================================================================================ - * 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.openecomp.policy.common.im.test; - -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.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - -import org.openecomp.policy.common.im.StateManagement; -import org.openecomp.policy.common.im.jpa.StateManagementEntity; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class StateManagementEntityTest { - private static Logger logger = FlexLogger.getLogger(StateManagementEntityTest.class); - - private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; - private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/smTest"; - //private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/xacml"; - private static final String DEFAULT_DB_USER = "sa"; - private static final String DEFAULT_DB_PWD = ""; - - /* - private static final String DEFAULT_DB_DRIVER = "org.mariadb.jdbc.Driver"; - private static final String DEFAULT_DB_URL = "jdbc:mariadb://localhost:3306/xacml"; - private static final String DEFAULT_DB_USER = "policy_user"; - private static final String DEFAULT_DB_PWD = "policy_user"; - */ - - private static final String DB_DRIVER = "javax.persistence.jdbc.driver"; - private static final String DB_URL = "javax.persistence.jdbc.url"; - private static final String DB_USER = "javax.persistence.jdbc.user"; - private static final String DB_PWD = "javax.persistence.jdbc.password"; - - @BeforeClass - public static void setUpClass() throws Exception { - - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Ignore - @Test - public void testJPA() throws Exception { - System.out.println("\n??? logger.infor StateManagementEntityTest: Entering\n\n"); - - Properties myProp = new Properties(); - myProp.put(DB_DRIVER, DEFAULT_DB_DRIVER); - myProp.put(DB_URL, DEFAULT_DB_URL); - myProp.put(DB_USER, DEFAULT_DB_USER); - myProp.put(DB_PWD, DEFAULT_DB_PWD); - - System.out.println("??? " + DB_DRIVER + "=" + DEFAULT_DB_DRIVER); - System.out.println("??? " + DB_URL + "=" + DEFAULT_DB_URL); - System.out.println("??? " + DB_USER + "=" + DEFAULT_DB_USER); - System.out.println("??? " + DB_PWD + "=" + DEFAULT_DB_PWD); - - //Create the data schema and entity manager factory - System.out.println("??? createEntityManagerFactory for schemaPU"); - EntityManagerFactory emf = Persistence.createEntityManagerFactory("schemaPU", myProp); - - // Create an entity manager to use the DB - System.out.println("??? createEntityManager"); - EntityManager em = emf.createEntityManager(); - System.out.println("??? getTransaction"); - EntityTransaction et = em.getTransaction(); - et.begin(); - // Make sure the DB is clean - System.out.println("??? clean StateManagementEntity"); - em.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - - //Define the resourceName for the StateManagement constructor - String resourceName = "test_resource1"; - - // - System.out.println("Create StateManagementEntity, resourceName: " + resourceName); - System.out.println("??? instantiate StateManagementEntity object"); - StateManagementEntity sme = new StateManagementEntity(); - - System.out.println("??? setResourceName : " + resourceName); - sme.setResourceName(resourceName); - System.out.println("??? getResourceName : " + sme.getResourceName()); - - System.out.println("??? setAdminState : " + StateManagement.UNLOCKED); - sme.setAdminState(StateManagement.UNLOCKED); - System.out.println("??? getAdminState : " + sme.getAdminState()); - - System.out.println("??? setOpState : " + StateManagement.ENABLED); - sme.setOpState(StateManagement.ENABLED); - System.out.println("??? getOpState : " + sme.getOpState()); - - System.out.println("??? setAvailStatus : " + StateManagement.NULL_VALUE); - sme.setAvailStatus(StateManagement.NULL_VALUE); - System.out.println("??? getAvailStatus : " + sme.getAvailStatus()); - - System.out.println("??? setStandbyStatus: " + StateManagement.COLD_STANDBY); - sme.setStandbyStatus(StateManagement.COLD_STANDBY); - System.out.println("??? getStandbyStatus: " + sme.getStandbyStatus()); - - System.out.println("??? before persist"); - em.persist(sme); - System.out.println("??? after persist"); - - em.flush(); - System.out.println("??? after flush"); - - et.commit(); - System.out.println("??? after commit"); - - try { - Query query = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource"); - - query.setParameter("resource", resourceName); - - //Just test that we are retrieving the right object - @SuppressWarnings("rawtypes") - List resourceList = query.getResultList(); - if (!resourceList.isEmpty()) { - // exist - StateManagementEntity sme2 = (StateManagementEntity) resourceList.get(0); - System.out.println("??? -- Retrieve StateManagementEntity from database --" - + "\n\nsme.getResourceName() = " + sme.getResourceName() - + "\nsme2getResourceName() = " + sme2.getResourceName() - + "\n\nsme.getAdminState() = " + sme.getAdminState() - + "\nsme2.getAdminState() = " + sme2.getAdminState() - + "\n\nsme.getOpState() = " + sme.getOpState() - + "\nsme2.getOpState() = " + sme2.getOpState() - + "\n\nsme.getAvailStatus() = " + sme.getAvailStatus() - + "\nsme2.getAvailStatus() = " + sme.getAvailStatus() - + "\n\nsme.getStandbyStatus() = " + sme.getStandbyStatus() - + "\nsme2.getStandbyStatus() = " + sme2.getStandbyStatus()); - - - assert(sme2.getResourceName().equals(sme.getResourceName())); - assert(sme2.getAdminState().equals(sme.getAdminState())); - assert(sme2.getOpState().equals(sme.getOpState())); - assert(sme2.getAvailStatus().equals(sme.getAvailStatus())); - assert(sme2.getStandbyStatus().equals(sme.getStandbyStatus())); - System.out.println("--"); - } else { - System.out.println("Record not found, resourceName: " + resourceName); - } - } catch(Exception ex) { - logger.error("Exception on select query: " + ex.toString()); - } - - em.close(); - System.out.println("\n??? after close"); - System.out.println("\n\nJpaTest: Exit\n\n"); - } -} diff --git a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementTest.java b/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementTest.java deleted file mode 100644 index 92fc225c..00000000 --- a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateManagementTest.java +++ /dev/null @@ -1,321 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Monitor - * ================================================================================ - * 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.openecomp.policy.common.im.test; - -import java.util.Properties; -import javax.persistence.EntityManagerFactory; -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.openecomp.policy.common.im.StateManagement; -import org.openecomp.policy.common.im.StandbyStatusException; -import org.openecomp.policy.common.im.StateChangeNotifier; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.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. - */ -public class StateManagementTest { - private static Logger logger = FlexLogger.getLogger(StateManagementTest.class); - - private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; - private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/smTest"; - private static final String DEFAULT_DB_USER = "sa"; - private static final String DEFAULT_DB_PWD = ""; - - private static final String DB_DRIVER = "javax.persistence.jdbc.driver"; - private static final String DB_URL = "javax.persistence.jdbc.url"; - private static final String DB_USER = "javax.persistence.jdbc.user"; - private static final String DB_PWD = "javax.persistence.jdbc.password"; - // - - @BeforeClass - public static void setUpClass() throws Exception { - - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Ignore - @Test - public void testJPA() throws Exception { - logger.info("\n\nlogger.infor StateManagementTest: Entering\n\n"); - String resourceName = "test_resource1"; - boolean standbyExceptionThrown = false; - - //These parameters are in a properties file - EntityManagerFactory emf = null; - try { - Properties myProp = new Properties(); - myProp.put(DB_DRIVER, DEFAULT_DB_DRIVER); - myProp.put(DB_URL, DEFAULT_DB_URL); - myProp.put(DB_USER, DEFAULT_DB_USER); - myProp.put(DB_PWD, DEFAULT_DB_PWD); - - //Create the data schema and entity manager factory - emf = Persistence.createEntityManagerFactory("schemaPU", myProp); - - StateManagement sm = new StateManagement(emf, resourceName); - System.out.println("\n\ntest lock()"); - displayState(resourceName, sm); - logger.info("\n??? test lock()"); - logger.info(resourceName + " before adminState = " + sm.getAdminState()); - logger.info(resourceName + " before opState = " + sm.getOpState()); - logger.info(resourceName + " before availStatus = " + sm.getAvailStatus()); - logger.info(resourceName + " before standbyStatus= " + sm.getStandbyStatus()); - sm.lock(); - System.out.println("\n\nafter lock()"); - displayState(resourceName, sm); - logger.info(resourceName + " after adminState = " + sm.getAdminState()); - logger.info(resourceName + " after opState = " + sm.getOpState()); - logger.info(resourceName + " after availStatus = " + sm.getAvailStatus()); - logger.info(resourceName + " after standbyStatus= " + sm.getStandbyStatus()); - - logger.info("\n??? test unlock()"); - sm.unlock(); - System.out.println("\n\nafter unlock()"); - displayState(resourceName, sm); - logger.info(resourceName + " adminState = " + sm.getAdminState()); - logger.info(resourceName + " opState = " + sm.getOpState()); - logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); - logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); - - logger.info("\n??? test enableNotFailed()"); - sm.enableNotFailed(); - System.out.println("\n\nafter enableNotFailed()"); - displayState(resourceName, sm); - logger.info(resourceName + " adminState = " + sm.getAdminState()); - logger.info(resourceName + " opState = " + sm.getOpState()); - logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); - logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); - - logger.info("\n??? test disableFailed()"); - sm.disableFailed(); - System.out.println("\n\nafter disableFailed()"); - displayState(resourceName, sm); - logger.info(resourceName + " adminState = " + sm.getAdminState()); - logger.info(resourceName + " opState = " + sm.getOpState()); - logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); - logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); - - // P4 If promote() is called while either the opState is disabled or the adminState is locked, - // the standbystatus shall transition to coldstandby and a StandbyStatusException shall be thrown - logger.info("\n??? promote() test case P4"); - try { - sm.disableFailed(); - sm.lock(); - System.out.println("\n\nafter lock() and disableFailed"); - displayState(resourceName, sm); - logger.info(resourceName + " adminState = " + sm.getAdminState()); - logger.info(resourceName + " opState = " + sm.getOpState()); - logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); - sm.promote(); - System.out.println("\n\nafter promote"); - displayState(resourceName, sm); - } catch(StandbyStatusException ex) { - standbyExceptionThrown = true; - logger.info("StandbyStatusException thrown and catched"); - } catch(Exception ex) { - logger.info("??? Exception: " + ex.toString()); - } - assert(standbyExceptionThrown); - assert(sm.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); - standbyExceptionThrown = false; - - // P3 If promote() is called while standbyStatus is coldstandby, the state shall not transition - // and a StandbyStatusException shall be thrown - logger.info("\n??? promote() test case P3"); - try { - logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); - sm.promote(); - } catch(StandbyStatusException ex) { - standbyExceptionThrown = true; - logger.info("StandbyStatusException thrown and catched"); - } catch(Exception ex) { - logger.info("??? Exception: " + ex.toString()); - } - assert(standbyExceptionThrown); - assert(sm.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); - System.out.println("\n\nP3 after promote()"); - displayState(resourceName, sm); - standbyExceptionThrown = false; - - // P2 If promote() is called while the standbyStatus is null and the opState is enabled and adminState is unlocked, - // the state shall transition to providingservice - logger.info("\n??? promote() test case P2"); - resourceName = "test_resource2"; - StateManagement sm2 = new StateManagement(emf, resourceName); - sm2.enableNotFailed(); - sm2.unlock(); - System.out.println("\n\nafter sm2.enableNotFailed() and sm2.unlock()"); - displayState(resourceName, sm2); - logger.info(resourceName + " adminState = " + sm2.getAdminState()); - logger.info(resourceName + " opState = " + sm2.getOpState()); - logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); - sm2.promote(); - System.out.println("\n\nP2 after sm2.promote"); - displayState(resourceName, sm2); - assert(sm2.getAdminState().equals(StateManagement.UNLOCKED)); - assert(sm2.getOpState().equals(StateManagement.ENABLED)); - assert(sm2.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); - - // P5 If promote() is called while standbyStatus is providingservice, no action is taken - logger.info("\n??? promote() test case P5"); - logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); - sm2.promote(); - System.out.println("\n\nP5 after sm2.promote()"); - displayState(resourceName, sm2); - assert(sm2.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); - - // D1 If demote() is called while standbyStatus is providingservice, the state shall transition to hotstandby - logger.info("\n??? demote() test case D1"); - logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); - sm2.demote(); - System.out.println("\n\nD1 after sm2.demote()"); - displayState(resourceName, sm2); - assert(sm2.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); - - // D4 If demote() is called while standbyStatus is hotstandby, no action is taken - logger.info("\n??? demote() test case D4"); - logger.info(resourceName + " standbyStatus= " + sm2.getStandbyStatus()); - sm2.demote(); - System.out.println("\n\nD4 after sm2.demote()"); - displayState(resourceName, sm2); - assert(sm2.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); - - // D3 If demote() is called while standbyStatus is null and adminState is locked or opState is disabled, - // the state shall transition to coldstandby - logger.info("\n??? demote() test case D3"); - resourceName = "test_resource3"; - StateManagement sm3 = new StateManagement(emf, resourceName); - sm3.lock(); - sm3.disableFailed(); - System.out.println("\n\nD3 after sm3.lock() and sm3.disableFailed()"); - displayState(resourceName, sm3); - logger.info(resourceName + " adminState = " + sm3.getAdminState()); - logger.info(resourceName + " opState = " + sm3.getOpState()); - logger.info(resourceName + " standbyStatus= " + sm3.getStandbyStatus()); - sm3.demote(); - System.out.println("\n\nD3 after sm3.demote()"); - displayState(resourceName, sm3); - assert(sm3.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); - - // D5 If demote() is called while standbyStatus is coldstandby, no action is taken - logger.info("\n??? demote() test case D5"); - logger.info(resourceName + " standbyStatus= " + sm3.getStandbyStatus()); - sm3.demote(); - System.out.println("\n\nD5 after sm3.demote()"); - displayState(resourceName, sm3); - assert(sm3.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); - - // D2 If demote() is called while standbyStatus is null and adminState is unlocked and opState is enabled, - // the state shall transition to hotstandby - logger.info("\n??? demote() test case D2"); - resourceName = "test_resource4"; - StateManagement sm4 = new StateManagement(emf, resourceName); - sm4.unlock(); - sm4.enableNotFailed(); - System.out.println("\n\nD2 after sm4.unlock() and sm4.enableNotFailed()"); - displayState(resourceName, sm4); - logger.info(resourceName + " adminState = " + sm4.getAdminState()); - logger.info(resourceName + " opState = " + sm4.getOpState()); - logger.info(resourceName + " standbyStatus= " + sm4.getStandbyStatus()); - sm4.demote(); - assert(sm4.getStandbyStatus().equals(StateManagement.HOT_STANDBY)); - - // P1 If promote() is called while standbyStatus is hotstandby, the state shall transition to providingservice. - logger.info("\n??? promote() test case P1"); - logger.info(resourceName + " standbyStatus= " + sm4.getStandbyStatus()); - sm4.promote(); - System.out.println("\n\nP1 after sm4.promote()"); - displayState(resourceName, sm4); - assert(sm4.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); - - // State change notification - logger.info("\n??? State change notification test case 1 - lock()"); - StateChangeNotifier stateChangeNotifier = new StateChangeNotifier(); - sm.addObserver(stateChangeNotifier); - sm.lock(); - - logger.info("\n??? State change notification test case 2 - unlock()"); - sm.unlock(); - - logger.info("\n??? State change notification test case 3 - enabled()"); - sm.enableNotFailed(); - - logger.info("\n??? State change notification test case 4 - disableFailed()"); - sm.disableFailed(); - - logger.info("\n??? State change notification test case 5 - demote()"); - sm.demote(); - - logger.info("\n??? State change notification test case 6 - promote()"); - try { - sm.promote(); - } catch(Exception ex) { - logger.info("Exception from promote(): " + ex.toString()); - } - - if (emf.isOpen()) { - emf.close(); - } - } catch(Exception ex) { - logger.error("Exception: " + ex.toString()); - } finally { - if (emf.isOpen()) { - emf.close(); - } - } - - logger.info("\n\nStateManagementTest: Exit\n\n"); - } - - private void displayState(String resourceName, StateManagement sm) - { - System.out.println("\nAdminState = " + sm.getAdminState() - + "\nOpState() = " + sm.getOpState() - + "\nAvailStatus = " + sm.getAvailStatus() - + "\nStandbyStatus = " + sm.getStandbyStatus() - + "\n"); - logger.info(resourceName + " adminState = " + sm.getAdminState()); - logger.info(resourceName + " opState = " + sm.getOpState()); - logger.info(resourceName + " availStatus = " + sm.getAvailStatus()); - logger.info(resourceName + " standbyStatus= " + sm.getStandbyStatus()); - } -} - diff --git a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateTransitionTest.java b/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateTransitionTest.java deleted file mode 100644 index d90e27bc..00000000 --- a/integrity-monitor/src/test/java/org/openecomp/policy/common/im/test/StateTransitionTest.java +++ /dev/null @@ -1,2175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Integrity Monitor - * ================================================================================ - * 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.openecomp.policy.common.im.test; - -import java.util.Properties; -import javax.persistence.EntityManagerFactory; -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.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - -import org.openecomp.policy.common.im.StateTransition; -import org.openecomp.policy.common.im.StateElement; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.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. - */ -public class StateTransitionTest { - private static Logger logger = FlexLogger.getLogger(StateTransitionTest.class); - - private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; - private static final String DEFAULT_DB_URL = "jdbc:h2:file:./sql/smTest"; - private static final String DEFAULT_DB_USER = "sa"; - private static final String DEFAULT_DB_PWD = ""; - - private static final String DB_DRIVER = "javax.persistence.jdbc.driver"; - private static final String DB_URL = "javax.persistence.jdbc.url"; - private static final String DB_USER = "javax.persistence.jdbc.user"; - private static final String DB_PWD = "javax.persistence.jdbc.password"; - // - - @BeforeClass - public static void setUpClass() throws Exception { - - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Ignore - @Test - public void testJPA() throws Exception { - logger.info("\n\nlogger.infor StateTransitionTest: Entering\n\n"); - //These parameters are in a properties file - EntityManagerFactory emf = null; - try { - Properties myProp = new Properties(); - myProp.put(DB_DRIVER, DEFAULT_DB_DRIVER); - myProp.put(DB_URL, DEFAULT_DB_URL); - myProp.put(DB_USER, DEFAULT_DB_USER); - myProp.put(DB_PWD, DEFAULT_DB_PWD); - - logger.info("??? create a new StateTransition"); - StateTransition st = new StateTransition(); - - StateElement se = null; - try { - // bad test case - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "lock"); - // - logger.info("??? StateTransition testcase 1"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "lock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 2"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 3"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 4"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 5"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 6"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 7"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 8"); - se = st.getEndingState("unlocked", "enabled", "null", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 9"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 10"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 11"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 12"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 13"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 14"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 15"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 16"); - se = st.getEndingState("unlocked", "enabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 17"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 18"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 19"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 20"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 21"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 22"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 23"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 24"); - se = st.getEndingState("unlocked", "enabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 25"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 26"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 27"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 28"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 29"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 30"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 31"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 32"); - se = st.getEndingState("unlocked", "enabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 33"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 34"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 35"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 36"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 37"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 38"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 39"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 40"); - se = st.getEndingState("unlocked", "enabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 41"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 42"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 43"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 44"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 45"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 46"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 47"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 48"); - se = st.getEndingState("unlocked", "enabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 49"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 50"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 51"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 52"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 53"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 54"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 55"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 56"); - se = st.getEndingState("unlocked", "enabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 57"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 58"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 59"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 60"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 61"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 62"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 63"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 64"); - se = st.getEndingState("unlocked", "enabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 65"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 66"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 67"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 68"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 69"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 70"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 71"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 72"); - se = st.getEndingState("unlocked", "enabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 73"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 74"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 75"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 76"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 77"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 78"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 79"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 80"); - se = st.getEndingState("unlocked", "enabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 81"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 82"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 83"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 84"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 85"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 86"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 87"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 88"); - se = st.getEndingState("unlocked", "enabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 89"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 90"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 91"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 92"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 93"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 94"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 95"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 96"); - se = st.getEndingState("unlocked", "enabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 97"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 98"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 99"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 100"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 101"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 102"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 103"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 104"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 105"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 106"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 107"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 108"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 109"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 110"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 111"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 112"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 113"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 114"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 115"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 116"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 117"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 118"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 119"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 120"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 121"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 122"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 123"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 124"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 125"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 126"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 127"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 128"); - se = st.getEndingState("unlocked", "enabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 129"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 130"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 131"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 132"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 133"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 134"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 135"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 136"); - se = st.getEndingState("unlocked", "disabled", "null", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 137"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 138"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 139"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 140"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 141"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 142"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 143"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 144"); - se = st.getEndingState("unlocked", "disabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 145"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 146"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 147"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 148"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 149"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 150"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 151"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 152"); - se = st.getEndingState("unlocked", "disabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 153"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 154"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 155"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 156"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 157"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 158"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 159"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 160"); - se = st.getEndingState("unlocked", "disabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 161"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 162"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 163"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 164"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 165"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 166"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 167"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 168"); - se = st.getEndingState("unlocked", "disabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 169"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 170"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 171"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 172"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 173"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 174"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 175"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 176"); - se = st.getEndingState("unlocked", "disabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 177"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 178"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 179"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 180"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 181"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 182"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 183"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 184"); - se = st.getEndingState("unlocked", "disabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 185"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 186"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 187"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 188"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 189"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 190"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 191"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 192"); - se = st.getEndingState("unlocked", "disabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 193"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 194"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 195"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 196"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 197"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 198"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 199"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 200"); - se = st.getEndingState("unlocked", "disabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 201"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 202"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 203"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 204"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 205"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 206"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 207"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 208"); - se = st.getEndingState("unlocked", "disabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 209"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 210"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 211"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 212"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 213"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 214"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 215"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 216"); - se = st.getEndingState("unlocked", "disabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 217"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 218"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 219"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 220"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 221"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 222"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 223"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 224"); - se = st.getEndingState("unlocked", "disabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 225"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 226"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 227"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 228"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 229"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 230"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 231"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 232"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 233"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 234"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 235"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 236"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 237"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 238"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 239"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 240"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 241"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 242"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 243"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 244"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 245"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 246"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 247"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 248"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 249"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 250"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 251"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 252"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 253"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 254"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 255"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 256"); - se = st.getEndingState("unlocked", "disabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 257"); - se = st.getEndingState("locked", "enabled", "null", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 258"); - se = st.getEndingState("locked", "enabled", "null", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 259"); - se = st.getEndingState("locked", "enabled", "null", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 260"); - se = st.getEndingState("locked", "enabled", "null", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 261"); - se = st.getEndingState("locked", "enabled", "null", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 262"); - se = st.getEndingState("locked", "enabled", "null", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 263"); - se = st.getEndingState("locked", "enabled", "null", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 264"); - se = st.getEndingState("locked", "enabled", "null", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 265"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 266"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 267"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 268"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 269"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 270"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 271"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 272"); - se = st.getEndingState("locked", "enabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 273"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 274"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 275"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 276"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 277"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 278"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 279"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 280"); - se = st.getEndingState("locked", "enabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 281"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 282"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 283"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 284"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 285"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 286"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 287"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 288"); - se = st.getEndingState("locked", "enabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 289"); - se = st.getEndingState("locked", "enabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 290"); - se = st.getEndingState("locked", "enabled", "failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 291"); - se = st.getEndingState("locked", "enabled", "failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 292"); - se = st.getEndingState("locked", "enabled", "failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 293"); - se = st.getEndingState("locked", "enabled", "failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 294"); - se = st.getEndingState("locked", "enabled", "failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 295"); - se = st.getEndingState("locked", "enabled", "failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 296"); - se = st.getEndingState("locked", "enabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 297"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 298"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 299"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 300"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 301"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 302"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 303"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 304"); - se = st.getEndingState("locked", "enabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 305"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 306"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 307"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 308"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 309"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 310"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 311"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 312"); - se = st.getEndingState("locked", "enabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 313"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 314"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 315"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 316"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 317"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 318"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 319"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 320"); - se = st.getEndingState("locked", "enabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 321"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 322"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 323"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 324"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 325"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 326"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 327"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 328"); - se = st.getEndingState("locked", "enabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 329"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 330"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 331"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 332"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 333"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 334"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 335"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 336"); - se = st.getEndingState("locked", "enabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 337"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 338"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 339"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 340"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 341"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 342"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 343"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 344"); - se = st.getEndingState("locked", "enabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 345"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 346"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 347"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 348"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 349"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 350"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 351"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 352"); - se = st.getEndingState("locked", "enabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 353"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 354"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 355"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 356"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 357"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 358"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 359"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 360"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 361"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 362"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 363"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 364"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 365"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 366"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 367"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 368"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 369"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 370"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 371"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 372"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 373"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 374"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 375"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 376"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 377"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 378"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 379"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 380"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 381"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 382"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 383"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 384"); - se = st.getEndingState("locked", "enabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 385"); - se = st.getEndingState("locked", "disabled", "null", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 386"); - se = st.getEndingState("locked", "disabled", "null", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 387"); - se = st.getEndingState("locked", "disabled", "null", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 388"); - se = st.getEndingState("locked", "disabled", "null", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 389"); - se = st.getEndingState("locked", "disabled", "null", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 390"); - se = st.getEndingState("locked", "disabled", "null", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 391"); - se = st.getEndingState("locked", "disabled", "null", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 392"); - se = st.getEndingState("locked", "disabled", "null", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 393"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 394"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 395"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 396"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 397"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 398"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 399"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 400"); - se = st.getEndingState("locked", "disabled", "null", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 401"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 402"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 403"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 404"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 405"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 406"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 407"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 408"); - se = st.getEndingState("locked", "disabled", "null", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 409"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 410"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 411"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 412"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 413"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 414"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 415"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 416"); - se = st.getEndingState("locked", "disabled", "null", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 417"); - se = st.getEndingState("locked", "disabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 418"); - se = st.getEndingState("locked", "disabled", "failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 419"); - se = st.getEndingState("locked", "disabled", "failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 420"); - se = st.getEndingState("locked", "disabled", "failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 421"); - se = st.getEndingState("locked", "disabled", "failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 422"); - se = st.getEndingState("locked", "disabled", "failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 423"); - se = st.getEndingState("locked", "disabled", "failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 424"); - se = st.getEndingState("locked", "disabled", "failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 425"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 426"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 427"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 428"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 429"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 430"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 431"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 432"); - se = st.getEndingState("locked", "disabled", "failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 433"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 434"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 435"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 436"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 437"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 438"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 439"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 440"); - se = st.getEndingState("locked", "disabled", "failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 441"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 442"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 443"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 444"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 445"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 446"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 447"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 448"); - se = st.getEndingState("locked", "disabled", "failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 449"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 450"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 451"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 452"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 453"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 454"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 455"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 456"); - se = st.getEndingState("locked", "disabled", "dependency", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 457"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 458"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 459"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 460"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 461"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 462"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 463"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 464"); - se = st.getEndingState("locked", "disabled", "dependency", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 465"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 466"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 467"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 468"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 469"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 470"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 471"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 472"); - se = st.getEndingState("locked", "disabled", "dependency", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 473"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 474"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 475"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 476"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 477"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 478"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 479"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 480"); - se = st.getEndingState("locked", "disabled", "dependency", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 481"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 482"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 483"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 484"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 485"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 486"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 487"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 488"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "null", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 489"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 490"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 491"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 492"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 493"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 494"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 495"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 496"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "coldstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 497"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 498"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 499"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 500"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 501"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 502"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 503"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 504"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "hotstandby", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 505"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 506"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "unlock"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 507"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "disableFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 508"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "enableNotFailed"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 509"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "disableDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 510"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "enableNoDependency"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 511"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "promote"); - if (se != null) displayEndingState(se); - - logger.info("??? StateTransition testcase 512"); - se = st.getEndingState("locked", "disabled", "dependency,failed", "providingservice", "demote"); - if (se != null) displayEndingState(se); - - } catch (Exception ex) { - logger.error("EndingState NOT found"); - throw new Exception("EndingState NOT found. " + ex); - } - - //if (emf.isOpen()) { - //emf.close(); - //} - } catch(Exception ex) { - logger.error("Exception: " + ex.toString()); - throw new Exception("Failure getting ending state. " + ex ); - } finally { - if (emf != null && emf.isOpen()) { - emf.close(); - } - } - - logger.info("\n\nStateTransitionTest: Exit\n\n"); - } - - private void displayEndingState(StateElement se) - { - String endingStandbyStatus = se.getEndingStandbyStatus(); - if (endingStandbyStatus != null) { - endingStandbyStatus.replace(".", ","); - } - logger.info("EndingAdminState = [" + se.getEndingAdminState() +"]"); - logger.info("EndingOpState = [" + se.getEndingOpState() +"]"); - logger.info("EndingAvailStatus = [" + se.getEndingAvailStatus() +"]"); - logger.info("EndingStandbyStatus= [" + endingStandbyStatus +"]"); - logger.info("Exception = [" + se.getException() +"]"); - } -} \ No newline at end of file diff --git a/integrity-monitor/src/test/resources/logback.xml b/integrity-monitor/src/test/resources/logback.xml index 3a879008..544162f3 100644 --- a/integrity-monitor/src/test/resources/logback.xml +++ b/integrity-monitor/src/test/resources/logback.xml @@ -29,7 +29,7 @@ + ::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> diff --git a/pom.xml b/pom.xml index 289fdd5c..d16039df 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@