aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoradheli.tavares <adheli.tavares@est.tech>2024-08-29 15:58:06 +0100
committeradheli.tavares <adheli.tavares@est.tech>2024-08-29 15:59:31 +0100
commitf875828ecc091dc505697ac98256ba06aff9a20a (patch)
tree62f23931de0fa3dce16021bc8badd6822cdd615a
parent63d23a4aa0f3aeae9d6470b95dfa8f87b2d85aa8 (diff)
Remove modules not being used
Remove modules common-logging, integrity-audity and integrity-monitor as they are not being used in any component. Issue-ID: POLICY-5123 Change-Id: I571f17236a3c8bb9e8e52c99d0298f4098cb5ca9 Signed-off-by: adheli.tavares <adheli.tavares@est.tech>
-rw-r--r--common-logging/config/policyLogger.properties44
-rw-r--r--common-logging/policyLogger.properties50
-rw-r--r--common-logging/pom.xml124
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java567
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java104
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfo.java53
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java117
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java80
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java85
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java96
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/MdcInfo.java37
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java160
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java87
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java1423
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java47
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java575
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java218
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java249
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java28
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java340
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java548
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java64
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java53
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java37
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java52
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java63
-rw-r--r--common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java28
-rw-r--r--common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties229
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfoTest.java43
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java62
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java172
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java130
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java131
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java718
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java390
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java112
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java172
-rw-r--r--common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java558
-rw-r--r--integrity-audit/config/policyLogger.properties44
-rw-r--r--integrity-audit/policyLogger.properties44
-rw-r--r--integrity-audit/pom.xml95
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java771
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java54
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java503
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java41
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java722
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java41
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java287
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditException.java41
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java46
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java41
-rw-r--r--integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java130
-rw-r--r--integrity-audit/src/main/resources/META-INF/persistence.xml47
-rw-r--r--integrity-audit/src/main/resources/log4j.properties48
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java254
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/AuditorTimeTest.java43
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java551
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java283
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java452
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java103
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java53
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java593
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java75
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java658
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java177
-rw-r--r--integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java69
-rw-r--r--integrity-audit/src/test/resources/log4j.properties54
-rw-r--r--integrity-audit/src/test/resources/logback-test.xml258
-rw-r--r--integrity-audit/src/test/resources/logger-test.expectedlog1
-rw-r--r--integrity-audit/src/test/resources/policyLogger.properties45
-rw-r--r--integrity-audit/src/test/resources/xlogger-test.expectedlog1
-rw-r--r--integrity-monitor/config/policyLogger.properties44
-rw-r--r--integrity-monitor/policyLogger.properties44
-rw-r--r--integrity-monitor/pom.xml87
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java41
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java42
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java41
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java1915
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java47
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java62
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java41
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java39
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java47
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java76
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java60
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java551
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java42
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java401
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java42
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java31
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java226
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java44
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java49
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java120
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java71
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java70
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java89
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java68
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java113
-rw-r--r--integrity-monitor/src/main/resources/META-INF/persistence.xml51
-rw-r--r--integrity-monitor/src/main/resources/log4j.properties48
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/AllSeemsWellTest.java209
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/ExceptionsTest.java79
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTest.java982
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTestBase.java268
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/MonitorTimeTest.java43
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/StateChangeNotifierTest.java49
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementEntityTest.java138
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementTest.java297
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/StateTransitionTest.java3566
-rw-r--r--integrity-monitor/src/test/java/org/onap/policy/common/im/exceptions/EntityRetrievalExceptionTest.java37
-rw-r--r--integrity-monitor/src/test/resources/logback-test.xml46
-rw-r--r--pom.xml3
-rw-r--r--utils-test/pom.xml1
-rw-r--r--utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java2
115 files changed, 0 insertions, 24993 deletions
diff --git a/common-logging/config/policyLogger.properties b/common-logging/config/policyLogger.properties
deleted file mode 100644
index 8e4e869a..00000000
--- a/common-logging/config/policyLogger.properties
+++ /dev/null
@@ -1,44 +0,0 @@
-###
-# ============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=========================================================
-###
-
-################################### Set concurrentHashMap and timer info #######################
-#Timer initial delay and the delay between in milliseconds before task is to be execute.
-timer.delay.time=1000
-#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions.
-check.interval= 30000
-#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds.
-event.expired.time=86400
-#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed
-#to remove all expired records from this concurrentHashMap.
-concurrentHashMap.limit=5000
-#Size of the concurrentHashMap - when its size drops to this point, stop the Timer
-stop.check.point=2500
-################################### Set logging format #############################################
-# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println
-logger.type=EELF
-#################################### Set level for EELF or SYSTEMOUT logging ##################################
-# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all
-debugLogger.level=INFO
-# Set level for metrics file. Set OFF to disable; set ON to enable
-metricsLogger.level=ON
-# Set level for error file. Set OFF to disable; set ON to enable
-error.level=ON
-# Set level for audit file. Set OFF to disable; set ON to enable
-audit.level=ON \ No newline at end of file
diff --git a/common-logging/policyLogger.properties b/common-logging/policyLogger.properties
deleted file mode 100644
index e2335df6..00000000
--- a/common-logging/policyLogger.properties
+++ /dev/null
@@ -1,50 +0,0 @@
-###
-# ============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=========================================================
-###
-
-################################### Set concurrentHashMap and timer info #######################
-#Timer initial delay and the delay between in milliseconds before task is to be execute.
-timer.delay.time=1000
-#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions.
-check.interval= 30000
-#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds.
-event.expired.time=86400
-#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed
-#to remove all expired records from this concurrentHashMap.
-concurrentHashMap.limit=5000
-#Size of the concurrentHashMap - when its size drops to this point, stop the Timer
-stop.check.point=2500
-################################### Set logging format #############################################
-# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println
-logger.type=EELF
-#################################### Set level for EELF or SYSTEMOUT logging ##################################
-# Set override flag. Set TRUE for override the level setups in logback.xml. Set FALSE for using the level setups of logback.xml
-override.logback.level.setup=FALSE
-#Only use these setups below if override.logback.level.setup=TRUE
-# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all
-debugLogger.level=INFO
-# Set level for metrics file. Set OFF to disable; set ON to enable
-metricsLogger.level=ON
-# Set level for error file. Set OFF to disable; set ON to enable
-error.level=ON
-# Set level for audit file. Set OFF to disable; set ON to enable
-audit.level=ON
-#################################### Set Policy Component ##################################
-# Set DROOLS for drools PDP. Set XACML to xacml PDP
-policy.component=DROOLS
diff --git a/common-logging/pom.xml b/common-logging/pom.xml
deleted file mode 100644
index 2a889d0e..00000000
--- a/common-logging/pom.xml
+++ /dev/null
@@ -1,124 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- ONAP Policy Engine - Common Modules
- ================================================================================
- Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023-2024 Nordix Foundation.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>common-modules</artifactId>
- <version>3.0.1-SNAPSHOT</version>
- </parent>
-
- <artifactId>ONAP-Logging</artifactId>
- <description>ONAP Logging Framework</description>
- <packaging>jar</packaging>
-
- <dependencies>
- <dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- <version>2.0.0-oss</version>
- <exclusions>
- <exclusion>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.re2j</groupId>
- <artifactId>re2j</artifactId>
- </dependency>
- <dependency>
- <groupId>jakarta.servlet</groupId>
- <artifactId>jakarta.servlet-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-maven-plugin</artifactId>
- <version>2.0.0-oss</version>
- <executions>
- <execution>
- <phase>install</phase>
- <goals>
- <goal>WikiMsgGenerator</goal>
- </goals>
- </execution>
- </executions>
- <dependencies>
- <!-- We need to include the dependency of the project so that its include
- in classpath when running plugin -->
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>ONAP-Logging</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
- <configuration>
- <outputDirectory>target/messages</outputDirectory>
- <outputFile>messages.html</outputFile>
- <resources>
- <resource>
- <messageClass>org.onap.policy.common.logging.eelf.MessageCodes</messageClass>
- This needs to be replaced with your Enum
- class name .which
- implements EELFResolvableErrorEnum and have your defined error
- codes.
- <header><![CDATA[<p> <ac:macro ac:name="toc" /> </p>
- <p>
- <ac:macro ac:name="anchor"> <ac:default-parameter>Application Messages</ac:default-parameter> </ac:macro> </p> <h2>Application Messages</h2>]]></header>
- </resource>
-
- </resources>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
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
deleted file mode 100644
index e457f5f3..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingContext.java
+++ /dev/null
@@ -1,567 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging;
-
-import java.text.SimpleDateFormat;
-import java.time.Duration;
-import java.time.Instant;
-import java.util.Date;
-import org.onap.policy.common.logging.nsa.LoggingContextFactory;
-import org.onap.policy.common.logging.nsa.SharedLoggingContext;
-import org.slf4j.MDC;
-
-/**
- * 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.
- *
- * <p>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.
- *
- * <p>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 final String POLICY = "POLICY";
- private static final String USER = "USER";
- private static final String COMPLETE = "COMPLETE";
- private static final String PE_PROCESS = "PE Process";
- private static final String TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS+00:00";
- private static final String EMPTY_STRING = "";
- private static final int DEFAULT_VALUE = 0;
-
-
- private static LoggingContextFactory.Builder loggingContextBuilder = new LoggingContextFactory.Builder();
-
- protected SharedLoggingContext context = null;
- 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 onap logging context
- */
- 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 <code>transactionEnded()</code> to calculate the duration of the transaction.
- */
- public void transactionStarted() {
- transactionStartTime = Instant.now();
- setTransactionBeginTimestamp(transactionStartTime);
- }
-
- /**
- * Indicate the end of transaction processing. The difference between the current system time
- * and the time recorded by <code>transactionStarted()</code> will be recorded in the data item
- * with key "TransactionElapsedTime".
- */
- public void transactionEnded() {
- var transactionEndTime = Instant.now();
- setTransactionEndTimestamp(transactionEndTime);
- setTransactionElapsedTime(transactionEndTime);
- }
-
- /**
- * Indicate the start of metric processing. The current system time will be recorded for use by
- * <code>metricEnded()</code> to calculate the duration of the metric.
- */
- public void metricStarted() {
- metricStartTime = Instant.now();
- setMetricBeginTimestamp(metricStartTime);
- }
-
- /**
- * Indicate the end of metric processing. The difference between the current system time and the
- * time recorded by <code>metricStarted()</code> will be recorded in the data item with key
- * "MetricElapsedTime".
- */
- public void metricEnded() {
- var metricEndTime = Instant.now();
- setMetricEndTimestamp(metricEndTime);
- setMetricElapsedTime(metricEndTime);
- }
-
- /**
- * Set the value for the data item with key "requestId".
- *
- * @param id request identifier
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "serviceInstanceId".
- *
- * @param id service identifier
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * 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 thread identifier
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "serverName".
- *
- * @param name server name
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "serviceName".
- *
- * @param name service name
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "partnerName".
- *
- * @param name partner name
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "statusCode".
- *
- * @param name status code
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "targetEntity".
- *
- * @param name target entity
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "targetServiceName".
- *
- * @param name target service name
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "instanceUuid".
- *
- * @param uuid instance uuid
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "severity".
- *
- * @param severity severity
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "serverIp".
- *
- * @param serverIp server ip address
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "server".
- *
- * @param server server
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "clientIp".
- *
- * @param clientIp client ip address
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * 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 classname class name
- */
- 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, EMPTY_STRING);
- }
-
- /**
- * Set the value for the data item with key "TransactionBeginTimestamp".
- *
- * @param transactionStartTime transaction start time
- */
- public void setTransactionBeginTimestamp(Instant transactionStartTime) {
- var sdf = new SimpleDateFormat(TIME_FORMAT);
- context.put(TRANSACTION_BEGIN_TIME_STAMP, sdf.format(Date.from(transactionStartTime)));
- }
-
- /**
- * 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, DEFAULT_VALUE);
- }
-
- /**
- * Set the value for the data item with key "TransactionEndTimestamp".
- *
- * @param transactionEndTime transaction end time
- */
- public void setTransactionEndTimestamp(Instant transactionEndTime) {
- var sdf = new SimpleDateFormat(TIME_FORMAT);
- context.put(TRANSACTION_END_TIME_STAMP, sdf.format(Date.from(transactionEndTime)));
- }
-
- /**
- * 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, DEFAULT_VALUE);
- }
-
- /**
- * Set the value for the data item with key "TransactionElapsedTime". An alternative to calling
- * this method directly is to call <code>transactionStarted()</code> at the start of transaction
- * processing and <code>transactionEnded()</code> at the end, which will compute the time
- * difference in milliseconds and store the result as the "ns" value.
- *
- * @param transactionEndTime transaction end time
- */
-
- public void setTransactionElapsedTime(Instant transactionEndTime) {
- long ns = Duration.between(transactionStartTime, transactionEndTime).toMillis();
- context.put(TRANSACTION_ELAPSED_TIME, ns);
- }
-
- /**
- * 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, DEFAULT_VALUE);
- }
-
- /**
- * Set the value for the data item with key "MetricBeginTimestamp".
- *
- * @param metricStartTime metric start time
- */
- public void setMetricBeginTimestamp(Instant metricStartTime) {
- var sdf = new SimpleDateFormat(TIME_FORMAT);
- context.put(METRIC_BEGIN_TIME_STAMP, sdf.format(Date.from(metricStartTime)));
- }
-
- /**
- * 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, DEFAULT_VALUE);
- }
-
- /**
- * Set the value for the data item with key "MetricEndTimestamp".
- *
- * @param metricEndTime metric end time
- */
- public void setMetricEndTimestamp(Instant metricEndTime) {
- var sdf = new SimpleDateFormat(TIME_FORMAT);
- context.put(METRIC_END_TIME_STAMP, sdf.format(Date.from(metricEndTime)));
- }
-
- /**
- * 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, DEFAULT_VALUE);
- }
-
- /**
- * Set the value for the data item with key "MetricElapsedTime". An alternative to calling this
- * method directly is to call <code>metricStarted()</code> at the start of metric processing and
- * <code>metricEnded()</code> at the end, which will compute the time difference in milliseconds
- * and store the result as the "ns" value.
- *
- * @param metricEndTime metric end time
- */
-
- public void setMetricElapsedTime(Instant metricEndTime) {
- long ns = Duration.between(metricStartTime, metricEndTime).toMillis();
- context.put(METRIC_ELAPSED_TIME, ns);
- }
-
- /**
- * 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, DEFAULT_VALUE);
- }
-}
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
deleted file mode 100644
index 91133d1a..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/OnapLoggingUtils.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging;
-
-import com.google.re2j.Pattern;
-import jakarta.servlet.http.HttpServletRequest;
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class OnapLoggingUtils {
-
- private static final Pattern COMMA_PAT = Pattern.compile(",");
- private static final Pattern CURLS_PAT = Pattern.compile("[{][}]");
-
- /**
- * Get the ONAPLoggingContext for a request.
- *
- * @param request the request
- * @param baseContext the context to supply to the ONAPLoggingContext
- * @return the ONAPLoggingContext
- */
- public static OnapLoggingContext getLoggingContextForRequest(HttpServletRequest request,
- OnapLoggingContext baseContext) {
- var 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 = COMMA_PAT.split(forwarded.trim())[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;
- }
-
- /**
- * Create message text replace {} place holder with data
- * if last argument is throwable/exception, pass it as argument to logger.
- * @param format message format can contains text and {}
- * @param arguments output arguments
- * @return the formatted message as a String
- */
- public static String formatMessage(String format, Object...arguments) {
- if (arguments.length <= 0 || arguments[0] == null) {
- return format;
- }
- int index;
- var builder = new StringBuilder();
- String[] token = CURLS_PAT.split(format);
- for (index = 0; index < arguments.length; index++) {
- if (index < token.length) {
- builder.append(token[index]);
- builder.append(arguments[index]);
- } else {
- break;
- }
- }
- for (int index2 = index; index2 < token.length; index2++) {
- builder.append(token[index2]);
- }
-
- return builder.toString();
- }
-
- /**
- * Check object is throwable.
- * @param obj to verify
- * @return true if object is throwable or false otherwise
- */
- public static boolean isThrowable(Object obj) {
- return (obj instanceof Throwable);
- }
-}
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
deleted file mode 100644
index 6086a642..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfo.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import com.att.eelf.configuration.Configuration;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class DroolsPdpMdcInfo implements MdcInfo {
-
- private static ConcurrentHashMap<String, String> mdcMap = new ConcurrentHashMap<>();
-
- static {
-
- mdcMap.put(Configuration.MDC_REMOTE_HOST, "");
- mdcMap.put(Configuration.MDC_SERVICE_NAME, "Policy.droolsPdp");
- mdcMap.put(Configuration.MDC_SERVICE_INSTANCE_ID, "Policy.droolsPdp.event");
- mdcMap.put(Configuration.MDC_INSTANCE_UUID, "");
- mdcMap.put(Configuration.MDC_ALERT_SEVERITY, "");
- mdcMap.put(OnapConfigProperties.PARTNER_NAME, "N/A");
- mdcMap.put(OnapConfigProperties.STATUS_CODE, "N/A");
- mdcMap.put(OnapConfigProperties.RESPONSE_CODE, "N/A");
- mdcMap.put(OnapConfigProperties.RESPONSE_DESCRIPTION, "N/A");
- }
-
- /**
- * Get the MMDC Info.
- *
- * @return the instance of ConcurrentHashMap.
- */
- @Override
- public ConcurrentMap<String, String> 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
deleted file mode 100644
index 0eaa06b0..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/ErrorCodeMap.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import java.util.EnumMap;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-
-/**
- * ErrorCodeMap contains a HashMap of ErrorCodeInfo (error code and error description).
- * Standard error code:
- * 100 – permission errors
- * 200 – availability errors
- * 300 – data errors
- * 400 – schema errors
- * 500 – business process errors
- * 900 – unknown errors
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class ErrorCodeMap {
-
- private static final EnumMap<MessageCodes, ErrorCodeInfo> hm = new EnumMap<>(MessageCodes.class);
-
- private static final String CHECK_ERROR_MESSAGE = " Please check the error message for detail information";
-
- private static final String ERROR_PERMISSIONS = "100";
- private static final String ERROR_PERMISSIONS_DESCRIPTION = "This is a Permissions Error." + CHECK_ERROR_MESSAGE;
-
- private static final String ERROR_SCHEMA_INVALID = "400";
- private static final String ERROR_SCHEMA_INVALID_DESCRIPTION = "This is an Invalid Schema Error."
- + CHECK_ERROR_MESSAGE;
-
-
- private static final String UPDATE_ERROR = "300";
- private static final String UPDATE_ERROR_DESCRIPTION = "This is an updating error." + CHECK_ERROR_MESSAGE;
-
- private static final String EXCEPTION_ERROR_CODE = "500";
- private static final String EXCEPTION_ERROR_DESCRIPTION = "This is an exception error message during the process."
- + CHECK_ERROR_MESSAGE;
-
- private static final String MISS_PROPERTY_ERROR = "300";
- private static final String MISS_PROPERTY_ERROR_DESCRIPTION = "This is an error of missing properties."
- + CHECK_ERROR_MESSAGE;
-
- private static final String GENERAL_ERROR_CODE = "500";
- private static final String GENERAL_ERROR_DESCRIPTION = "This is a general error message during the process."
- + CHECK_ERROR_MESSAGE;
-
- private static final String ERROR_SYSTEM_ERROR = "200";
- private static final String ERROR_SYSTEM_ERROR_DESCRIPTION = "This is a System Error." + CHECK_ERROR_MESSAGE;
-
- private static final String ERROR_DATA_ISSUE = "300";
- private static final String ERROR_DATA_ISSUE_DESCRIPTION = "This is a Data Issue Error." + CHECK_ERROR_MESSAGE;
-
- private static final String ERROR_PROCESS_FLOW = "500";
- private static final String ERROR_PROCESS_FLOW_DESCRIPTION = "This is a Process Flow Error." + CHECK_ERROR_MESSAGE;
-
- private static final String ERROR_UNKNOWN = "900";
- private static final String ERROR_UNKNOWN_DESCRIPTION = "This is an Unknown Error." + CHECK_ERROR_MESSAGE;
-
- private static final String ERROR_AUDIT = "300";
- private static final String ERROR_AUDIT_DESCRIPTION = "This is an audit Error." + CHECK_ERROR_MESSAGE;
-
- 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_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));
- }
-
- public static ErrorCodeInfo getErrorCodeInfo(MessageCodes messageCode) {
- return hm.get(messageCode);
- }
-
- @Getter
- static class ErrorCodeInfo {
-
- private final String errorCode;
- private final String errorDesc;
-
- public ErrorCodeInfo(String errorCode, String errorDesc) {
- this.errorCode = errorCode;
- 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
deleted file mode 100644
index bdd67a08..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import java.time.Instant;
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-/**
- * EventData can be used for logging a rule event.
- */
-@Getter
-@Setter
-@NoArgsConstructor
-@AllArgsConstructor
-public class EventData {
-
- private String requestId = null;
- private Instant startTime = null;
- private Instant endTime = null;
-
- @Override
- public String toString() {
- return requestId + " Starting Time : " + this.startTime + " Ending Time : " + this.endTime;
- }
-
- @Override
- public int hashCode() {
- final var prime = 31;
- var 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 otherRequestId) {
- return requestId != null && requestId.equals(otherRequestId);
- }
- 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
deleted file mode 100644
index f6f38d0d..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfo.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import lombok.Getter;
-
-/**
- * EventTrackInfo contains a ConcurrentHashMap of EventData.
- */
-public class EventTrackInfo {
-
- @Getter
- private final ConcurrentMap<String, EventData> eventInfo;
-
- /**
- * Construct an instance.
- */
- 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 Concurrency Level 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 request id
- * @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 event data
- */
- public void storeEventData(EventData event) {
-
- if (event != null) {
- String id = event.getRequestId();
- if (id == null || id.isEmpty()) {
- return;
- }
- // in case override the start time, check the original event was already stored or not
- eventInfo.putIfAbsent(id, event);
- }
- }
-
- /**
- * Removes an EventData object from a ConcurrentHashMap using the eventId as key.
- *
- * @param eventId event id
- */
- public void remove(String eventId) {
- if (eventInfo != null) {
- eventInfo.remove(eventId);
- }
- }
-}
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
deleted file mode 100644
index f5203683..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandler.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import java.time.Duration;
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.TimerTask;
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * EventTrackInfoHandler is the handler of clean up all expired event objects.
- */
-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() {
-
- var eventTrackInfo = PolicyLogger.getEventTracker();
- if (eventTrackInfo == null) {
- return;
- }
- ConcurrentMap<String, EventData> eventInfo = eventTrackInfo.getEventInfo();
- if (eventInfo == null || eventInfo.isEmpty()) {
- return;
- }
-
- Instant startTime;
- long ns;
-
- ArrayList<String> expiredEvents = null;
-
- for (Map.Entry<String, EventData> entry : eventInfo.entrySet()) {
- EventData event = entry.getValue();
- startTime = event.getStartTime();
- ns = Duration.between(startTime, Instant.now()).getSeconds();
-
- PolicyLogger.info(className + " duration time : " + ns);
-
- PolicyLogger.info(className + " PolicyLogger.EXPIRED_TIME : " + PolicyLogger.expiredTime);
-
- // if longer than EXPIRED_TIME, remove the object
-
- if (ns > PolicyLogger.expiredTime) {
- if (expiredEvents == null) {
- expiredEvents = new ArrayList<>();
- }
- expiredEvents.add(entry.getKey());
-
- PolicyLogger.info(className + " add expired event request ID: " + event.getRequestId());
- }
- }
-
- synchronized (eventInfo) {
- if (expiredEvents != null) {
- for (String expiredKey : expiredEvents) {
- eventInfo.remove(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
deleted file mode 100644
index 59b8e8c3..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MdcInfo.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * Interface needs to be implemented by DroolsPDPMDCInfo.
- */
-@FunctionalInterface
-public interface MdcInfo {
-
- /**
- * Returns MDC info.
- *
- * @return MDC info
- */
- ConcurrentMap<String, String> 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
deleted file mode 100644
index 0535b9d7..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/MessageCodes.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import com.att.eelf.i18n.EELFResolvableResourceEnum;
-import com.att.eelf.i18n.EELFResourceManager;
-
-/**
- * MessageCodes contains all the messagge codes for EELF logging messages.
- */
-public enum MessageCodes implements EELFResolvableResourceEnum {
- // 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,
-
- 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);
-
- PolicyLogger.info("*********************** Rule audit id: " + id);
- PolicyLogger.info("*********************** Rule audit value: " + value);
-
- }
-}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java b/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java
deleted file mode 100644
index cfb14643..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/OnapConfigProperties.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class OnapConfigProperties {
-
- /**
- * The Date-time of the start of a transaction.
- */
- public static final String BEGIN_TIME_STAMP = "BeginTimestamp";
-
- /**
- * The Date-time of the end of transaction.
- */
- public static final String END_TIME_STAMP = "EndTimestamp";
-
- /**
- * Externally advertised API invoked by clients of this component.
- */
- public static final String SERVICE_NAME = "ServiceName";
-
- /**
- * Client or user invoking the API.
- */
- public static final String PARTNER_NAME = "PartnerName";
-
- public static final String TARGET_ENTITY = "TargetEntity";
-
- public static final String TARGET_SERVICE_NAME = "TargetServiceName";
-
- /**
- * High level success or failure (COMPLETE or ERROR).
- */
- public static final String STATUS_CODE = "StatusCode";
-
- /**
- * Application specific response code.
- */
- public static final String RESPONSE_CODE = "ResponseCode";
-
- /**
- * Human-readable description of the application specific response code.
- */
- public static final String RESPONSE_DESCRIPTION = "ResponseDescription";
-
- /**
- * Externally advertised API invoked by clients of this component.
- */
- public static final String ELAPSED_TIME = "ElapsedTime";
-
- /**
- * High level failure (ERROR).
- */
- public static final String ERROR_CATEGORY = "ErrorCategory";
-
- public static final String ERROR_CODE = "ErrorCode";
-
- public static final String ERROR_DESCRIPTION = "ErrorDescription";
-
- public static final String CLASS_NAME = "ClassName";
-
- public static final String SERVER_NAME = "ServerName";
-
- public static final String INVOCATION_ID = "InvocationID";
-}
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
deleted file mode 100644
index 662ca764..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/eelf/PolicyLogger.java
+++ /dev/null
@@ -1,1423 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
-import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
-import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
-import static com.att.eelf.configuration.Configuration.MDC_REMOTE_HOST;
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.BEGIN_TIME_STAMP;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ELAPSED_TIME;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.END_TIME_STAMP;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_CATEGORY;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_CODE;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.ERROR_DESCRIPTION;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.INVOCATION_ID;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.PARTNER_NAME;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_CODE;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_DESCRIPTION;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.SERVER_NAME;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CODE;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.TARGET_ENTITY;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.TARGET_SERVICE_NAME;
-import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayErrorMessage;
-
-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.UUID;
-import java.util.concurrent.ConcurrentMap;
-import java.util.function.Consumer;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.logging.OnapLoggingUtils;
-import org.onap.policy.common.logging.flexlogger.LoggerType;
-import org.slf4j.MDC;
-
-/**
- * PolicyLogger contains all the static methods for EELF logging.
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class PolicyLogger {
-
- private static EELFLogger errorLogger = EELFManager.getErrorLogger();
-
- private static EELFLogger metricsLogger = EELFManager.getMetricsLogger();
-
- private static EELFLogger auditLogger = EELFManager.getAuditLogger();
-
- private static EELFLogger debugLogger = EELFManager.getDebugLogger();
-
- private static final String POLICY_LOGGER = "PolicyLogger";
-
- private static EventTrackInfo eventTracker = new EventTrackInfo();
-
- private static String hostName = null;
- private static String hostAddress = null;
- private static String component = 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 timerDelayTime = 1000;
-
- // Default:Timer scheduleAtFixedRate period - time in milliseconds between successive task
- // executions
- private static int checkInterval = 30 * 1000;
-
- // Default:longest time an event info can be stored in the concurrentHashMap for logging - in
- // seconds
- static int expiredTime = 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 concurrentHashMapLimit = 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 stopCheckPoint = 2500;
-
- @Getter
- @Setter
- private static boolean overrideLogbackLevel = false;
-
- private static Level debugLevel = Level.INFO;
- private static Level auditLevel = Level.INFO;
- private static Level metricsLevel = Level.INFO;
- private static Level errorLevel = Level.ERROR;
- private static String classNameProp = "ClassName";
-
- private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS+00:00";
- private static final String COMPLETE_STATUS = "COMPLETE";
- private static final String ERROR_CATEGORY_VALUE = "ERROR";
-
- static {
- if (hostName == null || hostAddress == null) {
- try {
- hostName = InetAddress.getLocalHost().getHostName();
- hostAddress = InetAddress.getLocalHost().getHostAddress();
- } catch (UnknownHostException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER, "UnknownHostException");
- }
- }
- }
-
- public static synchronized Level getDebugLevel() {
- return debugLevel;
- }
-
- public static synchronized void setDebugLevel(Level level) {
- debugLevel = level;
- }
-
- /**
- * Sets Debug Level.
- */
- public static synchronized void setDebugLevel(String newDebugLevel) {
-
- if (overrideLogbackLevel) {
- PolicyLogger.debugLevel = Level.valueOf(newDebugLevel);
- debugLogger.setLevel(debugLevel);
- }
-
- }
-
- public static synchronized Level getAuditLevel() {
- return auditLevel;
- }
-
- public static synchronized void setAuditLevel(Level level) {
- auditLevel = level;
- }
-
- /**
- * Sets Audit OFF or ON.
- */
- public static synchronized void setAuditLevel(String newAuditLevel) {
-
- if (overrideLogbackLevel) {
- if ("OFF".equalsIgnoreCase(newAuditLevel)) {
- PolicyLogger.auditLevel = Level.OFF;
- auditLogger.setLevel(auditLevel);
- } else {
- // --- set default value
- auditLogger.setLevel(Level.INFO);
- PolicyLogger.auditLevel = Level.INFO;
- }
- }
- }
-
- public static synchronized Level getMetricsLevel() {
- return metricsLevel;
- }
-
- public static synchronized void setMetricsLevel(Level level) {
- metricsLevel = level;
- }
-
- /**
- * Sets Metrics OFF or ON.
- */
- public static synchronized void setMetricsLevel(String newMetricsLevel) {
-
- if (overrideLogbackLevel) {
- if ("OFF".equalsIgnoreCase(newMetricsLevel)) {
- PolicyLogger.metricsLevel = Level.OFF;
- metricsLogger.setLevel(metricsLevel);
- } else {
- // --- set default value
- metricsLogger.setLevel(Level.INFO);
- PolicyLogger.metricsLevel = Level.INFO;
- }
- }
-
- }
-
- public static synchronized Level getErrorLevel() {
- return errorLevel;
- }
-
- public static synchronized void setErrorLevel(Level level) {
- errorLevel = level;
- }
-
- /**
- * Sets Error OFF or ON.
- */
- public static synchronized void setErrorLevel(String newErrorLevel) {
-
- if (overrideLogbackLevel) {
- if ("OFF".equalsIgnoreCase(newErrorLevel)) {
- PolicyLogger.errorLevel = Level.OFF;
- errorLogger.setLevel(errorLevel);
- } else {
- // --- set default value
- errorLogger.setLevel(Level.ERROR);
- PolicyLogger.errorLevel = Level.ERROR;
- }
- }
- }
-
- public static synchronized String getClassname() {
- return classNameProp;
- }
-
- public static synchronized void setClassname(String name) {
- classNameProp = name;
- }
-
- /**
- * Populates MDC info.
- *
- * @param transId the transaction ID
- * @return String
- */
- public static String postMdcInfoForEvent(String transId) {
- MDC.clear();
-
- String transactionId = transId;
-
- if (transactionId == null || transactionId.isEmpty()) {
- transactionId = UUID.randomUUID().toString();
- }
-
- if ("DROOLS".equalsIgnoreCase(component)) {
- MDC.put(TARGET_ENTITY, "POLICY");
- MDC.put(TARGET_SERVICE_NAME, "drools evaluate rule");
- return postMdcInfoForEvent(transactionId, 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, transactionId);
- MDC.put(MDC_SERVICE_NAME, "Policy.xacmlPdp");
- MDC.put(MDC_SERVICE_INSTANCE_ID, "Policy.xacmlPdp.event");
-
- setMdcHostInfo();
- seTimeStamps();
-
- return transactionId;
- }
-
- /**
- * Populate MDC Info using the passed in mdcInfo.
- *
- * @param transId the transaction ID
- * @param mdcInfo the MDC info
- * @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()) {
-
- ConcurrentMap<String, String> mdcMap = mdcInfo.getMdcInfo();
- Iterator<String> keyIterator = mdcMap.keySet().iterator();
- String key;
-
- while (keyIterator.hasNext()) {
- key = keyIterator.next();
- MDC.put(key, mdcMap.get(key));
- }
- }
-
- setMdcHostInfo();
-
- var startTime = Instant.now();
- var endTime = Instant.now();
-
- seTimeStamps(startTime, endTime);
-
- return transId;
- }
-
- /**
- * Sets transaction Id to MDC.
- *
- * @param eventObject event object
- */
- public static void postMdcInfoForEvent(Object eventObject) {
- postMdcInfoForEvent("" + eventObject);
- }
-
- private static void setMdcHostInfo() {
- try {
- MDC.put(MDC_SERVER_FQDN, hostName);
- MDC.put(MDC_SERVER_IP_ADDRESS, hostAddress);
- } catch (Exception e) {
- errorLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICY_LOGGER);
- }
- }
-
- /**
- * Set Timestamps for start, end and duration of logging a transaction.
- */
- private static void seTimeStamps() {
- MDC.put(MDC_INSTANCE_UUID, "");
- MDC.put(MDC_ALERT_SEVERITY, "");
-
- var startTime = Instant.now();
- var endTime = Instant.now();
-
- seTimeStamps(startTime, endTime);
-
- MDC.put(PARTNER_NAME, "N/A");
-
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- MDC.put(RESPONSE_CODE, "N/A");
- MDC.put(RESPONSE_DESCRIPTION, "N/A");
-
- }
-
- private static void seTimeStamps(Instant startTime, Instant endTime) {
- var sdf = new SimpleDateFormat(DATE_FORMAT);
-
- 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(Duration.between(startTime, endTime).toMillis()));
- }
-
- /**
- * Sets transaction Id to MDC.
- *
- * @param transId the transaction ID
- */
- 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);
- }
-
- /**
- * Resets transaction Id in MDC for the rule triggered by this event.
- *
- * @param transId the transaction ID
- * @return String
- */
- public static String postMdcInfoForTriggeredRule(String transId) {
-
- String transactionId = transId;
-
- MDC.clear();
-
- if (transactionId == null || transactionId.isEmpty()) {
- transactionId = UUID.randomUUID().toString();
- }
- MDC.put(MDC_REMOTE_HOST, "");
- MDC.put(MDC_KEY_REQUEST_ID, transactionId);
- MDC.put(MDC_SERVICE_NAME, "Policy.droolsPdp");
- MDC.put(MDC_SERVICE_INSTANCE_ID, "");
- setMdcHostInfo();
- MDC.put(MDC_INSTANCE_UUID, "");
- MDC.put(MDC_ALERT_SEVERITY, "");
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
-
- return transactionId;
-
- }
-
- /**
- * Resets transaction Id in MDC for the rule triggered by this event.
- *
- * @param obj object
- */
- public static void postMdcUuidForTriggeredRule(Object obj) {
-
- postMdcInfoForTriggeredRule("" + obj);
-
- }
-
- // ************************************************************************************************
- /**
- * Records the Info event with String [] arguments.
- *
- * @param msg the message code
- * @param className the class name
- * @param arguments the messages
- */
- public static void info(MessageCodes msg, String className, String... arguments) {
- MDC.put(classNameProp, className);
- debugLogger.info(msg, arguments);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void info(Object arg0) {
- MDC.put(classNameProp, "");
- debugLogger.info(MessageCodes.GENERAL_INFO, String.valueOf(arg0));
- }
-
- /**
- * Records a message with passed in message code, Throwable object, a list of string values.
- *
- * @param msg the message code
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void info(MessageCodes msg, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, "");
- 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 the message code
- * @param className the class name
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void info(MessageCodes msg, String className, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, className);
- String arguments2 = getNormalizedStackTrace(arg0, arguments);
- debugLogger.info(msg, arguments2);
- }
-
- /**
- * Records a message with passed in message text and variable number of arguments.
- *
- * @param message class name if one argument, otherwise message text
- * @param arguments variable number of arguments
- */
- public static void info(String message, Object... arguments) {
- if (!debugLogger.isInfoEnabled()) {
- return;
- }
- if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
- MDC.put(classNameProp, message);
- debugLogger.info(MessageCodes.GENERAL_INFO,
- arguments[0] == null ? "" : arguments[0].toString());
- return;
- }
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
- debugLogger.info(MessageCodes.GENERAL_INFO, message + arguments2);
- return;
- }
-
- MDC.put(classNameProp, "");
- debugLogger.info(message, arguments);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void warn(Object arg0) {
- MDC.put(classNameProp, "");
- debugLogger.warn(MessageCodes.GENERAL_WARNING, "" + arg0);
- }
-
- /**
- * Records only one String message without its class name passed in.
- *
- * @param arg0 the message
- */
- public static void warn(String arg0) {
- MDC.put(classNameProp, "");
- debugLogger.warn(MessageCodes.GENERAL_WARNING, arg0);
- }
-
- /**
- * Records a message with passed in message code, class name and a list of string values.
- *
- * @param msg the message code
- * @param className the class name
- * @param arguments the messages
- */
- public static void warn(MessageCodes msg, String className, String... arguments) {
- MDC.put(classNameProp, className);
- debugLogger.warn(msg, arguments);
- }
-
- /**
- * Records a message with passed in message code, Throwable object, a list of string values.
- *
- * @param msg the message code
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void warn(MessageCodes msg, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, "");
- 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 the message code
- * @param className the class name
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void warn(MessageCodes msg, String className, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, className);
- String arguments2 = getNormalizedStackTrace(arg0, arguments);
- debugLogger.warn(msg, arguments2);
- }
-
- /**
- * Records a message with passed in message text and variable number of arguments.
- *
- * @param message class name if one argument, otherwise message text
- * @param arguments variable number of arguments
- */
- public static void warn(String message, Object... arguments) {
- if (!debugLogger.isWarnEnabled()) {
- return;
- }
- if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
- MDC.put(classNameProp, message);
- debugLogger.warn(MessageCodes.GENERAL_INFO,
- arguments[0] == null ? "" : arguments[0].toString());
- return;
- }
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
- debugLogger.warn(MessageCodes.GENERAL_INFO, message + arguments2);
- return;
- }
- MDC.put(classNameProp, "");
- debugLogger.warn(message, arguments);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void error(String arg0) {
- MDC.put(classNameProp, "");
- setErrorCode(MessageCodes.GENERAL_ERROR);
- errorLogger.error(MessageCodes.GENERAL_ERROR, arg0);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void error(Object arg0) {
- MDC.put(classNameProp, "");
- setErrorCode(MessageCodes.GENERAL_ERROR);
- errorLogger.error(MessageCodes.GENERAL_ERROR, "" + arg0);
- }
-
- /**
- * Records a message with passed in message code, Throwable object, a list of string values.
- *
- * @param msg the message code
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void error(MessageCodes msg, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, "");
- setErrorCode(msg);
- 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 the message code
- * @param className the class name
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void error(MessageCodes msg, String className, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, className);
- setErrorCode(msg);
- 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 the message code
- * @param arguments the messages
- */
- public static void error(MessageCodes msg, String... arguments) {
- MDC.put(classNameProp, "");
- setErrorCode(msg);
- errorLogger.error(msg, arguments);
- }
-
- /**
- * Records a message with passed in message text and variable number of arguments.
- *
- * @param message class name if one argument, otherwise message text
- * @param arguments variable number of arguments
- */
- public static void error(String message, Object... arguments) {
- if (!errorLogger.isErrorEnabled()) {
- return;
- }
- if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
- MDC.put(classNameProp, message);
- setErrorCode(MessageCodes.GENERAL_ERROR);
- errorLogger.error(MessageCodes.GENERAL_ERROR,
- arguments[0] == null ? "" : arguments[0].toString());
- return;
- }
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
- errorLogger.error(MessageCodes.GENERAL_ERROR, message + arguments2);
- return;
- }
- MDC.put(classNameProp, "");
- setErrorCode(MessageCodes.GENERAL_ERROR);
- errorLogger.error(message, arguments);
- }
-
- /**
- * Records a message with passed in message code and a list of string values.
- *
- * @param msg the message code
- * @param arguments the messages
- */
- public static void debug(MessageCodes msg, String... arguments) {
- MDC.put(classNameProp, "");
- debugLogger.debug(msg, arguments);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void debug(String arg0) {
- MDC.put(classNameProp, "");
- debugLogger.debug(arg0);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void debug(Object arg0) {
-
- MDC.put(classNameProp, "");
- debugLogger.debug("{}", arg0);
- }
-
- /**
- * Records a message with passed in message code, hrowable object, a list of string values.
- *
- * @param msg the message code
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void debug(MessageCodes msg, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, "");
- String arguments2 = getNormalizedStackTrace(arg0, arguments);
- debugLogger.debug(msg, arguments2);
- }
-
- /**
- * Records a message with passed in message code, class name, Throwable object, a list of
- * string. values
- *
- * @param msg the message code
- * @param className the class name
- * @param arg0 the throwable
- * @param arguments the messages
- */
- public static void debug(MessageCodes msg, String className, Throwable arg0, String... arguments) {
- MDC.put(classNameProp, className);
- String arguments2 = getNormalizedStackTrace(arg0, arguments);
- debugLogger.debug(msg, arguments2);
- }
-
- /**
- * Records a message with passed in message text and variable number of arguments.
- *
- * @param message class name if one argument, otherwise message text
- * @param arguments variable number of arguments
- */
- public static void debug(String message, Object... arguments) {
- if (!debugLogger.isDebugEnabled()) {
- return;
- }
- if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
- MDC.put(classNameProp, message);
- debugLogger.debug(MessageCodes.GENERAL_INFO,
- arguments[0] == null ? "" : arguments[0].toString());
- return;
- }
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
- debugLogger.debug(MessageCodes.GENERAL_INFO, message + arguments2);
- return;
- }
- MDC.put(classNameProp, "");
- debugLogger.debug(message, arguments);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void audit(Object arg0) {
- MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- MDC.put(RESPONSE_CODE, "0");
- MDC.put(classNameProp, "");
- auditLogger.info("{}", arg0);
- }
-
- /**
- * Records a message with passed in message text and variable number of arguments.
- *
- * @param message class name if one argument, otherwise message text
- * @param arguments variable number of arguments
- */
- public static void audit(String message, Object... arguments) {
- if (!auditLogger.isInfoEnabled()) {
- return;
- }
- MDC.put(INVOCATION_ID, postMdcInfoForEvent(null));
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- MDC.put(RESPONSE_CODE, "0");
- if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
- MDC.put(classNameProp, message);
- auditLogger.info("{}", arguments[0] == null ? "" : arguments[0].toString());
- return;
- }
-
- MDC.put(classNameProp, "");
- auditLogger.info(message, arguments);
- }
-
- /**
- * 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 the class name
- * @param arg0 the message
- */
- public static void trace(String className, String arg0) {
- MDC.put(classNameProp, className);
- debugLogger.trace(MessageCodes.GENERAL_INFO, arg0);
- }
-
- /**
- * Records only one String message.
- *
- * @param arg0 the message
- */
- public static void trace(Object arg0) {
-
- MDC.put(classNameProp, "");
- debugLogger.trace("{}", arg0);
- }
-
- /**
- * Records the starting time of the event with its request Id as the key.
- *
- * @param eventId the event ID
- */
- public static void recordAuditEventStart(String eventId) {
-
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- postMdcInfoForEvent(eventId);
-
- if (eventTracker == null) {
- eventTracker = new EventTrackInfo();
- }
- var event = new EventData();
- event.setRequestId(eventId);
- event.setStartTime(Instant.now());
- eventTracker.storeEventData(event);
- MDC.put(MDC_KEY_REQUEST_ID, eventId);
- debugLogger.info("CONCURRENTHASHMAP_LIMIT : {}", concurrentHashMapLimit);
- // --- 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 : {} on {}", size, new Date());
- debugLogger.info("isEventTrackerRunning : {}", isEventTrackerRunning);
-
- if (size >= concurrentHashMapLimit) {
-
-
- if (!isEventTrackerRunning) {
-
- startCleanUp();
- isEventTrackerRunning = true;
- }
-
- } else if (size <= stopCheckPoint && isEventTrackerRunning) {
-
- stopCleanUp();
- }
- }
-
- /**
- * Records the starting time of the event with its request Id as the key.
- *
- * @param eventId the event ID
- */
- 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 the event ID
- * @param rule the 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 the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- 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 the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- 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 the event ID
- * @param rule the 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 the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- public static void creatAuditEventTrackingRecord(String eventId, String rule, String policyVersion) {
-
- if (eventTracker == null) {
- return;
- }
-
- var event = eventTracker.getEventDataByRequestId(eventId);
-
- if (event != null) {
- Instant endTime = event.getEndTime();
- if (endTime == null) {
- endTime = Instant.now();
- }
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- recordAuditEventStartToEnd(eventId, rule, event.getStartTime(), endTime, policyVersion);
- }
- }
-
- /**
- * Records the ending time of the event with its request Id as the key.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- public static void creatAuditEventTrackingRecord(UUID eventId, String rule) {
-
- if (eventId == null) {
- return;
- }
-
- if (eventTracker == null) {
- return;
- }
-
- var 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 the event ID
- * @param rule the rule
- * @param startTime the start time
- * @param endTime the end time
- * @param policyVersion the policy version
- */
- public static void recordAuditEventStartToEnd(String eventId, String rule, Instant startTime, Instant endTime,
- String policyVersion) {
-
- if (startTime == null || endTime == null) {
- return;
- }
- if (eventId != null && !eventId.isEmpty()) {
- MDC.put(MDC_KEY_REQUEST_ID, eventId);
- }
-
- seTimeStamps(startTime, endTime);
-
- MDC.put(RESPONSE_CODE, "N/A");
- MDC.put(RESPONSE_DESCRIPTION, "N/A");
-
- long ns = Duration.between(startTime, endTime).toMillis();
-
- auditLogger.info(MessageCodes.RULE_AUDIT_START_END_INFO, MDC.get(MDC_SERVICE_NAME), rule, startTime.toString(),
- endTime.toString(), Long.toString(ns), policyVersion);
-
- // --- remove the record from the concurrentHashMap
- if (eventTracker != null && eventTracker.getEventDataByRequestId(eventId) != null) {
-
- eventTracker.remove(eventId);
- debugLogger.info("eventTracker.remove({})", eventId);
-
- }
- }
-
- /**
- * Records the metrics with an event Id and log message.
- *
- * @param eventId the event ID
- * @param arg1 the message
- */
- public static void recordMetricEvent(String eventId, String arg1) {
-
- seTimeStamps();
-
- String serviceName = MDC.get(MDC_SERVICE_NAME);
- MDC.put(MDC_KEY_REQUEST_ID, eventId);
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, serviceName, arg1);
-
- }
-
- /**
- * Records the metrics with an event Id, class name and log message.
- *
- * @param eventId the event ID
- * @param className the class name
- * @param arg1 the message
- */
- public static void recordMetricEvent(String eventId, String className, String arg1) {
-
- seTimeStamps();
-
- MDC.put(classNameProp, className);
- String serviceName = MDC.get(MDC_SERVICE_NAME);
- MDC.put(MDC_KEY_REQUEST_ID, eventId);
- MDC.put(STATUS_CODE, COMPLETE_STATUS);
- metricsLogger.info(MessageCodes.RULE_AUDIT_END_INFO, serviceName, arg1);
- }
-
- /**
- * Records the metrics with an event Id and log message.
- *
- * @param eventId the event ID
- * @param arg1 the message
- */
- 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 the message
- */
- 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 the message
- */
- public static void metrics(String arg0) {
- seTimeStamps();
- MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
- MDC.put(RESPONSE_CODE, "0");
- 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 the message
- */
- public static void metrics(Object arg0) {
- seTimeStamps();
- MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
- MDC.put(RESPONSE_CODE, "0");
- MDC.put(classNameProp, "");
- String serviceName = MDC.get(MDC_SERVICE_NAME);
- metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName, "" + arg0);
- }
-
- /**
- * Records a message with passed in message text and variable number of arguments.
- *
- * @param message class name if one argument, otherwise message text
- * @param arguments variable number of arguments
- */
- public static void metrics(String message, Object... arguments) {
- if (!metricsLogger.isInfoEnabled()) {
- return;
- }
- seTimeStamps();
- MDC.put(INVOCATION_ID, MDC.get(MDC_KEY_REQUEST_ID));
- MDC.put(RESPONSE_CODE, "0");
- if (arguments.length == 1 && !OnapLoggingUtils.isThrowable(arguments[0])) {
- MDC.put(classNameProp, message);
- String serviceName = MDC.get(MDC_SERVICE_NAME);
- metricsLogger.info(MessageCodes.RULE_METRICS_INFO, serviceName,
- arguments[0] == null ? "" : arguments[0].toString());
- return;
- }
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- String arguments2 = getNormalizedStackTrace((Throwable) arguments[0], "");
- metricsLogger.info(MessageCodes.RULE_METRICS_INFO, message + arguments2);
- return;
- }
-
- MDC.put(classNameProp, "");
- metricsLogger.info(message, arguments);
- }
-
- /**
- * Records the metrics event with a String message.
- *
- * @param arg0 the message
- */
- public static void metricsPrintln(String arg0) {
- MDC.clear();
- metricsLogger.info(arg0);
- }
-
- /**
- * Removes all the return lines from the printStackTrace.
- *
- * @param throwable the throwable
- * @param arguments the messages
- */
- private static String getNormalizedStackTrace(Throwable throwable, String... arguments) {
- var sw = new StringWriter();
- var pw = new PrintWriter(sw);
- throwable.printStackTrace(pw);
- String newStValue = sw.toString().replace('|', '!').replace("\n", " - ");
- int curSize = arguments == null ? 0 : arguments.length;
- var newArgument = new StringBuilder();
- for (var i = 0; i < curSize; i++) {
- newArgument.append(arguments[i]);
- newArgument.append(":");
- }
- newArgument.append(newStValue);
- return newArgument.toString();
- }
-
- /**
- * Starts the process of cleaning up the ConcurrentHashMap of EventData.
- */
- private static void startCleanUp() {
-
- if (!isEventTrackerRunning) {
- var ttrcker = new EventTrackInfoHandler();
- timer = new Timer(true);
- timer.scheduleAtFixedRate(ttrcker, timerDelayTime, checkInterval);
- debugLogger.info("EventTrackInfoHandler begins! : {}", new Date());
- } else {
- debugLogger.info("Timer is still running : {}", new Date());
-
- }
- }
-
-
- /**
- * Stops the process of cleaning up the ConcurrentHashMap of EventData.
- */
- private static void stopCleanUp() {
-
- if (isEventTrackerRunning && timer != null) {
- timer.cancel();
- timer.purge();
- debugLogger.info("Timer stopped: {}", new Date());
- } else {
- debugLogger.info("Timer was already stopped : {}", new Date());
-
- }
- isEventTrackerRunning = false;
-
- }
-
- /**
- * Loads all the attributes from policyLogger.properties file
- */
- public static LoggerType init(Properties properties) {
-
- var loggerProperties = getLoggerProperties(properties);
-
- // fetch and verify definitions of some properties
- try {
- setOverrideLogbackLevels(loggerProperties);
-
- setLoggerLevel(loggerProperties, "debugLogger.level", "INFO", PolicyLogger::setDebugLevel);
-
- // Only check if it is to turn on or off
- setLoggerOnOff(loggerProperties, "metricsLogger.level", PolicyLogger::setMetricsLevel);
- setLoggerOnOff(loggerProperties, "audit.level", PolicyLogger::setAuditLevel);
- setLoggerOnOff(loggerProperties, "error.level", PolicyLogger::setErrorLevel);
-
- isEventTrackerRunning = false;
-
- timerDelayTime = getIntProp(loggerProperties, "timer.delay.time", timerDelayTime);
- checkInterval = getIntProp(loggerProperties, "check.interval", checkInterval);
- expiredTime = getIntProp(loggerProperties, "event.expired.time", expiredTime);
- concurrentHashMapLimit = getIntProp(loggerProperties, "concurrentHashMap.limit", concurrentHashMapLimit);
- stopCheckPoint = getIntProp(loggerProperties, "stop.check.point", stopCheckPoint);
-
- component = loggerProperties.getProperty("policy.component", "DROOLS");
- debugLogger.info("component: {}", component);
-
- return detmLoggerType(loggerProperties);
-
- } catch (Exception e) {
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
-
- if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc());
-
- }
- errorLogger.error("failed to get the policyLogger.properties, so use their default values", e);
-
- return LoggerType.EELF;
- }
-
- }
-
- private static int getIntProp(Properties properties, String propName, int defaultValue) {
- final var propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
-
- debugLogger.info("{} value: {}", propName, propValue);
-
- if (propValue > 0) {
- return propValue;
-
- } else {
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
- if (ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorCode());
- MDC.put(ERROR_DESCRIPTION,
- ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR).getErrorDesc());
-
- }
- errorLogger.error("failed to get the {}, so use its default value: {}", propName, defaultValue);
- return defaultValue;
- }
- }
-
- private static Properties getLoggerProperties(Properties properties) {
- if (properties != null) {
- return properties;
- } else {
- displayErrorMessage("PolicyLogger cannot find its configuration - continue");
- return new Properties();
- }
- }
-
- private static void setLoggerLevel(Properties properties, String propName, String defaultValue,
- Consumer<String> setter) {
-
- final String propValue = properties.getProperty(propName, defaultValue);
-
- if (!StringUtils.isBlank(propValue)) {
- debugLogger.info("{} level: {}", propName, propValue);
- }
-
- setter.accept(propValue);
- }
-
- private static void setLoggerOnOff(Properties properties, String propName, Consumer<String> setter) {
- final String propValue = properties.getProperty(propName, "ON");
-
- if (Level.OFF.toString().equalsIgnoreCase(propValue)) {
- debugLogger.info("{} level: {}", propName, propValue);
- }
-
- setter.accept(propValue);
- }
-
- private static void setOverrideLogbackLevels(Properties loggerProperties) {
- final var overrideLogbackLevelText = loggerProperties.getProperty("override.logback.level.setup");
-
- if (!StringUtils.isBlank(overrideLogbackLevelText)) {
- overrideLogbackLevel = "TRUE".equalsIgnoreCase(overrideLogbackLevelText);
- }
- }
-
- private static LoggerType detmLoggerType(Properties loggerProperties) {
- final String loggerTypeProp = loggerProperties.getProperty("logger.type", LoggerType.EELF.toString());
- debugLogger.info("loggerType value: {}", loggerTypeProp);
-
- switch (loggerTypeProp.toUpperCase()) {
- case "EELF":
- return LoggerType.EELF;
- case "SYSTEMOUT":
- return LoggerType.SYSTEMOUT;
-
- default:
- return LoggerType.EELF;
- }
- }
-
- /**
- * Sets server information to MDC.
- */
- public static void setServerInfo(String serverHost, String serverPort) {
- MDC.put(SERVER_NAME, serverHost + ":" + serverPort);
- }
-
- /**
- * Sets error category, code and description.
- */
- private static void setErrorCode(MessageCodes errcode) {
- MDC.put(ERROR_CATEGORY, ERROR_CATEGORY_VALUE);
- if (ErrorCodeMap.getErrorCodeInfo(errcode) != null) {
- MDC.put(ERROR_CODE, ErrorCodeMap.getErrorCodeInfo(errcode).getErrorCode());
- MDC.put(ERROR_DESCRIPTION, ErrorCodeMap.getErrorCodeInfo(errcode).getErrorDesc());
- } else {
- MDC.put(ERROR_CODE,
- ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_UNKNOWN).getErrorCode());
- MDC.put(ERROR_DESCRIPTION,
- ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_UNKNOWN).getErrorDesc());
- }
- }
-}
diff --git a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java
deleted file mode 100644
index 425c62a4..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/DisplayUtils.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-/**
- * Utilities to display messages. These are generally used while logging is being
- * configured, or when logging being directed to System.out. As a result, it directly
- * writes to System.out rather than to a logger.
- */
-
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class DisplayUtils {
-
- /*
- * As the comment above says, these purposely write to System.out rather than a
- * logger, thus sonar is disabled.
- */
-
- public static void displayMessage(Object message) {
- System.out.println(message); // NOSONAR
- }
-
- public static void displayErrorMessage(Object msg) {
- System.err.println(msg); // NOSONAR
- }
-}
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
deleted file mode 100644
index 0e0ef2bf..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/EelfLogger.java
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import com.att.eelf.configuration.EELFLogger.Level;
-import java.io.Serializable;
-import java.util.UUID;
-import lombok.Getter;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-
-/**
- * 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 = "";
- @Getter
- private String transId = UUID.randomUUID().toString();
-
- /**
- * Constructor.
- *
- * @param clazz the class
- */
- public EelfLogger(Class<?> clazz) {
- if (clazz != null) {
- className = clazz.getName();
- }
- PolicyLogger.postMdcInfoForEvent(null);
- }
-
- /**
- * Constructor.
- *
- * @param className the class name
- */
- public EelfLogger(String className) {
- if (className != null) {
- this.className = className;
- }
- PolicyLogger.postMdcInfoForEvent(null);
- }
-
- /**
- * Constructor.
- *
- * @param clazz the class
- * @param isNewTransaction is a new transaction
- */
- public EelfLogger(Class<?> clazz, boolean isNewTransaction) {
- if (clazz != null) {
- className = clazz.getName();
- }
- if (isNewTransaction) {
- transId = PolicyLogger.postMdcInfoForEvent(null);
- } else {
- transId = PolicyLogger.getTransId();
- }
- }
-
- /**
- * Constructor.
- *
- * @param className the class name
- * @param isNewTransaction is a new transaction
- */
- public EelfLogger(String className, boolean isNewTransaction) {
- if (className != null) {
- this.className = className;
- }
- if (isNewTransaction) {
- transId = PolicyLogger.postMdcInfoForEvent(null);
- } else {
- transId = PolicyLogger.getTransId();
- }
- }
-
- /**
- * Constructor.
- *
- * @param clazz the class
- * @param transId the transaction ID
- */
- public EelfLogger(Class<?> clazz, String transId) {
- if (clazz != null) {
- className = clazz.getName();
- }
- PolicyLogger.postMdcInfoForEvent(transId);
- this.transId = transId;
- }
-
- /**
- * Constructor.
- *
- * @param className the class name
- * @param transId the transaction ID
- */
- public EelfLogger(String className, String transId) {
- if (className != null) {
- this.className = className;
- }
- PolicyLogger.postMdcInfoForEvent(transId);
- this.transId = transId;
- }
-
- /**
- * Sets transaction Id for logging.
- *
- * @param transId the transaction ID
- */
- @Override
- public void setTransId(String transId) {
-
- PolicyLogger.setTransId(transId);
- this.transId = transId;
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void debug(Object message) {
- PolicyLogger.debug(className, "" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void debug(Object message, Throwable throwable) {
- PolicyLogger.debug(MessageCodes.GENERAL_INFO, throwable, message.toString());
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments the arguments for message
- */
- @Override
- public void debug(String message, Object... arguments) {
- PolicyLogger.debug(message, arguments);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- */
- @Override
- public void error(Object message) {
- PolicyLogger.error(className, "" + message);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void error(Object message, Throwable throwable) {
- PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, throwable, message.toString());
- }
-
- /**
- * Records an error message.
- *
- * @param msg the message code
- * @param throwable the throwable
- * @param arguments the messages
- */
- @Override
- public void error(MessageCodes msg, Throwable throwable, String... arguments) {
- PolicyLogger.error(msg, className, throwable, arguments);
- }
-
- /**
- * Records an error message.
- *
- * @param msg the message code
- * @param arguments the messages
- */
- @Override
- public void error(MessageCodes msg, String... arguments) {
- PolicyLogger.error(msg, arguments);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- * @param arguments the arguments for message
- */
- @Override
- public void error(String message, Object... arguments) {
- PolicyLogger.error(message, arguments);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void info(Object message) {
- PolicyLogger.info(className, "" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void info(Object message, Throwable throwable) {
- PolicyLogger.info(MessageCodes.GENERAL_INFO, throwable, message.toString());
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments the arguments for message
- */
- @Override
- public void info(String message, Object... arguments) {
- PolicyLogger.info(message, arguments);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void warn(Object message) {
- PolicyLogger.warn(className, "" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void warn(Object message, Throwable throwable) {
- PolicyLogger.warn(MessageCodes.GENERAL_WARNING, throwable, message.toString());
- }
-
- /**
- * Records a message.
- *
- * @param msg the message codes
- * @param arguments the messages
- */
- @Override
- public void warn(MessageCodes msg, String... arguments) {
- PolicyLogger.warn(msg, className, arguments);
- }
-
- /**
- * Records a message.
- *
- * @param msg the message
- * @param throwable the throwable
- * @param arguments the messages
- */
- @Override
- public void warn(MessageCodes msg, Throwable throwable, String... arguments) {
- PolicyLogger.warn(msg, className, throwable, arguments);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments the arguments for message
- */
- @Override
- public void warn(String message, Object... arguments) {
- PolicyLogger.warn(message, arguments);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void trace(Object message) {
- PolicyLogger.trace(className, "" + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void trace(Object message, Throwable throwable) {
- PolicyLogger.trace(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() {
- return (PolicyLogger.getAuditLevel() != Level.OFF);
- }
-
- /**
- * Returns true for metrics enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isMetricsEnabled() {
- return (PolicyLogger.getMetricsLevel() != Level.OFF);
- }
-
- /**
- * Returns true for trace enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isTraceEnabled() {
- return PolicyLogger.isDebugEnabled();
- }
-
- /**
- * Records an audit message.
- *
- * @param arg0 the message
- */
- @Override
- public void audit(Object arg0) {
- PolicyLogger.audit(className, "" + arg0);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void audit(Object message, Throwable throwable) {
- PolicyLogger.audit(message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments the arguments for message
- */
- @Override
- public void audit(String message, Object... arguments) {
- PolicyLogger.audit(message, arguments);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(String eventId) {
- PolicyLogger.recordAuditEventStart(eventId);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(UUID eventId) {
- PolicyLogger.recordAuditEventStart(eventId);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- * @param policyVersion the policy cersion
- */
- @Override
- public void recordAuditEventEnd(String eventId, String rule, String policyVersion) {
- PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- @Override
- public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) {
- PolicyLogger.recordAuditEventEnd(eventId, rule, policyVersion);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- @Override
- public void recordAuditEventEnd(String eventId, String rule) {
- PolicyLogger.recordAuditEventEnd(eventId, rule);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- @Override
- public void recordAuditEventEnd(UUID eventId, String rule) {
- PolicyLogger.recordAuditEventEnd(eventId, rule);
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(String eventId, String message) {
- PolicyLogger.recordMetricEvent(eventId, message);
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(UUID eventId, String message) {
- PolicyLogger.recordMetricEvent(eventId, message);
- }
-
- /**
- * Records a metrics message.
- *
- * @param message the message
- */
- @Override
- public void metrics(Object message) {
- PolicyLogger.metrics(className, message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments the arguments for message
- */
- @Override
- public void metrics(String message, Object... arguments) {
- PolicyLogger.metrics(message, arguments);
- }
-
- /**
- * Populates MDC Info.
- *
- * @param transId the transaction ID
- */
- @Override
- public String postMdcInfoForEvent(String transId) {
- return PolicyLogger.postMdcInfoForEvent(transId);
- }
-
- /**
- * Populates MDC Info.
- *
- * @param obj the object
- */
- @Override
- public void postMdcInfoForEvent(Object obj) {
- PolicyLogger.postMdcInfoForEvent(obj);
- }
-
- /**
- * Populates MDC Info for the rule triggered.
- *
- * @param transId the transaction ID
- */
- @Override
- public void postMdcInfoForTriggeredRule(String transId) {
- PolicyLogger.postMdcInfoForTriggeredRule(transId);
- }
-
-}
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
deleted file mode 100644
index 7bfcb5d4..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage;
-
-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 {
-
- private static final String GET_LOGGER_PREFIX = "FlexLogger:getLogger : loggerType = ";
- private static LoggerType loggerType = LoggerType.EELF;
- private static ConcurrentHashMap<String, EelfLogger> eelfLoggerMap = new ConcurrentHashMap<>();
- private static ConcurrentHashMap<String, SystemOutLogger> systemOutMap = new ConcurrentHashMap<>();
-
- // --- init logger first
- static {
- loggerType = initLogger();
- }
-
- /**
- * Returns an instance of Logger.
- *
- * @param clazz the class
- */
- public static Logger getLogger(Class<?> clazz) {
- return getLogger(clazz, false);
- }
-
- /**
- * Returns an instance of Logger.
- */
- public static Logger getLogger() {
- return getLogger(null);
- }
-
- /**
- * Returns an instance of Logger.
- *
- * @param clazz the class
- * @param isNewTransaction is a new transaction
- */
- public static Logger getLogger(Class<?> clazz, boolean isNewTransaction) {
- Logger logger;
- displayMessage(GET_LOGGER_PREFIX + loggerType);
- if (loggerType == LoggerType.EELF) {
- logger = getEelfLogger(clazz, isNewTransaction);
- } else {
- logger = getSystemOutLogger();
- }
-
- return logger;
- }
-
- /**
- * Returns an instance of Logger.
- *
- * @param isNewTransaction is a new transaction
- */
- public static Logger getLogger(boolean isNewTransaction) {
- return getLogger(null, isNewTransaction);
- }
-
- /**
- * Returns the calling class name.
- */
- public String getClassName() {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
- if (stackTrace.length > 3) {
- return stackTrace[3].getClassName();
- }
- return "UnknownClass";
- }
-
- /**
- * Returns an instance of EelfLogger.
- *
- * @param clazz the class
- * @param isNewTransaction is a new transaction
- */
- private static EelfLogger getEelfLogger(Class<?> clazz, boolean isNewTransaction) {
-
- String className;
- EelfLogger logger;
- if (clazz != null) {
- className = clazz.getName();
- } else {
- className = new FlexLogger().getClassName();
- }
-
- logger = eelfLoggerMap.computeIfAbsent(className, key -> new EelfLogger(clazz, isNewTransaction));
-
- if (isNewTransaction) {
- String transId = PolicyLogger.postMdcInfoForEvent(null);
- logger.setTransId(transId);
- }
-
- displayMessage("eelfLoggerMap size : " + eelfLoggerMap.size() + " class name: " + className);
- return logger;
- }
-
- /**
- * Returns an instance of SystemOutLogger.
- */
- private static SystemOutLogger getSystemOutLogger() {
-
- String className = new FlexLogger().getClassName();
-
- return systemOutMap.computeIfAbsent(className, SystemOutLogger::new);
- }
-
- /**
- * loads the logger properties.
- */
- private static LoggerType initLogger() {
- var loggerType = LoggerType.EELF;
- Properties properties = null;
-
- try {
- properties = PropertyUtil.getProperties("config/policyLogger.properties");
- displayMessage("FlexLogger:properties => " + properties);
-
- String overrideLogbackLevel = properties.getProperty("override.logback.level.setup");
- displayMessage("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel);
- var loggerTypeString = properties.getProperty("logger.type");
- if ("EELF".equalsIgnoreCase(loggerTypeString) && "TRUE".equalsIgnoreCase(overrideLogbackLevel)) {
- displayMessage("FlexLogger: start listener.");
- properties = PropertyUtil.getProperties("config/policyLogger.properties",
- new PropertiesCallBack("FlexLogger-CallBack"));
- }
- } catch (IOException e1) {
- displayMessage("initLogger" + e1);
- } finally {
- // OK to pass no properties (null)
- loggerType = PolicyLogger.init(properties);
- }
-
- return loggerType;
- }
-
- /**
- * PropertiesCallBack is listening any updates on the policyLogger.properties
- */
- public static 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
- */
- @Override
- public void propertiesChanged(Properties properties, Set<String> 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");
-
- var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
- var startTime = Instant.now();
- String formattedTime = sdf.format(Date.from(startTime));
- displayMessage("FlexLogger.propertiesChanged : called at time : " + formattedTime);
- displayMessage("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/Logger.java b/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java
deleted file mode 100644
index ad155a4c..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/Logger.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2020 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.DEBUG
- */
- public void debug(Object message, Throwable throwable);
-
- /**
- * Prints messages with the level.DEBUG
- */
- public void debug(String message, Object... arguments);
-
- /**
- * Prints messages with the level.ERROR
- */
- public void error(Object message);
-
- /**
- * Prints messages with the level.ERROR
- */
- public void error(Object message, Throwable throwable);
-
- /**
- * Prints messages with the level.ERROR
- */
- public void error(MessageCodes msg, String... arguments);
-
- /**
- * Prints messages with the level.ERROR
- */
- public void error(MessageCodes msg, Throwable arg0, String... arguments);
-
- /**
- * Prints messages with the level.ERROR
- */
- public void error(String message, Object... arguments);
-
- /**
- * Prints messages with the level.INFO
- */
- public void info(Object message);
-
- /**
- * Prints messages with the level.INFO
- */
- public void info(Object message, Throwable throwable);
-
- /**
- * Prints messages with the level.INFO
- */
- public void info(String message, Object... arguments);
-
- /**
- * Prints messages with the level.WARN
- */
- public void warn(Object message);
-
- /**
- * Prints messages with the level.WARN
- */
- public void warn(Object message, Throwable throwable);
-
- /**
- * 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.WARN
- */
- public void warn(String message, Object... arguments);
-
- /**
- * Prints messages with the level.TRACE
- */
- public void trace(Object message);
-
- /**
- * Prints messages with the level.TRACE
- */
- public void trace(Object message, Throwable throwable);
-
- /**
- * Prints messages in audit log with the level.INFO
- */
- public void audit(Object arg0);
-
- /**
- * Prints messages in audit log with the level.INFO
- */
- public void audit(Object arg0, Throwable throwable);
-
- /**
- * Prints messages in audit log with the level.INFO
- */
- public void audit(String message, Object... arguments);
-
- /**
- * 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);
-
- /**
- * Records the Metrics log message.
- */
- public void metrics(String message, Object... arguments);
-
- /**
- * 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);
-
- /**
- * Populates MDC Info.
- */
- public void postMdcInfoForEvent(Object obj);
-
- /**
- * 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);
-
-}
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
deleted file mode 100644
index f73bc4bc..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/LoggerType.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2020 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, 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
deleted file mode 100644
index ef6c2e95..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/PropertyUtil.java
+++ /dev/null
@@ -1,340 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayErrorMessage;
-
-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;
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-/**
- * This class provides utilities to read properties from a properties file, and optionally get
- * notifications of future changes.
- */
-public final class PropertyUtil {
-
-
- @NoArgsConstructor(access = AccessLevel.PRIVATE)
- protected static class LazyHolder {
- /**
- * Timer thread. Will not be allocated by the JVM until it is first referenced.
- * This may be overridden by junit tests.
- */
- private static Timer timer = new Timer("PropertyUtil-Timer", true);
- }
-
- // this table maps canonical file into a 'ListenerRegistration' instance
- private static HashMap<File, ListenerRegistration> registrations = new HashMap<>();
-
- /**
- * 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.
- */
- public static Properties getProperties(File file) throws IOException {
- // create an InputStream (may throw a FileNotFoundException)
- try (var fis = new FileInputStream(file)) {
- // create the properties instance
- var rval = new Properties();
-
- // load properties (may throw an IOException)
- rval.load(fis);
- return rval;
- }
- }
-
- /**
- * 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.
- */
- public static Properties getProperties(String fileName) throws IOException {
- return getProperties(new File(fileName));
- }
-
- /* ============================================================ */
-
- /**
- * This is the callback interface, used for sending notifications of changes in the properties
- * file.
- */
- @FunctionalInterface
- public interface Listener {
- /**
- * Notification of a properties file change.
- *
- * @param properties the new properties
- * @param changedKeys the set of property names that have changed, including additions and
- * removals
- */
- void propertiesChanged(Properties properties, Set<String> changedKeys);
- }
-
- /**
- * 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<Listener> 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);
-
- // create and schedule the timer task, so this is periodically polled
- timerTask = new TimerTask() {
- @Override
- public void run() {
- try {
- poll();
- } catch (Exception e) {
- displayErrorMessage(e);
- }
- }
- };
- LazyHolder.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.isEmpty()) {
- 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.
- var oldProperties = properties;
- HashSet<String> 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<String> 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.isEmpty()) {
- // 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 var tmpProperties = (Properties) (properties.clone());
- final HashSet<String> tmpChangedProperties = new HashSet<>(changedProperties);
-
- // Do the notification in a separate thread, so blocking
- // won't cause any problems.
- new Thread() {
- @Override
- 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 listener 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.
- */
- public static 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.
- var tempFile = 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(tempFile);
- if (reg == null) {
- // a new registration is needed
- reg = new ListenerRegistration(tempFile);
- }
- 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 listener 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.
- */
- public static Properties getProperties(String fileName, Listener listener) throws IOException {
- return getProperties(new File(fileName), listener);
- }
-
- /**
- * Stop listenening for updates.
- *
- * @param file the properties file
- * @param listener notify if not null, this is a callback interface that was used for
- * notifications of changes
- * @throws IOException If an I/O error occurs
- */
- public static void stopListening(File file, Listener listener) throws IOException {
- if (listener != null) {
- ListenerRegistration reg = registrations.get(file.getCanonicalFile());
- if (reg != null) {
- reg.removeListener(listener);
- }
- }
- }
-
- /**
- * Stop listenening for updates.
- *
- * @param fileName the properties file
- * @param listener notify if not null, this is a callback interface that was used for
- * notifications of changes
- * @throws IOException If an I/O error occurs
- */
- public static void stopListening(String fileName, Listener listener) throws IOException {
- stopListening(new File(fileName), listener);
- }
-
-}
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
deleted file mode 100644
index d16a1d7a..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/SystemOutLogger.java
+++ /dev/null
@@ -1,548 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import static org.onap.policy.common.logging.flexlogger.DisplayUtils.displayMessage;
-
-import com.att.eelf.configuration.EELFLogger.Level;
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.UUID;
-import lombok.Getter;
-import org.onap.policy.common.logging.OnapLoggingUtils;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-
-/**
- * SystemOutLogger implements all the methods of interface Logger by calling System.out.println
- */
-@Getter
-public class SystemOutLogger implements Logger, Serializable {
-
- private static final long serialVersionUID = 4956408061058933929L;
- private String className = "";
- private boolean debugEnabled = true;
- private boolean infoEnabled = true;
- private boolean warnEnabled = true;
- private boolean errorEnabled = true;
- private boolean auditEnabled = true;
- private boolean metricsEnabled = true;
- private String transId = UUID.randomUUID().toString();
-
- /**
- * Constructor.
- *
- * @param clazz the class
- */
- public SystemOutLogger(Class<?> clazz) {
- displayMessage("create instance of SystemOutLogger");
- if (clazz != null) {
- className = clazz.getName();
- }
- initLevel();
- }
-
- /**
- * Constructor.
- *
- * @param className the class name
- */
- public SystemOutLogger(String className) {
- displayMessage("create instance of SystemOutLogger");
- if (className != null) {
- this.className = className;
- }
- initLevel();
- }
-
- /**
- * Sets logging levels.
- */
- private void initLevel() {
-
- if (PolicyLogger.getDebugLevel() == Level.DEBUG) {
- debugEnabled = true;
- infoEnabled = true;
- warnEnabled = true;
- } else {
- debugEnabled = false;
- }
-
- if (PolicyLogger.getDebugLevel() == Level.INFO) {
- infoEnabled = true;
- warnEnabled = true;
- debugEnabled = false;
- }
-
- if (PolicyLogger.getDebugLevel() == Level.OFF) {
- infoEnabled = false;
- warnEnabled = false;
- debugEnabled = false;
- }
-
- if (PolicyLogger.getErrorLevel() == Level.OFF) {
- errorEnabled = false;
- }
-
- if (PolicyLogger.getAuditLevel() == Level.OFF) {
- auditEnabled = false;
- }
-
- if (PolicyLogger.getMetricsLevel() == Level.OFF) {
- metricsEnabled = false;
- }
- }
-
- /**
- * Sets transaction Id.
- */
- @Override
- public void setTransId(String transId) {
-
- displayMessage(transId);
- this.transId = transId;
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void debug(Object message) {
-
- displayMessage(transId + "|" + className + " : " + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void debug(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments variable number of arguments
- */
- @Override
- public void debug(String message, Object...arguments) {
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
- } else {
- displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
- }
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- */
- @Override
- public void error(Object message) {
-
- displayMessage(transId + "|" + className + " : " + message);
- }
-
- /**
- * Records an error message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void error(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
-
- /**
- * Records an error message.
- *
- * @param msg the message code
- * @param throwable the throwable
- * @param arguments the messages
- */
- @Override
- public void error(MessageCodes msg, Throwable throwable, String... arguments) {
- displayMessage(className + " : " + "MessageCodes :" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records an error message.
- *
- * @param msg the message code
- * @param arguments the messages
- */
- @Override
- public void error(MessageCodes msg, String... arguments) {
- displayMessage(transId + "|" + className + " : " + "MessageCode:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records a error message.
- *
- * @param message the message
- * @param arguments variable number of arguments
- */
- @Override
- public void error(String message, Object...arguments) {
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
- } else {
- displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
- }
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void info(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void info(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments variable number of arguments
- */
- @Override
- public void info(String message, Object...arguments) {
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
- } else {
- displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
- }
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void warn(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
- }
-
- /**
- * Records a message.
- *
- * @param msg the message code
- * @param arguments the messages
- */
- @Override
- public void warn(MessageCodes msg, String... arguments) {
-
- displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void warn(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
-
- /**
- * Records a message.
- *
- * @param msg the message code
- * @param throwable the throwable
- * @param arguments the messages
- */
- @Override
- public void warn(MessageCodes msg, Throwable throwable, String... arguments) {
-
- displayMessage(transId + "|" + className + " : " + "MessageCodes:" + msg + Arrays.asList(arguments));
-
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param arguments variable number of arguments
- */
- @Override
- public void warn(String message, Object...arguments) {
- if (arguments.length == 1 && OnapLoggingUtils.isThrowable(arguments[0])) {
- displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
- } else {
- displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
- }
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- */
- @Override
- public void trace(Object message) {
- displayMessage(transId + "|" + className + " : " + message);
- }
-
- /**
- * Records a message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void trace(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- */
- @Override
- public void audit(Object message) {
-
- displayMessage(transId + "|" + className + " : " + message);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- @Override
- public void audit(Object message, Throwable throwable) {
- displayMessage(transId + "|" + className + " : " + message + ":" + throwable);
- }
-
- /**
- * Records an audit message.
- *
- * @param message the message
- */
- @Override
- public void audit(String message, Object... arguments) {
- if (arguments.length == 1) {
- displayMessage(transId + "|" + className + " : " + message + ":" + arguments[0]);
- } else {
- displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
- }
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(String eventId) {
-
- displayMessage(transId + "|" + className + " : " + eventId);
-
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- */
- @Override
- public void recordAuditEventStart(UUID eventId) {
-
- displayMessage(eventId);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- @Override
- public void recordAuditEventEnd(String eventId, String rule, String policyVersion) {
-
- displayMessage(className + " : " + eventId + ":" + rule + ":" + policyVersion);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- * @param policyVersion the policy version
- */
- @Override
- public void recordAuditEventEnd(UUID eventId, String rule, String policyVersion) {
-
- displayMessage(className + " : " + eventId + ":" + rule + ":" + policyVersion);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- @Override
- public void recordAuditEventEnd(String eventId, String rule) {
-
- displayMessage(className + " : " + eventId + ":" + rule);
- }
-
- /**
- * Records an audit message.
- *
- * @param eventId the event ID
- * @param rule the rule
- */
- @Override
- public void recordAuditEventEnd(UUID eventId, String rule) {
-
- displayMessage(className + " : " + eventId + ":" + rule);
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(String eventId, String message) {
-
- displayMessage(className + " : " + "eventId:" + eventId + "message:" + message);
-
- }
-
- /**
- * Records a metrics message.
- *
- * @param eventId the event ID
- * @param message the message
- */
- @Override
- public void recordMetricEvent(UUID eventId, String message) {
-
- displayMessage(className + " : " + eventId + ":" + message);
- }
-
- /**
- * Records a metrics message.
- *
- * @param message the message
- */
- @Override
- public void metrics(Object message) {
-
- displayMessage(className + " : " + message);
- }
-
- /**
- * Records a metrics message.
- *
- * @param message the message
- * @param arguments the arguments
- */
- @Override
- public void metrics(String message, Object... arguments) {
- if (arguments.length == 1) {
- displayMessage(className + " : " + message + " : " + arguments[0]);
- } else {
- displayMessage(OnapLoggingUtils.formatMessage(message, arguments));
- }
- }
-
- /**
- * Returns transaction Id.
- *
- * @param transId the transaction ID
- */
- @Override
- public String postMdcInfoForEvent(String transId) {
-
- String transactionId = transId;
- if (transactionId == null || transactionId.isEmpty()) {
- transactionId = UUID.randomUUID().toString();
- }
-
- return transactionId;
- }
-
- /**
- * Records transaction Id.
- *
- * @param message the message
- */
- @Override
- public void postMdcInfoForEvent(Object message) {
- displayMessage(message);
- }
-
-
- /**
- * Returns true for trace enabled, or false for not.
- *
- * @return boolean
- */
- @Override
- public boolean isTraceEnabled() {
- // default
- return false;
- }
-
- /**
- * Records transaction Id.
- *
- * @param transId the transaction ID
- */
- @Override
- public void postMdcInfoForTriggeredRule(String transId) {
-
- displayMessage(transId);
- }
-}
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
deleted file mode 100644
index a8dde087..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContext.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.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.
- *
- * <p>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 the key
- * @param value the 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 the key
- * @param value the value
- */
- void put(String key, long value);
-
- /**
- * Get a string value, returning the default value if the value is missing.
- *
- * @param key the key
- * @param defaultValue the default value
- * @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 the key
- * @param defaultValue the default value
- * @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
deleted file mode 100644
index eb2b318e..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/LoggingContextFactory.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.nsa;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-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.
- *
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class LoggingContextFactory {
- public static class Builder {
-
- private LoggingContext baseContext = null;
- private boolean forShared = false;
-
- public Builder withBaseContext(LoggingContext lc) {
- baseContext = lc;
- return this;
- }
-
- public Builder forSharing() {
- forShared = true;
- return this;
- }
-
- public LoggingContext build() {
- return forShared ? new SharedContext(baseContext) : new Slf4jLoggingContext(baseContext);
- }
- }
-}
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
deleted file mode 100644
index 1d844fa0..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/SharedLoggingContext.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.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 the shared logging context
- */
- 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
deleted file mode 100644
index 13b38fc0..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/SharedContext.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2018, 2020 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 {
- private final HashMap<String, String> contextMap;
-
- public SharedContext(LoggingContext base) {
- super(base);
- contextMap = new HashMap<>();
- }
-
- @Override
- public void put(String key, String value) {
- super.put(key, value);
- contextMap.put(key, value);
- }
-
- @Override
- public void transferTo(SharedLoggingContext lc) {
- for (Entry<String, String> e : contextMap.entrySet()) {
- lc.put(e.getKey(), e.getValue());
- }
- }
-}
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
deleted file mode 100644
index 33e9f637..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/impl/Slf4jLoggingContext.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.nsa.impl;
-
-import org.onap.policy.common.logging.nsa.LoggingContext;
-import org.slf4j.MDC;
-
-/**
- * A logging context for SLF4J.
- *
- */
-public class Slf4jLoggingContext implements LoggingContext {
- public Slf4jLoggingContext(LoggingContext base) {
- // Default constructor
- }
-
- @Override
- public void put(String key, String value) {
- MDC.put(key, value);
- }
-
- @Override
- public void put(String key, long value) {
- put(key, Long.toString(value));
- }
-
- @Override
- public String get(String key, String defaultValue) {
- String result = MDC.get(key);
- if (result == null) {
- result = defaultValue;
- }
- return result;
- }
-
- @Override
- public long get(String key, long defaultValue) {
- final String str = get(key, Long.toString(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
deleted file mode 100644
index 76554c49..00000000
--- a/common-logging/src/main/java/org/onap/policy/common/logging/nsa/package-info.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*-
- * ============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/resources/org/onap/policy/common/logging/eelf/Resources.properties b/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties
deleted file mode 100644
index 0f9d0f8c..00000000
--- a/common-logging/src/main/resources/org/onap/policy/common/logging/eelf/Resources.properties
+++ /dev/null
@@ -1,229 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# ONAP-Logging
-# ================================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
-# Modifications Copyright (C) 2024 Nordix Foundation.
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END=========================================================
-###
-
-#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
-
-
-
-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/test/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfoTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfoTest.java
deleted file mode 100644
index ba72f36b..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/DroolsPdpMdcInfoTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP Policy Engine - Common Modules
- * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import com.att.eelf.configuration.Configuration;
-import org.junit.jupiter.api.Test;
-
-class DroolsPdpMdcInfoTest {
-
- /**
- * Test method for {@link org.onap.policy.common.logging.eelf.DroolsPdpMdcInfo#getMdcInfo()}.
- */
- @Test
- void testGetMdcInfo() {
- DroolsPdpMdcInfo di = new DroolsPdpMdcInfo();
-
- assertNotNull(di.getMdcInfo());
- assertEquals("Policy.droolsPdp", di.getMdcInfo().get(Configuration.MDC_SERVICE_NAME));
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java
deleted file mode 100644
index 764b41b2..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/ErrorCodeMapTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 AT&T.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.logging.eelf.ErrorCodeMap.ErrorCodeInfo;
-
-class ErrorCodeMapTest {
-
- @Test
- void testGetErrorCodeInfo() {
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.EXCEPTION_ERROR));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.GENERAL_ERROR));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.MISS_PROPERTY_ERROR));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.UPDATE_ERROR));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_SYSTEM_ERROR));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_DATA_ISSUE));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_PERMISSIONS));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_DATA_ISSUE));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_PROCESS_FLOW));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_SCHEMA_INVALID));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_UNKNOWN));
- assertNotNull(ErrorCodeMap.getErrorCodeInfo(MessageCodes.ERROR_AUDIT));
- }
-
- @Test
- void testErrorCodeInfoGetErrorCode() {
- ErrorCodeInfo errorCodeInfo = ErrorCodeMap.getErrorCodeInfo(MessageCodes.EXCEPTION_ERROR);
- assertEquals("500", errorCodeInfo.getErrorCode());
- }
-
- @Test
- void testErrorCodeInfoGetErrorDesc() {
- ErrorCodeInfo errorCodeInfo = ErrorCodeMap.getErrorCodeInfo(MessageCodes.EXCEPTION_ERROR);
- assertEquals("This is an exception error message during the process. Please check the error message for detail "
- + "information", errorCodeInfo.getErrorDesc());
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java
deleted file mode 100644
index 6e518c22..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventDataTest.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP Policy Engine - Common Modules
- * ================================================================================
- * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import java.time.Instant;
-import org.junit.jupiter.api.Test;
-
-class EventDataTest {
- private static final Instant istart = Instant.ofEpochMilli(100000L);
- private static final Instant iend = Instant.ofEpochMilli(200000L);
-
- /**
- * Test method for {@link EventData#EventData()}.
- */
- @Test
- void testEventData() {
- EventData eventData = new EventData();
-
- assertNull(eventData.getEndTime());
- assertNull(eventData.getRequestId());
- assertNull(eventData.getStartTime());
- }
-
- /**
- * Test method for {@link EventData#EventData(String, Instant, Instant)}.
- */
- @Test
- void testEventDataStringInstantInstant() {
- EventData eventData = new EventData("myreq", istart, iend);
-
- assertEquals("myreq", eventData.getRequestId());
- assertEquals(istart, eventData.getStartTime());
- assertEquals(iend, eventData.getEndTime());
- }
-
- /**
- * Test method for {@link EventData#getRequestId()} and {@link EventData#setRequestId(String)}.
- */
- @Test
- void testGetSetRequestId() {
- EventData eventData = new EventData();
- assertNull(eventData.getRequestId());
-
- eventData.setRequestId("abc");
- assertEquals("abc", eventData.getRequestId());
-
- eventData.setRequestId("def");
- assertEquals("def", eventData.getRequestId());
- }
-
- /**
- * Test method for {@link EventData#getStartTime()} and {@link EventData#setStartTime(Instant)}.
- */
- @Test
- void testGetSetStartTime() {
- EventData eventData = new EventData();
- assertNull(eventData.getStartTime());
-
- eventData.setStartTime(istart);
- assertEquals(istart, eventData.getStartTime());
-
- eventData.setStartTime(iend);
- assertEquals(iend, eventData.getStartTime());
-
- // setting end-time should not effect start-time
- eventData.setEndTime(istart);
- assertEquals(iend, eventData.getStartTime());
- }
-
- /**
- * Test method for {@link EventData#getEndTime()} and {@link EventData#setEndTime(Instant)}.
- */
- @Test
- void testGetSetEndTime() {
- EventData eventData = new EventData();
- assertNull(eventData.getEndTime());
-
- eventData.setEndTime(iend);
- assertEquals(iend, eventData.getEndTime());
-
- eventData.setEndTime(istart);
- assertEquals(istart, eventData.getEndTime());
-
- // setting start-time should not effect end-time
- eventData.setStartTime(iend);
- assertEquals(istart, eventData.getEndTime());
- }
-
- /**
- * Test method for {@link EventData#toString()}.
- */
- @Test
- void testToString() {
- EventData eventData = new EventData("myreq", istart, iend);
- assertEquals("myreq Starting Time : 1970-01-01T00:01:40Z Ending Time : 1970-01-01T00:03:20Z",
- eventData.toString());
- }
-
- /**
- * Test method for {@link EventData#hashCode()}.
- */
- @Test
- void testHashCode() {
- int hc1 = new EventData("abc", istart, iend).hashCode();
-
- assertNotEquals(hc1, new EventData("abd", istart, iend).hashCode());
- assertEquals(hc1, new EventData("abc", iend, istart).hashCode());
- }
-
- /**
- * Test method for {@link EventData#equals(Object)}.
- */
- @Test
- void testEqualsObject() {
- final EventData d1 = new EventData("abc", istart, iend);
- final EventData d2 = new EventData("abd", istart, iend);
- final EventData d3 = new EventData("abc", iend, istart);
-
- // same object
- assertEquals(d1, d1);
-
- // compare with null
- assertNotEquals(null, d1);
-
- // compare with request id
- // note: ignoring sonar because we want to test d1.equals(), not "abc".equals()
- assertEquals(d1, "abc"); // NOSONAR
- assertNotEquals("abd", d1);
-
- // compare with int - different class type
- assertNotEquals(10, d1);
-
- // "this" has null request id
- assertNotEquals(new EventData(), d1);
-
- // both null
- assertEquals(new EventData(), new EventData());
-
- // this request id is not null, other is null
- assertNotEquals(d1, new EventData());
-
- // neither null, same
- assertEquals(d1, d3);
-
- // neither null, diff
- assertNotEquals(d1, d2);
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java
deleted file mode 100644
index 92d24009..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoHandlerTest.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP Policy Engine - Common Modules
- * ================================================================================
- * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.time.Instant;
-import java.util.concurrent.ConcurrentMap;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class EventTrackInfoHandlerTest {
-
- private static final Instant inow = Instant.now();
- private static final Instant iexpired = Instant.ofEpochMilli(10000L);
-
- private static final EventData data1 = new EventData("abc", inow, inow);
- private static final EventData data2 = new EventData("def", inow, inow);
-
- private static EventTrackInfo tracker;
- private static ConcurrentMap<String, EventData> info;
-
- private EventTrackInfoHandler hdlr;
-
- @BeforeAll
- public static void setUpBeforeClass() {
- tracker = PolicyLogger.getEventTracker();
- info = tracker.getEventInfo();
- }
-
- /**
- * Perform set up for test cases.
- */
- @BeforeEach
- void setUp() {
- info.clear();
-
- hdlr = new EventTrackInfoHandler();
- }
-
- @Test
- void testNoEvents() {
- hdlr.run();
- assertEquals(0, info.size());
- }
-
- @Test
- void testNothingExpired() {
- tracker.storeEventData(data1);
- tracker.storeEventData(data2);
-
- hdlr.run();
- assertEquals(2, info.size());
- }
-
- @Test
- void testSomeExpired() {
- // not expired
- tracker.storeEventData(data1);
- tracker.storeEventData(data2);
-
- // start time is expired
- tracker.storeEventData(new EventData("expiredA", iexpired, inow));
- tracker.storeEventData(new EventData("expiredB", iexpired, inow));
-
- // end time is expired, but that has no impact - these should be retained
- EventData oka = new EventData("okA", inow, iexpired);
- EventData okb = new EventData("okB", inow, iexpired);
-
- tracker.storeEventData(oka);
- tracker.storeEventData(okb);
-
- hdlr.run();
- assertEquals(4, info.size());
-
- assertEquals(data1, info.get("abc"));
- assertEquals(data2, info.get("def"));
- assertEquals(oka, info.get("okA"));
- assertEquals(okb, info.get("okB"));
- }
-
- @Test
- void testMultipleRuns() {
-
- hdlr.run();
- assertEquals(0, info.size());
-
- // not expired
- tracker.storeEventData(data1);
- tracker.storeEventData(data2);
-
- hdlr.run();
- assertEquals(2, info.size());
-
- // start time is expired
- tracker.storeEventData(new EventData("expiredA", iexpired, inow));
- tracker.storeEventData(new EventData("expiredB", iexpired, inow));
-
- // end time is expired, but that has no impact - these should be retained
- tracker.storeEventData(new EventData("okA", inow, iexpired));
- tracker.storeEventData(new EventData("okB", inow, iexpired));
-
- hdlr.run();
- assertEquals(4, info.size());
-
- hdlr.run();
- assertEquals(4, info.size());
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java
deleted file mode 100644
index 49a3463f..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/EventTrackInfoTest.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP Policy Engine - Common Modules
- * ================================================================================
- * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.eelf;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertSame;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.time.Instant;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class EventTrackInfoTest {
-
- private static final Instant istart = Instant.ofEpochMilli(100000L);
- private static final Instant iend = Instant.ofEpochMilli(200000L);
-
- private static final EventData data1 = new EventData("abc", istart, iend);
- private static final EventData data2 = new EventData("def", iend, istart);
-
- private EventTrackInfo info;
-
- @BeforeEach
- void setUp() {
- info = new EventTrackInfo();
-
- }
-
- /**
- * Test method for {@link EventTrackInfo#EventTrackInfo()}.
- */
- @Test
- void testEventTrackInfo() {
- assertNotNull(info.getEventInfo());
- }
-
- /**
- * Test method for {@link EventTrackInfo#getEventDataByRequestId(String)}.
- */
- @Test
- void testGetEventDataByRequestId() {
- info.storeEventData(data1);
- info.storeEventData(data2);
-
- assertSame(data1, info.getEventDataByRequestId("abc"));
- assertSame(data2, info.getEventDataByRequestId("def"));
- assertNull(info.getEventDataByRequestId("hello"));
- }
-
- /**
- * Test method for {@link EventTrackInfo#storeEventData(EventData)}.
- */
- @Test
- void testStoreEventData() {
- // should ignore null
- info.storeEventData(null);
- assertTrue(info.getEventInfo().isEmpty());
-
- // should ignore if request id is null or empty
- info.storeEventData(new EventData());
- info.storeEventData(new EventData("", istart, iend));
- assertTrue(info.getEventInfo().isEmpty());
-
- info.storeEventData(data1);
- info.storeEventData(data2);
- assertEquals(2, info.getEventInfo().size());
-
- // look-up by request id
- assertSame(data1, info.getEventDataByRequestId("abc"));
- assertSame(data2, info.getEventDataByRequestId("def"));
-
- // doesn't replace existing value
- info.storeEventData(new EventData("abc", iend, istart));
- assertEquals(2, info.getEventInfo().size());
- assertSame(data1, info.getEventDataByRequestId("abc"));
- assertSame(data2, info.getEventDataByRequestId("def"));
- }
-
- /**
- * Test method for {@link EventTrackInfo#remove(String)}.
- */
- @Test
- void testRemove() {
- info.storeEventData(data1);
- info.storeEventData(data2);
-
- info.remove("abc");
-
- // ensure only that item was removed
- assertEquals(1, info.getEventInfo().size());
-
- // look-up by request id
- assertNull(info.getEventDataByRequestId("abc"));
- assertSame(data2, info.getEventDataByRequestId("def"));
- }
-
- /**
- * Test method for {@link EventTrackInfo#getEventInfo()}.
- */
- @Test
- void testGetEventInfo() {
- info.storeEventData(data1);
- info.storeEventData(data2);
-
- assertEquals(2, info.getEventInfo().size());
- assertSame(data1, info.getEventInfo().get("abc"));
- assertSame(data2, info.getEventInfo().get("def"));
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java
deleted file mode 100644
index d7239f4e..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/eelf/PolicyLoggerTest.java
+++ /dev/null
@@ -1,718 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-
-package org.onap.policy.common.logging.eelf;
-
-import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
-import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
-import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
-import static com.att.eelf.configuration.Configuration.MDC_REMOTE_HOST;
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
-import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.never;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.PARTNER_NAME;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_CODE;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.RESPONSE_DESCRIPTION;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.SERVER_NAME;
-import static org.onap.policy.common.logging.eelf.OnapConfigProperties.STATUS_CODE;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFLogger.Level;
-import java.time.Instant;
-import java.util.Properties;
-import java.util.UUID;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-import org.slf4j.MDC;
-import org.springframework.test.util.ReflectionTestUtils;
-
-class PolicyLoggerTest {
-
- /**
- * Perform set up for test cases.
- */
- @BeforeEach
- void setUp() {
- Properties properties = new Properties();
- properties.setProperty("policy.component", "XACML");
- PolicyLogger.init(properties);
- }
-
- @Test
- void testSetAndGetDebugLevelLevel() {
- PolicyLogger.setDebugLevel(Level.INFO);
- assertEquals(Level.INFO, PolicyLogger.getDebugLevel());
- PolicyLogger.setDebugLevel(Level.DEBUG);
- assertEquals(Level.DEBUG, PolicyLogger.getDebugLevel());
- }
-
- @Test
- void testSetAndGetAuditLevelLevel() {
- PolicyLogger.setAuditLevel(Level.INFO);
- assertEquals(Level.INFO, PolicyLogger.getAuditLevel());
- PolicyLogger.setAuditLevel(Level.DEBUG);
- assertEquals(Level.DEBUG, PolicyLogger.getAuditLevel());
- }
-
- @Test
- void testSetAndGetMetricsLevelLevel() {
- PolicyLogger.setMetricsLevel(Level.INFO);
- assertEquals(Level.INFO, PolicyLogger.getMetricsLevel());
- PolicyLogger.setMetricsLevel(Level.DEBUG);
- assertEquals(Level.DEBUG, PolicyLogger.getMetricsLevel());
- }
-
- @Test
- void testSetAndGetErrorLevelLevel() {
- PolicyLogger.setErrorLevel(Level.INFO);
- assertEquals(Level.INFO, PolicyLogger.getErrorLevel());
- PolicyLogger.setErrorLevel(Level.DEBUG);
- assertEquals(Level.DEBUG, PolicyLogger.getErrorLevel());
- }
-
- @Test
- void testSetAndGetClassname() {
- assertEquals("ClassName", PolicyLogger.getClassname());
- PolicyLogger.setClassname("PolicyLoggerTest");
- assertEquals("PolicyLoggerTest", PolicyLogger.getClassname());
- }
-
- @Test
- void testPostMdcInfoForEventString() {
- PolicyLogger.postMdcInfoForEvent("transactionId");
-
- assertEquals("", MDC.get(MDC_REMOTE_HOST));
- assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
- assertEquals("Policy.xacmlPdp", MDC.get(MDC_SERVICE_NAME));
- assertEquals("Policy.xacmlPdp.event", MDC.get(MDC_SERVICE_INSTANCE_ID));
- assertEquals("", MDC.get(MDC_INSTANCE_UUID));
- assertEquals("", MDC.get(MDC_ALERT_SEVERITY));
- assertEquals("N/A", MDC.get(PARTNER_NAME));
- assertEquals("COMPLETE", MDC.get(STATUS_CODE));
- assertEquals("N/A", MDC.get(RESPONSE_CODE));
- assertEquals("N/A", MDC.get(RESPONSE_DESCRIPTION));
- }
-
- @Test
- void testPostMdcInfoForEventStringDrools() {
- Properties properties = new Properties();
- properties.setProperty("policy.component", "DROOLS");
- PolicyLogger.init(properties);
-
- PolicyLogger.postMdcInfoForEvent("transactionId");
-
- assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
- assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME));
- assertEquals("Policy.droolsPdp.event", MDC.get(MDC_SERVICE_INSTANCE_ID));
- }
-
- @Test
- void testSetAndGetTransId() {
- PolicyLogger.setTransId("123456");
- assertEquals("123456", PolicyLogger.getTransId());
- }
-
- @Test
- void testPostMdcInfoForEventObject() {
- PolicyLogger.postMdcInfoForEvent(1);
-
- assertEquals("", MDC.get(MDC_REMOTE_HOST));
- assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID));
- assertEquals("Policy.xacmlPdp", MDC.get(MDC_SERVICE_NAME));
- assertEquals("Policy.xacmlPdp.event", MDC.get(MDC_SERVICE_INSTANCE_ID));
- assertEquals("", MDC.get(MDC_INSTANCE_UUID));
- assertEquals("", MDC.get(MDC_ALERT_SEVERITY));
- assertEquals("N/A", MDC.get(PARTNER_NAME));
- assertEquals("COMPLETE", MDC.get(STATUS_CODE));
- assertEquals("N/A", MDC.get(RESPONSE_CODE));
- assertEquals("N/A", MDC.get(RESPONSE_DESCRIPTION));
- }
-
- @Test
- void testPostMdcInfoForTriggeredRule() {
- PolicyLogger.postMdcInfoForTriggeredRule("transactionId");
-
- assertEquals("", MDC.get(MDC_REMOTE_HOST));
- assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
- assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME));
- assertEquals("", MDC.get(MDC_SERVICE_INSTANCE_ID));
- assertNotNull(MDC.get(MDC_SERVER_FQDN));
- assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS));
- assertEquals("", MDC.get(MDC_INSTANCE_UUID));
- assertEquals("", MDC.get(MDC_ALERT_SEVERITY));
- assertEquals("COMPLETE", MDC.get(STATUS_CODE));
- }
-
- @Test
- void testPostMdcUuidForTriggeredRule() {
- PolicyLogger.postMdcUuidForTriggeredRule(1);
-
- assertEquals("", MDC.get(MDC_REMOTE_HOST));
- assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID));
- assertEquals("Policy.droolsPdp", MDC.get(MDC_SERVICE_NAME));
- assertEquals("", MDC.get(MDC_SERVICE_INSTANCE_ID));
- assertNotNull(MDC.get(MDC_SERVER_FQDN));
- assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS));
- assertEquals("", MDC.get(MDC_INSTANCE_UUID));
- assertEquals("", MDC.get(MDC_ALERT_SEVERITY));
- assertEquals("COMPLETE", MDC.get(STATUS_CODE));
- }
-
- @Test
- void testInfoMessageCodesStringStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
- Mockito.verify(mockLogger).info(MessageCodes.ERROR_DATA_ISSUE, "str2");
- }
-
- @Test
- void testInfoStringString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.info("str1", "str2");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
- PolicyLogger.info("str1", "str2");
- Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str2");
- }
-
- @Test
- void testInfoObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.info("str1");
- Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "str1");
- }
-
- @Test
- void testInfoMessageCodesThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
- Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testInfoMessageCodesStringThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.info(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
- "str2");
- Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testWarnMessageCodesStringStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "str1");
- Mockito.verify(mockLogger).warn(MessageCodes.ERROR_DATA_ISSUE);
- }
-
- @Test
- void testWarnStringString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.warn("str1", "str2");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isWarnEnabled()).thenReturn(true);
- PolicyLogger.warn("str1", "str2");
- Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "str2");
- }
-
- @Test
- void testWarnObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.warn(1);
- Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "1");
- }
-
- @Test
- void testWarnMessageCodesThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
- Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testWarnMessageCodesStringThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
- "str2");
- Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testWarnString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.warn("str1");
- Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_WARNING, "str1");
- }
-
- @Test
- void testErrorStringString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- PolicyLogger.error("str1", "str2");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isErrorEnabled()).thenReturn(true);
- PolicyLogger.error("str1", "str2");
- Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str2");
- assertEquals("500", MDC.get("ErrorCode"));
- assertEquals("This is a general error message during the process. Please check the error message for detail "
- + "information", MDC.get("ErrorDescription"));
- }
-
- @Test
- void testErrorString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- PolicyLogger.error("str1");
- Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1");
- assertEquals("ERROR", MDC.get("ErrorCategory"));
- assertEquals("500", MDC.get("ErrorCode"));
- assertEquals("This is a general error message during the process. Please check the error message for detail "
- + "information", MDC.get("ErrorDescription"));
- }
-
- @Test
- void testErrorObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- PolicyLogger.error(1);
- Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "1");
- assertEquals("ERROR", MDC.get("ErrorCategory"));
- assertEquals("500", MDC.get("ErrorCode"));
- assertEquals("This is a general error message during the process. Please check the error message for detail "
- + "information", MDC.get("ErrorDescription"));
- }
-
- @Test
- void testErrorMessageCodesThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
- Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testErrorMessageCodesStringThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
- "str2");
- Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testErrorMessageCodesStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
- Mockito.verify(mockLogger).error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
- }
-
- @Test
- void testDebugMessageCodesStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
- Mockito.verify(mockLogger).debug(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
- }
-
- @Test
- void testDebugStringString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.debug("str1", "str2");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isDebugEnabled()).thenReturn(true);
- PolicyLogger.debug("str1", "str2");
- Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "str2");
- }
-
- @Test
- void testDebugString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.debug("str1");
- Mockito.verify(mockLogger).debug("str1");
- }
-
- @Test
- void testDebugObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.debug(1);
- Mockito.verify(mockLogger).debug("{}", 1);
- }
-
- @Test
- void testAuditStringObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
- PolicyLogger.audit("PolicyLoggerTest", 1);
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
- PolicyLogger.audit("PolicyLoggerTest", 1);
- assertEquals("PolicyLoggerTest", MDC.get("ClassName"));
- assertEquals("COMPLETE", MDC.get("StatusCode"));
- Mockito.verify(mockLogger).info("{}", "1");
- }
-
- @Test
- void testAuditObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
- PolicyLogger.audit(1);
- assertEquals("", MDC.get("ClassName"));
- assertEquals("COMPLETE", MDC.get("StatusCode"));
- Mockito.verify(mockLogger).info("{}", 1);
- }
-
- @Test
- void testDebugMessageCodesThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
- Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testDebugMessageCodesStringThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.debug(MessageCodes.ERROR_DATA_ISSUE, "PolicyLoggerTest", new NullPointerException(), "str1",
- "str2");
- Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testIsDebugEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(PolicyLogger.isDebugEnabled());
- assertTrue(PolicyLogger.isDebugEnabled());
- }
-
- @Test
- void testIsErrorEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(PolicyLogger.isErrorEnabled());
- assertTrue(PolicyLogger.isErrorEnabled());
- }
-
- @Test
- void testIsWarnEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(PolicyLogger.isWarnEnabled());
- assertTrue(PolicyLogger.isWarnEnabled());
- }
-
- @Test
- void testIsInfoEnabled1() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(PolicyLogger.isInfoEnabled1());
- assertTrue(PolicyLogger.isInfoEnabled1());
- }
-
- @Test
- void testIsAuditEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(PolicyLogger.isAuditEnabled());
- assertTrue(PolicyLogger.isAuditEnabled());
- }
-
- @Test
- void testIsInfoEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(PolicyLogger.isInfoEnabled());
- assertTrue(PolicyLogger.isInfoEnabled());
- }
-
- @Test
- void testTraceStringString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.trace("str1", "str2");
- Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "str2");
- }
-
- @Test
- void testTraceObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- PolicyLogger.trace(1);
- Mockito.verify(mockLogger).trace("{}", 1);
- }
-
- @Test
- void testRecordAuditEventStartAndEnd() {
- PolicyLogger.recordAuditEventStart("eventId");
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
-
- PolicyLogger.recordAuditEventEnd("eventId", "rule");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
- }
-
- @Test
- void testRecordAuditEventStartAndEndUuid() {
- UUID uuid = UUID.randomUUID();
- PolicyLogger.recordAuditEventStart(uuid);;
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
-
- PolicyLogger.recordAuditEventEnd(uuid, "rule");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
- }
-
-
- @Test
- void testRecordAuditEventEndStringStringString() {
- PolicyLogger.recordAuditEventStart("eventId");
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
-
- PolicyLogger.recordAuditEventEnd("eventId", "rule", "policyVersion");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
- }
-
- @Test
- void testRecordAuditEventEndUuidStringString() {
- UUID uuid = UUID.randomUUID();
- PolicyLogger.recordAuditEventStart(uuid);;
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
-
- PolicyLogger.recordAuditEventEnd(uuid, "rule", "policyVersion");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
- }
-
-
- @Test
- void testCreatAuditEventTrackingRecordStringStringString() {
- PolicyLogger.recordAuditEventStart("eventId");
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
-
- PolicyLogger.creatAuditEventTrackingRecord("eventId", "rule", "policyVersion");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
- }
-
- @Test
- void testCreatAuditEventTrackingRecordUuidString() {
- UUID uuid = UUID.randomUUID();
- PolicyLogger.recordAuditEventStart(uuid);;
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
-
- PolicyLogger.creatAuditEventTrackingRecord(uuid, "rule");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
- }
-
- @Test
- void testRecordAuditEventStartToEnd() {
- PolicyLogger.recordAuditEventStartToEnd("eventId", "rule", Instant.now(), Instant.now(), "policyVersion");
- assertEquals("eventId", MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testRecordMetricEventStringString() {
- PolicyLogger.recordMetricEvent("eventId", "str1");
- assertEquals("eventId", MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testRecordMetricEventStringStringString() {
- PolicyLogger.recordMetricEvent("eventId", "PolicyLoggerTest", "str1");
- assertEquals("eventId", MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testRecordMetricEventUuidString() {
- UUID uuid = UUID.randomUUID();
- PolicyLogger.recordMetricEvent(uuid, "str1");
- assertEquals(uuid.toString(), MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testRecordMetricEventString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
- PolicyLogger.recordMetricEvent("eventId");
- Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
- Mockito.eq("eventId"));
- }
-
- @Test
- void testMetricsString() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
- PolicyLogger.metrics("str1");
- Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
- Mockito.eq("str1"));
- }
-
- @Test
- void testMetricsStringObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
- PolicyLogger.metrics("PolicyLoggerTest", 1);
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
- PolicyLogger.metrics("PolicyLoggerTest", 1);
- Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
- Mockito.eq("1"));
- }
-
- @Test
- void testMetricsObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
- PolicyLogger.metrics(1);
- Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
- Mockito.eq("1"));
- }
-
- @Test
- void testMetricsPrintln() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
- PolicyLogger.metricsPrintln("str1");
- Mockito.verify(mockLogger).info("str1");
- }
-
- @Test
- void testInitNullProperties() {
- assertThatCode(() -> PolicyLogger.init(null)).doesNotThrowAnyException();
- }
-
- @Test
- void testInit() {
- Properties properties = new Properties();
- properties.setProperty("override.logback.level.setup", "true");
- properties.setProperty("metricsLogger.level", "OFF");
- properties.setProperty("error.level", "OFF");
- properties.setProperty("audit.level", "OFF");
- properties.setProperty("timer.delay.time", "0");
- properties.setProperty("check.interval", "0");
- properties.setProperty("event.expired.time", "0");
- properties.setProperty("concurrentHashMap.limit", "0");
- properties.setProperty("stop.check.point", "0");
- properties.setProperty("logger.property", "LOG4J");
-
- assertThatCode(() -> PolicyLogger.init(properties)).doesNotThrowAnyException();
- }
-
- @Test
- void testSetDebugLevelString() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setDebugLevel("TRACE");
- assertEquals(Level.TRACE, PolicyLogger.getDebugLevel());
- }
-
- @Test
- void testSetErrorLevelStringOff() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setErrorLevel("OFF");
- assertEquals(Level.OFF, PolicyLogger.getErrorLevel());
- }
-
- @Test
- void testSetErrorLevelStringOther() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setErrorLevel("INFO");
- assertEquals(Level.ERROR, PolicyLogger.getErrorLevel());
- }
-
- @Test
- void testSetMetricsLevelStringOff() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setMetricsLevel("OFF");
- assertEquals(Level.OFF, PolicyLogger.getMetricsLevel());
- }
-
- @Test
- void testSetMetricsLevelStringOther() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setMetricsLevel("ERROR");
- assertEquals(Level.INFO, PolicyLogger.getMetricsLevel());
- }
-
- @Test
- void testSetAuditLevelStringOff() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setAuditLevel("OFF");
- assertEquals(Level.OFF, PolicyLogger.getAuditLevel());
- }
-
- @Test
- void testSetAuditLevelStringOther() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setAuditLevel("ERROR");
- assertEquals(Level.INFO, PolicyLogger.getAuditLevel());
- }
-
- @Test
- void testSetAndIsOverrideLogbackLevel() {
- PolicyLogger.setOverrideLogbackLevel(false);
- assertFalse(PolicyLogger.isOverrideLogbackLevel());
- PolicyLogger.setOverrideLogbackLevel(true);
- assertTrue(PolicyLogger.isOverrideLogbackLevel());
- }
-
- @Test
- void testSetServerInfo() {
- PolicyLogger.setServerInfo("serverHost", "serverPort");
- assertEquals("serverHost:serverPort", MDC.get(SERVER_NAME));
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java
deleted file mode 100644
index 66b48e07..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/EelfLoggerTest.java
+++ /dev/null
@@ -1,390 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.never;
-
-import com.att.eelf.configuration.EELFLogger;
-import java.util.UUID;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-import org.slf4j.MDC;
-import org.springframework.test.util.ReflectionTestUtils;
-
-class EelfLoggerTest {
-
- EelfLogger eelfLogger = new EelfLogger("EelfLoggerTest", "transactionId");
-
- @Test
- void testEelfLoggerClassOfQ() {
- new EelfLogger(this.getClass());
- assertNotNull(PolicyLogger.getTransId());
- assertFalse(PolicyLogger.getTransId().isEmpty());
- }
-
- @Test
- void testEelfLoggerString() {
- new EelfLogger("EelfLoggerTest");
- assertNotNull(PolicyLogger.getTransId());
- assertFalse(PolicyLogger.getTransId().isEmpty());
- }
-
- @Test
- void testEelfLoggerClassOfQBoolean() {
- new EelfLogger(this.getClass(), true);
- assertNotNull(PolicyLogger.getTransId());
- assertFalse(PolicyLogger.getTransId().isEmpty());
- }
-
- @Test
- void testEelfLoggerStringBoolean() {
- new EelfLogger("EelfLoggerTest", true);
- assertNotNull(PolicyLogger.getTransId());
- assertFalse(PolicyLogger.getTransId().isEmpty());
- }
-
- @Test
- void testEelfLoggerClassOfQString() {
- new EelfLogger(this.getClass(), "transactionId");
- assertEquals("transactionId", PolicyLogger.getTransId());
- }
-
- @Test
- void testEelfLoggerStringString() {
- new EelfLogger("EelfLoggerTest", "transactionId");
- assertEquals("transactionId", PolicyLogger.getTransId());
- }
-
- @Test
- void testSetAndGetTransId() {
- assertEquals("transactionId", eelfLogger.getTransId());
- eelfLogger.setTransId("transactionId2");
- assertEquals("transactionId2", eelfLogger.getTransId());
- }
-
- @Test
- void testDebugObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.debug("message");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isDebugEnabled()).thenReturn(true);
- eelfLogger.debug("message");
- Mockito.verify(mockLogger).debug(MessageCodes.GENERAL_INFO, "message");
- }
-
- @Test
- void testErrorObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- eelfLogger.error("message");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isErrorEnabled()).thenReturn(true);
- eelfLogger.error("message");
- Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "message");
- }
-
- @Test
- void testInfoObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.info("message");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
- eelfLogger.info("message");
- Mockito.verify(mockLogger).info(MessageCodes.GENERAL_INFO, "message");
- }
-
- @Test
- void testWarnObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.warn("message");
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isWarnEnabled()).thenReturn(true);
- eelfLogger.warn("message");
- Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_INFO, "message");
- }
-
- @Test
- void testTraceObject() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.trace("message");
- Mockito.verify(mockLogger).trace(MessageCodes.GENERAL_INFO, "message");
- }
-
- @Test
- void testIsDebugEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(eelfLogger.isDebugEnabled());
- assertTrue(eelfLogger.isDebugEnabled());
-
- }
-
- @Test
- void testIsInfoEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(eelfLogger.isInfoEnabled());
- assertTrue(eelfLogger.isInfoEnabled());
- }
-
- @Test
- void testIsWarnEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isWarnEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(eelfLogger.isWarnEnabled());
- assertTrue(eelfLogger.isWarnEnabled());
- }
-
- @Test
- void testIsErrorEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- Mockito.when(mockLogger.isErrorEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(eelfLogger.isErrorEnabled());
- assertTrue(eelfLogger.isErrorEnabled());
- }
-
- @Test
- void testIsMetricsEnabled() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setMetricsLevel("ERROR");
- assertTrue(eelfLogger.isMetricsEnabled());
- }
-
- @Test
- void testIsTraceEnabled() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- Mockito.when(mockLogger.isDebugEnabled()).thenReturn(false).thenReturn(true);
- assertFalse(eelfLogger.isTraceEnabled());
- assertTrue(eelfLogger.isTraceEnabled());
- }
-
- @Test
- void testAuditObject() {
- PolicyLogger.setOverrideLogbackLevel(true);
- PolicyLogger.setAuditLevel("ERROR");
- assertTrue(eelfLogger.isAuditEnabled());
- }
-
- @Test
- void testDebugObjectThrowable() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.debug("message", new NullPointerException());
- Mockito.verify(mockLogger).debug((MessageCodes) Mockito.any(),
- Mockito.startsWith("message:java.lang.NullPointerException"));
- }
-
- @Test
- void testErrorObjectThrowable() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- eelfLogger.error("message", new NullPointerException());
- Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
- Mockito.startsWith("message:java.lang.NullPointerException"));
- eelfLogger.error("message", new NullPointerException());
- }
-
- @Test
- void testInfoObjectThrowable() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.info("message", new NullPointerException());
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
- Mockito.verify(mockLogger).info((MessageCodes) Mockito.any(),
- Mockito.startsWith("message:java.lang.NullPointerException"));
- }
-
- @Test
- void testWarnObjectThrowable() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.warn("message", new NullPointerException());
- Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
- Mockito.startsWith("message:java.lang.NullPointerException"));
- }
-
- @Test
- void testTraceObjectThrowable() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.trace("message", new NullPointerException());
- Mockito.verify(mockLogger).trace("{}", "message");
- }
-
- @Test
- void testAuditObjectThrowable() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "auditLogger", mockLogger);
- eelfLogger.audit("message", new NullPointerException());
- Mockito.verify(mockLogger).info("{}", "message");
- }
-
- @Test
- void testRecordAuditEventStartString() {
- eelfLogger.recordAuditEventStart("eventId");
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
- }
-
- @Test
- void testRecordAuditEventStartUuid() {
- UUID uuid = UUID.randomUUID();
- eelfLogger.recordAuditEventStart(uuid);
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
- }
-
- @Test
- void testRecordAuditEventEndStringStringString() {
- eelfLogger.recordAuditEventStart("eventId");
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
-
- eelfLogger.recordAuditEventEnd("eventId", "rule", "policyVersion");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
- }
-
- @Test
- void testRecordAuditEventEndUuidStringString() {
- UUID uuid = UUID.randomUUID();
- eelfLogger.recordAuditEventStart(uuid);;
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
-
- eelfLogger.recordAuditEventEnd(uuid, "rule", "policyVersion");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
- }
-
- @Test
- void testRecordAuditEventEndStringString() {
- eelfLogger.recordAuditEventStart("eventId");
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
-
- eelfLogger.recordAuditEventEnd("eventId", "rule");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get("eventId"));
- }
-
- @Test
- void testRecordAuditEventEndUuidString() {
- UUID uuid = UUID.randomUUID();
- eelfLogger.recordAuditEventStart(uuid);;
- assertNotNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
-
- eelfLogger.recordAuditEventEnd(uuid, "rule");
- assertNull(PolicyLogger.getEventTracker().getEventInfo().get(uuid.toString()));
- }
-
- @Test
- void testRecordMetricEventStringString() {
- eelfLogger.recordMetricEvent("eventId", "str1");
- assertEquals("eventId", MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testRecordMetricEventUuidString() {
- UUID uuid = UUID.randomUUID();
- eelfLogger.recordMetricEvent(uuid, "str2");
- assertEquals(uuid.toString(), MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testMetrics() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "metricsLogger", mockLogger);
- eelfLogger.metrics(1);
- Mockito.verify(mockLogger, never()).info(Mockito.anyString(), Mockito.anyString());
- Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true);
- eelfLogger.metrics(1);
- Mockito.verify(mockLogger).info(Mockito.eq(MessageCodes.RULE_METRICS_INFO), Mockito.anyString(),
- Mockito.eq("1"));
- }
-
- @Test
- void testErrorMessageCodesThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- eelfLogger.error(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
- Mockito.verify(mockLogger).error((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
- }
-
- @Test
- void testErrorMessageCodesStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "errorLogger", mockLogger);
- eelfLogger.error(MessageCodes.GENERAL_ERROR, "str1", "str2");
- Mockito.verify(mockLogger).error(MessageCodes.GENERAL_ERROR, "str1", "str2");
-
- }
-
- @Test
- void testPostMdcInfoForEventString() {
- eelfLogger.postMdcInfoForEvent("transactionId");
- assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testWarnMessageCodesStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
- Mockito.verify(mockLogger).warn(MessageCodes.GENERAL_ERROR, "str1", "str2");
- }
-
- @Test
- void testWarnMessageCodesThrowableStringArray() {
- EELFLogger mockLogger = Mockito.mock(EELFLogger.class);
- ReflectionTestUtils.setField(PolicyLogger.class, "debugLogger", mockLogger);
- eelfLogger.warn(MessageCodes.GENERAL_ERROR, new NullPointerException(), "str1", "str2");
- Mockito.verify(mockLogger).warn((MessageCodes) Mockito.any(),
- Mockito.startsWith("str1:str2:java.lang.NullPointerException"));
-
- }
-
- @Test
- void testPostMdcInfoForTriggeredRule() {
- eelfLogger.postMdcInfoForTriggeredRule("transactionId");
- assertEquals("transactionId", MDC.get(MDC_KEY_REQUEST_ID));
- }
-
- @Test
- void testPostMDdcInfoForEventObject() {
- eelfLogger.postMdcInfoForEvent(1);
- assertEquals("1", MDC.get(MDC_KEY_REQUEST_ID));
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java
deleted file mode 100644
index 3c78785b..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertSame;
-
-import java.util.HashSet;
-import java.util.Set;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.logging.flexlogger.FlexLogger.PropertiesCallBack;
-import org.springframework.test.util.ReflectionTestUtils;
-
-class FlexLoggerTest {
-
- @Test
- void testGetLoggerClassOfQEelf() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger((Class<?>) null);
- assertSame(logger, FlexLogger.getLogger((Class<?>) null));
- assertNotEquals(logger, FlexLogger.getLogger(String.class));
- }
-
- @Test
- void testGetLoggerClassOfQSystemOut() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger(this.getClass());
- assertSame(logger, FlexLogger.getLogger(this.getClass()));
- }
-
- @Test
- void testGetLoggerStringEelf() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger();
- assertSame(logger, FlexLogger.getLogger());
- }
-
- @Test
- void testGetLoggerStringSystemOut() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger();
- assertSame(logger, FlexLogger.getLogger());
- }
-
- @Test
- void testGetLoggerClassOfQBooleanEelf() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger(this.getClass(), true);
- assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
- }
-
- @Test
- void testGetLoggerClassOfQBooleanSystemOut() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger(this.getClass(), true);
- assertSame(logger, FlexLogger.getLogger(this.getClass(), true));
- }
-
- @Test
- void testGetLoggerStringBooleanEelf() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.EELF);
- Logger logger = FlexLogger.getLogger(true);
- assertSame(logger, FlexLogger.getLogger(true));
- }
-
- @Test
- void testGetLoggerStringBooleanSystemOut() {
- ReflectionTestUtils.setField(FlexLogger.class, "loggerType", LoggerType.SYSTEMOUT);
- Logger logger = FlexLogger.getLogger(true);
- assertSame(logger, FlexLogger.getLogger(true));
- }
-
- @Test
- void testGetClassName() {
- assertNotEquals("FlexLogger", new FlexLogger().getClassName());
- }
-
- @Test
- void testPropertiesCallBack() {
- Set<String> changedKeys = new HashSet<>();
- changedKeys.add("debugLogger.level");
- changedKeys.add("metricsLogger.level");
- changedKeys.add("error.level");
- changedKeys.add("audit.level");
- PropertiesCallBack propertiesCallBack = new PropertiesCallBack("name");
- assertThatCode(() -> propertiesCallBack
- .propertiesChanged(PropertyUtil.getProperties("config/policyLogger.properties"), changedKeys))
- .doesNotThrowAnyException();
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java
deleted file mode 100644
index 75c512b2..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/PropertyUtilTest.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018-2020 Ericsson, AT&T. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Properties;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener;
-import org.springframework.test.util.ReflectionTestUtils;
-
-class PropertyUtilTest {
-
- private static final String TIMER_FIELD = "timer";
- private static final File FILE = new File("target/test.properties");
- private static Timer saveTimer;
-
- private TimerTask task;
- private Timer timer;
- private TestListener testListener;
-
- @BeforeAll
- public static void setUpBeforeClass() {
- saveTimer = (Timer) ReflectionTestUtils.getField(PropertyUtil.LazyHolder.class, TIMER_FIELD);
-
- }
-
- @AfterAll
- public static void tearDownAfterClass() {
- ReflectionTestUtils.setField(PropertyUtil.LazyHolder.class, TIMER_FIELD, saveTimer);
-
- }
-
- /**
- * Perform test case set up.
- */
- @BeforeEach
- void setUp() throws IOException {
- task = null;
- timer = mock(Timer.class);
- ReflectionTestUtils.setField(PropertyUtil.LazyHolder.class, TIMER_FIELD, timer);
-
- doAnswer(args -> {
- task = args.getArgument(0, TimerTask.class);
- return null;
- }).when(timer).schedule(any(TimerTask.class), anyLong(), anyLong());
-
- testListener = new TestListener();
-
- FileOutputStream fileOutputStream = new FileOutputStream(FILE);
- Properties properties = new Properties();
- properties.put("testProperty", "testValue");
- properties.store(fileOutputStream, "");
- fileOutputStream.close();
- }
-
- @AfterEach
- void tearDown() throws IOException {
- PropertyUtil.stopListening(FILE, testListener);
- FILE.delete();
- }
-
- @Test
- void testTimer() {
- assertNotNull(saveTimer);
- }
-
- @Test
- void testGetProperties() throws IOException {
- FileOutputStream fileOutputStream = new FileOutputStream(FILE);
- Properties properties = new Properties();
- properties.put("testProperty", "testValue");
- properties.store(fileOutputStream, "");
- fileOutputStream.close();
-
- Properties readProperties = PropertyUtil.getProperties(FILE, testListener);
- assertEquals("testValue", readProperties.getProperty("testProperty"));
- }
-
- @Test
- void testPropertiesChanged() throws IOException, InterruptedException {
- PropertyUtil.getProperties(FILE, testListener);
-
- FileOutputStream fileOutputStream = new FileOutputStream(FILE);
- Properties newProperties = new Properties();
- newProperties.put("testProperty", "testValueNew");
- newProperties.store(fileOutputStream, "");
-
- // fire task and verify that it notifies the listener
- task.run();
- assertTrue(testListener.isPropertiesChangedInvoked());
-
- }
-
- @Test
- void testStopListening() throws IOException {
- FileOutputStream fileOutputStream = new FileOutputStream(FILE);
- Properties properties = new Properties();
- properties.put("testProperty", "testValue");
- properties.store(fileOutputStream, "");
-
- Properties readProperties = PropertyUtil.getProperties(FILE, testListener);
- assertEquals("testValue", readProperties.getProperty("testProperty"));
-
- PropertyUtil.stopListening(FILE, testListener);
-
- properties.put("testProperty", "testValueNew");
- properties.store(fileOutputStream, "");
- fileOutputStream.close();
- readProperties = PropertyUtil.getProperties(FILE, testListener);
- // If stopListening did not remove the listener, the properties file will not be re-read
- // until poll expires and
- // hence "testValue" will be returned here instead of "testNewValue"
- assertEquals("testValueNew", readProperties.getProperty("testProperty"));
- }
-
- /**
- * The {@link #propertiesChanged(Properties, Set)} method is invoked via a background
- * thread, thus we have to use a latch to wait for it to be invoked.
- */
- private class TestListener implements Listener {
-
- private CountDownLatch latch = new CountDownLatch(1);
-
- @Override
- public void propertiesChanged(Properties properties, Set<String> changedKeys) {
- latch.countDown();
- }
-
- public boolean isPropertiesChangedInvoked() throws InterruptedException {
- return latch.await(5, TimeUnit.SECONDS);
- }
- }
-
-}
diff --git a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java b/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java
deleted file mode 100644
index 343eea9c..00000000
--- a/common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/SystemOutLoggerTest.java
+++ /dev/null
@@ -1,558 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-Logging
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.logging.flexlogger;
-
-import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.att.eelf.configuration.EELFLogger.Level;
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.util.UUID;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-
-class SystemOutLoggerTest {
-
- SystemOutLogger systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
-
- @Test
- void testSystemOutLoggerClassOfQ() {
- assertThatCode(() -> new SystemOutLogger(SystemOutLoggerTest.class)).doesNotThrowAnyException();
- }
-
- @Test
- void testSetAndGetTransId() {
- systemOutLogger.setTransId("transactionId");
- assertEquals("transactionId", systemOutLogger.getTransId());
- }
-
- @Test
- void testDebugObject() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- systemOutLogger.setTransId("transactionId");
- System.setOut(ps);
- systemOutLogger.debug("message");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : message"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testErrorObject() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- systemOutLogger.setTransId("transactionId");
- System.setOut(ps);
- systemOutLogger.error("message");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : message"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testInfoObject() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- systemOutLogger.setTransId("transactionId");
- System.setOut(ps);
- systemOutLogger.info("message");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : message"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testWarnObject() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- systemOutLogger.setTransId("transactionId");
- System.setOut(ps);
- systemOutLogger.warn("message");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : message"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testTraceObject() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- systemOutLogger.setTransId("transactionId");
- System.setOut(ps);
- systemOutLogger.trace("message");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : message"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testIsDebugEnabled() {
- PolicyLogger.setDebugLevel(Level.DEBUG);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertTrue(systemOutLogger.isDebugEnabled());
- PolicyLogger.setDebugLevel(Level.INFO);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertFalse(systemOutLogger.isDebugEnabled());
- }
-
- @Test
- void testIsWarnEnabled() {
- PolicyLogger.setDebugLevel(Level.WARN);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertTrue(systemOutLogger.isWarnEnabled());
- PolicyLogger.setDebugLevel(Level.OFF);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertFalse(systemOutLogger.isWarnEnabled());
- }
-
- @Test
- void testIsInfoEnabled() {
- PolicyLogger.setDebugLevel(Level.INFO);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertTrue(systemOutLogger.isInfoEnabled());
- PolicyLogger.setDebugLevel(Level.OFF);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertFalse(systemOutLogger.isInfoEnabled());
- }
-
- @Test
- void testIsErrorEnabled() {
- PolicyLogger.setErrorLevel(Level.ERROR);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertTrue(systemOutLogger.isErrorEnabled());
- PolicyLogger.setErrorLevel(Level.OFF);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertFalse(systemOutLogger.isErrorEnabled());
- }
-
- @Test
- void testIsAuditEnabled() {
- PolicyLogger.setAuditLevel(Level.INFO);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertTrue(systemOutLogger.isAuditEnabled());
- PolicyLogger.setAuditLevel(Level.OFF);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertFalse(systemOutLogger.isAuditEnabled());
- }
-
- @Test
- void testIsMetricsEnabled() {
- PolicyLogger.setMetricsLevel(Level.INFO);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertTrue(systemOutLogger.isMetricsEnabled());
- PolicyLogger.setMetricsLevel(Level.OFF);
- systemOutLogger = new SystemOutLogger("SystemOutLoggerTest");
- assertFalse(systemOutLogger.isMetricsEnabled());
- }
-
- @Test
- void testAuditObject() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- systemOutLogger.setTransId("transactionId");
- System.setOut(ps);
- systemOutLogger.audit("message");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : message"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordAuditEventStartString() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- systemOutLogger.setTransId("transactionId");
- System.setOut(ps);
- systemOutLogger.recordAuditEventStart("eventId");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : eventId"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordAuditEventStartUuid() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- UUID uuid = UUID.randomUUID();
- System.setOut(ps);
- systemOutLogger.recordAuditEventStart(uuid);
- assertTrue(baos.toString().contains(uuid.toString()));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordAuditEventEndStringStringString() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.recordAuditEventEnd("eventId", "rule", "policyVersion");
- assertTrue(baos.toString().contains("SystemOutLoggerTest : eventId:rule:policyVersion"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordAuditEventEndUuidStringString() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- UUID uuid = UUID.randomUUID();
- System.setOut(ps);
- systemOutLogger.recordAuditEventEnd(uuid, "rule", "policyVersion");
- assertTrue(baos.toString().contains("SystemOutLoggerTest : " + uuid + ":rule:policyVersion"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordAuditEventEndStringString() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.recordAuditEventEnd("eventId", "rule");
- assertTrue(baos.toString().contains("SystemOutLoggerTest : eventId:rule"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordAuditEventEndUuidString() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- UUID uuid = UUID.randomUUID();
- System.setOut(ps);
- systemOutLogger.recordAuditEventEnd(uuid, "rule");
- assertTrue(baos.toString().contains("SystemOutLoggerTest : " + uuid + ":rule"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordMetricEventStringString() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.recordMetricEvent("eventId", "rule");
- assertTrue(baos.toString().contains("SystemOutLoggerTest : eventId:eventIdmessage:rule"), baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testRecordMetricEventUuidString() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- UUID uuid = UUID.randomUUID();
- System.setOut(ps);
- systemOutLogger.recordMetricEvent(uuid, "str1");
- assertTrue(baos.toString().contains("SystemOutLoggerTest : " + uuid + ":str1"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testMetrics() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.metrics("message");
- assertTrue(baos.toString().contains("SystemOutLoggerTest : message"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testErrorMessageCodesThrowableStringArray() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.error(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
- assertTrue(baos.toString()
- .contains("SystemOutLoggerTest : MessageCodes :" + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testErrorMessageCodesStringArray() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.error(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCode:"
- + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testPostMdcInfoForEventString() {
- assertEquals("transactionId", systemOutLogger.postMdcInfoForEvent("transactionId"));
- }
-
- @Test
- void testWarnMessageCodesStringArray() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.warn(MessageCodes.ERROR_DATA_ISSUE, "str1", "str2");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCodes:"
- + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testWarnMessageCodesThrowableStringArray() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.warn(MessageCodes.ERROR_DATA_ISSUE, new NullPointerException(), "str1", "str2");
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : MessageCodes:"
- + MessageCodes.ERROR_DATA_ISSUE + "[str1, str2]"));
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testDebugObjectThrowable() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.debug("1", new NullPointerException());
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"),
- baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testErrorObjectThrowable() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.error("1", new NullPointerException());
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"),
- baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testInfoObjectThrowable() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.info("1", new NullPointerException());
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"),
- baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testWarnObjectThrowable() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.warn("1", new NullPointerException());
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"),
- baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testTraceObjectThrowable() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.trace(1, new NullPointerException());
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"),
- baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testAuditObjectThrowable() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.setTransId("transactionId");
- systemOutLogger.audit("1", new NullPointerException());
- assertTrue(baos.toString().contains("transactionId|SystemOutLoggerTest : 1:java.lang.NullPointerException"),
- baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testIsTraceEnabled() {
- assertFalse(systemOutLogger.isTraceEnabled());
- }
-
- @Test
- void testPostMdcInfoForTriggeredRule() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.postMdcInfoForTriggeredRule("transactionId");
- assertTrue(baos.toString().contains("transactionId"), baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
- @Test
- void testPostMdcInfoForEventObject() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- PrintStream old = System.out;
- try {
- System.setOut(ps);
- systemOutLogger.postMdcInfoForEvent(1);
- assertTrue(baos.toString().contains("1"), baos.toString());
- } finally {
- System.out.flush();
- System.setOut(old);
- }
- }
-
-}
diff --git a/integrity-audit/config/policyLogger.properties b/integrity-audit/config/policyLogger.properties
deleted file mode 100644
index 1e7187f2..00000000
--- a/integrity-audit/config/policyLogger.properties
+++ /dev/null
@@ -1,44 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# Integrity Audit
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END=========================================================
-###
-
-################################### Set concurrentHashMap and timer info #######################
-#Timer initial delay and the delay between in milliseconds before task is to be execute.
-timer.delay.time=1000
-#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions.
-check.interval= 30000
-#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds.
-event.expired.time=86400
-#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed
-#to remove all expired records from this concurrentHashMap.
-concurrentHashMap.limit=5000
-#Size of the concurrentHashMap - when its size drops to this point, stop the Timer
-stop.check.point=2500
-################################### Set logging format #############################################
-# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println
-logger.type=EELF
-#################################### Set level for EELF or SYSTEMOUT logging ##################################
-# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all
-debugLogger.level=INFO
-# Set level for metrics file. Set OFF to disable; set ON to enable
-metricsLogger.level=ON
-# Set level for error file. Set OFF to disable; set ON to enable
-error.level=ON
-# Set level for audit file. Set OFF to disable; set ON to enable
-audit.level=ON
diff --git a/integrity-audit/policyLogger.properties b/integrity-audit/policyLogger.properties
deleted file mode 100644
index 1e7187f2..00000000
--- a/integrity-audit/policyLogger.properties
+++ /dev/null
@@ -1,44 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# Integrity Audit
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END=========================================================
-###
-
-################################### Set concurrentHashMap and timer info #######################
-#Timer initial delay and the delay between in milliseconds before task is to be execute.
-timer.delay.time=1000
-#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions.
-check.interval= 30000
-#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds.
-event.expired.time=86400
-#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed
-#to remove all expired records from this concurrentHashMap.
-concurrentHashMap.limit=5000
-#Size of the concurrentHashMap - when its size drops to this point, stop the Timer
-stop.check.point=2500
-################################### Set logging format #############################################
-# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println
-logger.type=EELF
-#################################### Set level for EELF or SYSTEMOUT logging ##################################
-# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all
-debugLogger.level=INFO
-# Set level for metrics file. Set OFF to disable; set ON to enable
-metricsLogger.level=ON
-# Set level for error file. Set OFF to disable; set ON to enable
-error.level=ON
-# Set level for audit file. Set OFF to disable; set ON to enable
-audit.level=ON
diff --git a/integrity-audit/pom.xml b/integrity-audit/pom.xml
deleted file mode 100644
index f2cd6f0e..00000000
--- a/integrity-audit/pom.xml
+++ /dev/null
@@ -1,95 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- ONAP Policy Engine - Common Modules
- ================================================================================
- Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023-2024 Nordix Foundation.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
- <modelVersion>4.0.0</modelVersion>
-
- <artifactId>integrity-audit</artifactId>
-
- <packaging>jar</packaging>
-
- <parent>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>common-modules</artifactId>
- <version>3.0.1-SNAPSHOT</version>
- </parent>
-
- <name>Integrity Audit</name>
-
- <dependencies>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>utils-test</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>ONAP-Logging</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- <dependency>
- <groupId>org.hibernate.orm</groupId>
- <artifactId>hibernate-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.hibernate.validator</groupId>
- <artifactId>hibernate-validator</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-ext</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-</project>
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java
deleted file mode 100644
index 03fbdb57..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditThread.java
+++ /dev/null
@@ -1,771 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Properties;
-import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-/**
- * AuditThread is the main thread for the IntegrityAudit.
- *
- */
-public class AuditThread extends Thread {
-
- private static final Logger logger = FlexLogger.getLogger(AuditThread.class);
-
- /*
- * Number of milliseconds that must elapse for audit to be considered complete. It's public for
- * access by JUnit test logic.
- */
- public static final long AUDIT_COMPLETION_INTERVAL = 30000L;
-
- /**
- * Number of audit cycles before the completion flag is reset.
- */
- public static final int AUDIT_RESET_CYCLES = 2;
-
- /*
- * Unless audit has already been run on this entity, number of milliseconds to sleep between
- * audit thread iterations. If audit has already been run, we sleep integrityAuditPeriodMillis.
- * May be modified by JUnit tests.
- */
- private static final long AUDIT_THREAD_SLEEP_INTERVAL_MS = 5000L;
-
- /*
- * String constants.
- */
- private static final String AUDIT_THREAD_MESSAGE = "AuditThread.run: resourceName=";
- private static final String ENTITY_INDEX_MESSAGE = ", entityIndex=";
- private static final String LAST_UPDATED_MESSAGE = ", lastUpdated=";
- private static final String PERSISTENCE_MESSAGE = ", persistenceUnit=";
-
- /*
- * DB access class.
- */
- private DbDao dbDao;
-
- /*
- * E.g. pdp_xacml
- */
- private String nodeType;
-
- /*
- * Persistence unit for which this audit is being run.
- */
- private String persistenceUnit;
-
- /*
- * Name of this resource
- */
- private String resourceName;
-
- /*
- * E.g. DB_DRIVER, SITE_NAME, NODE_TYPE
- */
- private Properties properties;
-
- /*
- * See IntegrityAudit class for usage.
- */
- private int integrityAuditPeriodSeconds;
-
- /*
- * The containing IntegrityAudit instance
- */
- private IntegrityAudit integrityAudit;
-
- /*
- * Used to create a list that is sorted lexicographically by resourceName.
- */
- Comparator<IntegrityAuditEntity> comparator = (r1, r2) -> r1.getResourceName().compareTo(r2.getResourceName());
-
- /**
- * AuditThread constructor.
- *
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @param integrityAuditPeriodSeconds the integrity audit period in seconds
- * @param integrityAudit the integrity audit
- * @throws IntegrityAuditException if an error occurs
- */
- public AuditThread(String resourceName, String persistenceUnit, Properties properties,
- int integrityAuditPeriodSeconds, IntegrityAudit integrityAudit) throws IntegrityAuditException {
-
- this.resourceName = resourceName;
- this.persistenceUnit = persistenceUnit;
- this.properties = properties;
- this.integrityAuditPeriodSeconds = integrityAuditPeriodSeconds;
- this.integrityAudit = integrityAudit;
-
- /*
- * The DbDao Constructor registers this node in the IntegrityAuditEntity table. Each
- * resource (node) inserts its own name, persistenceUnit, DB access properties and other
- * pertinent properties in the table. This allows the audit on each node to compare its own
- * version of the entities for the persistenceUnit in question with the versions from all
- * other nodes of similar type.
- */
- dbDao = new DbDao(this.resourceName, this.persistenceUnit, this.properties);
- this.nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE).toLowerCase();
-
- }
-
- @Override
- public void run() {
-
- logger.info("AuditThread.run: Entering");
-
- try {
- // for junit testing
- runStarted();
-
- /*
- * Triggers change in designation, unless no other viable candidate.
- */
- runUntilInterrupted();
-
- } catch (InterruptedException e) {
- handleAuditLoopException(e);
- Thread.currentThread().interrupt();
-
- } catch (Exception e) {
- handleAuditLoopException(e);
- }
-
- dbDao.destroy();
-
- logger.info("AuditThread.run: Exiting");
- }
-
- private void handleAuditLoopException(Exception exception) {
- String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + exception.getMessage();
- logger.error(MessageCodes.EXCEPTION_ERROR, exception, msg);
- integrityAudit.setThreadInitialized(false);
- }
-
- private void runUntilInterrupted() throws InterruptedException {
- var auditCompleted = false;
-
- var dbAudit = new DbAudit(dbDao);
-
- IntegrityAuditEntity entityCurrentlyDesignated;
- IntegrityAuditEntity thisEntity;
- integrityAudit.setThreadInitialized(true); // An exception will set it to false
-
- var interrupted = false;
-
- while (!interrupted) {
- try {
- /*
- * It may have been awhile since we last cycled through this loop, so refresh
- * the list of IntegrityAuditEntities.
- */
- List<IntegrityAuditEntity> integrityAuditEntityList = getIntegrityAuditEntityList();
-
- /*
- * We could've set entityCurrentlyDesignated as a side effect of
- * getIntegrityAuditEntityList(), but then we would've had to make
- * entityCurrentlyDesignated a class level attribute. Using this approach, we
- * can keep it local to the run() method.
- */
- entityCurrentlyDesignated = getEntityCurrentlyDesignated(integrityAuditEntityList);
-
- /*
- * Need to refresh thisEntity each time through loop, because we need a fresh
- * version of lastUpdated.
- */
- thisEntity = getThisEntity(integrityAuditEntityList);
-
- /*
- * If we haven't done the audit yet, note that we're current and see if we're
- * designated.
- */
- auditCompleted = doAudit(auditCompleted, dbAudit, entityCurrentlyDesignated, thisEntity,
- integrityAuditEntityList);
-
- /*
- * If we've just run audit, sleep per the integrity_audit_period_seconds
- * property, otherwise just sleep the normal interval.
- */
- sleepAfterAudit(auditCompleted);
-
- } catch (Exception e) {
- if (isInterruptedException(e)) {
- String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + "; Stopping.";
- logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
- Thread.currentThread().interrupt();
- interrupted = true;
-
- } else {
- String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage()
- + "; Will try audit again in " + integrityAuditPeriodSeconds + " seconds";
- logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
- // Sleep and try again later
- AuditorTime.getInstance().sleep(integrityAuditPeriodSeconds * 1000L);
- }
- }
- }
- }
-
- private boolean doAudit(boolean auditCompleted, DbAudit dbAudit, IntegrityAuditEntity entityCurrentlyDesignated,
- IntegrityAuditEntity thisEntity, List<IntegrityAuditEntity> integrityAuditEntityList)
- throws IntegrityAuditException {
-
- if (!auditCompleted) {
- dbDao.setLastUpdated();
-
- /*
- * If no current designation or currently designated node is stale, see if
- * we're the next node to be designated.
- */
- if (entityCurrentlyDesignated == null || isStale(entityCurrentlyDesignated)) {
- IntegrityAuditEntity designationCandidate =
- getDesignationCandidate(integrityAuditEntityList);
-
- /*
- * If we're the next node to be designated, run the audit.
- */
- if (designationCandidate.getResourceName().equals(this.resourceName)) {
- runAudit(dbAudit);
- auditCompleted = true;
- } else if (logger.isDebugEnabled()) {
- logger.debug("AuditThread.run: designationCandidate, " + designationCandidate.getResourceName()
- + ", not this entity, " + thisEntity.getResourceName());
- }
-
- /*
- * Application may have been stopped and restarted, in which case we
- * might be designated but auditCompleted will have been reset to false,
- * so account for this.
- */
- } else if (thisEntity.getResourceName().equals(entityCurrentlyDesignated.getResourceName())) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("AuditThread.run: Re-running audit for " + thisEntity.getResourceName());
- }
- runAudit(dbAudit);
- auditCompleted = true;
-
- } else if (logger.isDebugEnabled()) {
- logger.debug("AuditThread.run: Currently designated node, "
- + entityCurrentlyDesignated.getResourceName() + ", not yet stale and not this node");
- }
-
-
- /*
- * Audit already completed on this node, so allow the node to go stale until
- * twice the AUDIT_COMPLETION_PERIOD has elapsed. This should give plenty of
- * time for another node (if another node is out there) to pick up
- * designation.
- */
- } else {
-
- auditCompleted = resetAuditCompleted(auditCompleted, thisEntity);
-
- }
- return auditCompleted;
- }
-
- private void sleepAfterAudit(boolean auditCompleted) throws InterruptedException {
- if (auditCompleted) {
- // for junit testing: indicate that an audit has completed
- auditCompleted();
-
- if (logger.isDebugEnabled()) {
- logger.debug("AuditThread.run: Audit completed; resourceName=" + this.resourceName
- + " sleeping " + integrityAuditPeriodSeconds + "s");
- }
- AuditorTime.getInstance().sleep(integrityAuditPeriodSeconds * 1000L);
- if (logger.isDebugEnabled()) {
- logger.debug(AUDIT_THREAD_MESSAGE + this.resourceName + " awaking from "
- + integrityAuditPeriodSeconds + "s sleep");
- }
-
- } else {
-
- if (logger.isDebugEnabled()) {
- logger.debug(AUDIT_THREAD_MESSAGE + this.resourceName + ": Sleeping "
- + AuditThread.AUDIT_THREAD_SLEEP_INTERVAL_MS + "ms");
- }
- AuditorTime.getInstance().sleep(AuditThread.AUDIT_THREAD_SLEEP_INTERVAL_MS);
- if (logger.isDebugEnabled()) {
- logger.debug(AUDIT_THREAD_MESSAGE + this.resourceName + ": Awaking from "
- + AuditThread.AUDIT_THREAD_SLEEP_INTERVAL_MS + "ms sleep");
- }
-
- }
- }
-
- /**
- * Determines if an exception is an InterruptedException or was caused by an
- * InterruptedException.
- *
- * @param ex exception to be examined
- * @return {@code true} if it's an InterruptedException, {@code false} otherwise
- */
- private boolean isInterruptedException(Throwable ex) {
- while (ex != null) {
- if (ex instanceof InterruptedException) {
- return true;
- }
-
- ex = ex.getCause();
- }
-
- return false;
- }
-
- /**
- * getDesignationCandidate() Using round robin algorithm, gets next candidate to be designated.
- * Assumes list is sorted lexicographically by resourceName.
- */
- private IntegrityAuditEntity getDesignationCandidate(List<IntegrityAuditEntity> integrityAuditEntityList) {
-
- // Note: assumes integrityAuditEntityList is already lexicographically sorted by
- // resourceName
-
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: Entering, integrityAuditEntityList.size()="
- + integrityAuditEntityList.size());
- }
-
- IntegrityAuditEntity thisEntity = null;
-
- var designatedEntityIndex = -1;
- var entityIndex = 0;
- var priorCandidateIndex = -1;
- var subsequentCandidateIndex = -1;
-
- for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) {
-
- if (logger.isDebugEnabled()) {
- logIntegrityAuditEntity(integrityAuditEntity);
- }
-
- thisEntity = detmEntity(integrityAuditEntity, thisEntity);
-
- if (integrityAuditEntity.isDesignated()) {
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: Currently designated entity resourceName="
- + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE
- + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE
- + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex);
- }
- designatedEntityIndex = entityIndex;
-
- /*
- * Entity not currently designated
- */
- } else if (isStale(integrityAuditEntity)) {
- /*
- * Non-designated entity is stale.
- */
-
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: Entity is stale; resourceName="
- + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE
- + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE
- + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex);
- }
-
- /*
- * Entity is current.
- */
- } else if (designatedEntityIndex == -1) {
- priorCandidateIndex = detmPriorCandidate(entityIndex, integrityAuditEntity, priorCandidateIndex);
-
- } else {
- subsequentCandidateIndex =
- detmSubsequentCandidate(entityIndex, integrityAuditEntity, subsequentCandidateIndex);
- }
-
- entityIndex++;
-
- } // end for loop
-
- return detmDesignationCandidate(integrityAuditEntityList, thisEntity, priorCandidateIndex,
- subsequentCandidateIndex);
- }
-
- private IntegrityAuditEntity detmEntity(IntegrityAuditEntity integrityAuditEntity,
- IntegrityAuditEntity thisEntity) {
- if (integrityAuditEntity.getResourceName().equals(this.resourceName)) {
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: thisEntity=" + integrityAuditEntity.getResourceName());
- }
- thisEntity = integrityAuditEntity;
- }
- return thisEntity;
- }
-
- private int detmPriorCandidate(int entityIndex, IntegrityAuditEntity integrityAuditEntity,
- int priorCandidateIndex) {
- if (priorCandidateIndex == -1) {
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: Prior candidate found, resourceName="
- + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE
- + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE
- + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex);
- }
- priorCandidateIndex = entityIndex;
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "getDesignationCandidate: Prior entity current but prior candidate already "
- + "found; resourceName=" + integrityAuditEntity.getResourceName()
- + PERSISTENCE_MESSAGE + integrityAuditEntity.getPersistenceUnit()
- + LAST_UPDATED_MESSAGE + integrityAuditEntity.getLastUpdated()
- + ENTITY_INDEX_MESSAGE + entityIndex);
- }
- }
- return priorCandidateIndex;
- }
-
- private int detmSubsequentCandidate(int entityIndex, IntegrityAuditEntity integrityAuditEntity,
- int subsequentCandidateIndex) {
- if (subsequentCandidateIndex == -1) {
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: Subsequent candidate found, resourceName="
- + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE
- + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE
- + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE + entityIndex);
- }
- subsequentCandidateIndex = entityIndex;
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "getDesignationCandidate: Subsequent entity current but subsequent candidate "
- + "already found; resourceName="
- + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE
- + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE
- + integrityAuditEntity.getLastUpdated() + ENTITY_INDEX_MESSAGE
- + entityIndex);
- }
- }
- return subsequentCandidateIndex;
- }
-
- private IntegrityAuditEntity detmDesignationCandidate(List<IntegrityAuditEntity> integrityAuditEntityList,
- IntegrityAuditEntity thisEntity, int priorCandidateIndex, int subsequentCandidateIndex) {
- IntegrityAuditEntity designationCandidate;
- /*
- * Per round robin algorithm, if a current entity is found that is lexicographically after
- * the currently designated entity, this entity becomes the designation candidate. If no
- * current entity is found that is lexicographically after currently designated entity, we
- * cycle back to beginning of list and pick the first current entity as the designation
- * candidate.
- */
- if (subsequentCandidateIndex != -1) {
- designationCandidate = integrityAuditEntityList.get(subsequentCandidateIndex);
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: Exiting and returning subsequent designationCandidate="
- + designationCandidate.getResourceName());
- }
- } else {
- if (priorCandidateIndex != -1) {
- designationCandidate = integrityAuditEntityList.get(priorCandidateIndex);
- if (logger.isDebugEnabled()) {
- logger.debug("getDesignationCandidate: Exiting and returning prior designationCandidate="
- + designationCandidate.getResourceName());
- }
- } else if (thisEntity != null) {
- logger.debug("getDesignationCandidate: No subsequent or prior candidate found; designating thisEntity, "
- + "resourceName=" + thisEntity.getResourceName());
- designationCandidate = thisEntity;
- } else {
- // this shouldn't happen, but adding it to make sonar happy
- logger.debug("getDesignationCandidate: No entities available");
- designationCandidate = null;
- }
- }
-
- return designationCandidate;
- }
-
- /**
- * getEntityCurrentlyDesignated() Returns entity that is currently designated.
- *
- * @param integrityAuditEntityList the integrity audit entity list
- * @return the currently designated integrity audit entity
- */
- private IntegrityAuditEntity getEntityCurrentlyDesignated(List<IntegrityAuditEntity> integrityAuditEntityList) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("getEntityCurrentlyDesignated: Entering, integrityAuditEntityList.size="
- + integrityAuditEntityList.size());
- }
-
- IntegrityAuditEntity entityCurrentlyDesignated = null;
-
- for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) {
-
- if (integrityAuditEntity.isDesignated()) {
- if (logger.isDebugEnabled()) {
- logger.debug("getEntityCurrentlyDesignated: Currently designated entity resourceName="
- + integrityAuditEntity.getResourceName() + PERSISTENCE_MESSAGE
- + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE
- + integrityAuditEntity.getLastUpdated());
- }
- entityCurrentlyDesignated = integrityAuditEntity;
- }
-
- } // end for loop
-
- if (logger.isDebugEnabled()) {
- if (entityCurrentlyDesignated != null) {
- logger.debug("getEntityCurrentlyDesignated: Exiting and returning entityCurrentlyDesignated="
- + entityCurrentlyDesignated.getResourceName());
- } else {
- logger.debug("getEntityCurrentlyDesignated: Exiting and returning entityCurrentlyDesignated="
- + entityCurrentlyDesignated);
- }
- }
- return entityCurrentlyDesignated;
-
- }
-
- /**
- * getIntegrityAuditEnityList gets the list of IntegrityAuditEntity.
- *
- * @return the list of IntegrityAuditEntity
- * @throws DbDaoTransactionException if an error occurs getting the list of IntegrityAuditEntity
- */
- private List<IntegrityAuditEntity> getIntegrityAuditEntityList() throws DbDaoTransactionException {
-
- if (logger.isDebugEnabled()) {
- logger.debug("getIntegrityAuditEntityList: Entering");
- }
-
- /*
- * Get all records for this nodeType and persistenceUnit and then sort them
- * lexicographically by resourceName. Get index of designated entity, if any.
- */
- /*
- * Sorted list of entities for a particular nodeType and persistenceUnit.
- */
- List<IntegrityAuditEntity> integrityAuditEntityList =
- dbDao.getIntegrityAuditEntities(this.persistenceUnit, this.nodeType);
- var listSize = integrityAuditEntityList.size();
- if (logger.isDebugEnabled()) {
- logger.debug("getIntegrityAuditEntityList: Got " + listSize + " IntegrityAuditEntity records");
- }
- Collections.sort(integrityAuditEntityList, comparator);
-
- if (logger.isDebugEnabled()) {
- logger.debug(
- "getIntegrityAuditEntityList: Exiting and returning integrityAuditEntityList, size=" + listSize);
- }
- return integrityAuditEntityList;
-
- }
-
-
- /**
- * Returns the IntegrityAuditEntity for this entity.
- *
- * @param integrityAuditEntityList the list of IntegrityAuditEntity
- * @return the IntegrityAuditEntity for this entity
- */
- private IntegrityAuditEntity getThisEntity(List<IntegrityAuditEntity> integrityAuditEntityList) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("getThisEntity: Entering, integrityAuditEntityList.size=" + integrityAuditEntityList.size());
- }
-
- IntegrityAuditEntity thisEntity = null;
-
- for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) {
-
- if (integrityAuditEntity.getResourceName().equals(this.resourceName)) {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "getThisEntity: For this entity, resourceName=" + integrityAuditEntity.getResourceName()
- + PERSISTENCE_MESSAGE + integrityAuditEntity.getPersistenceUnit()
- + LAST_UPDATED_MESSAGE + integrityAuditEntity.getLastUpdated());
- }
- thisEntity = integrityAuditEntity;
- }
-
- } // end for loop
-
- if (logger.isDebugEnabled()) {
- if (thisEntity != null) {
- logger.debug("getThisEntity: Exiting and returning thisEntity=" + thisEntity.getResourceName());
- } else {
- logger.debug("getThisEntity: Exiting and returning thisEntity=" + thisEntity);
- }
- }
- return thisEntity;
-
- }
-
-
- /**
- * Returns false if the lastUpdated time for the record in question is more than
- * auditCompletionIntervalMillis seconds ago. During an audit, lastUpdated is updated every five
- * seconds or so, but when an audit finishes, the node doing the audit stops updating
- * lastUpdated.
- *
- * @param integrityAuditEntity the integrityAuditEntity
- * @return false if the lastUpdated time for the record in question is more than
- * auditCompletionIntervalMillis seconds ago
- */
- private boolean isStale(IntegrityAuditEntity integrityAuditEntity) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("isStale: Entering, resourceName=" + integrityAuditEntity.getResourceName()
- + PERSISTENCE_MESSAGE + integrityAuditEntity.getPersistenceUnit() + LAST_UPDATED_MESSAGE
- + integrityAuditEntity.getLastUpdated());
- }
-
- var stale = false;
-
- var currentTime = AuditorTime.getInstance().getDate();
- var lastUpdated = integrityAuditEntity.getLastUpdated();
-
- /*
- * If lastUpdated is null, we assume that the audit never ran for that node.
- */
- long lastUpdatedTime = 0;
- if (lastUpdated != null) {
- lastUpdatedTime = lastUpdated.getTime();
- }
- long timeDifference = currentTime.getTime() - lastUpdatedTime;
- if (timeDifference > AUDIT_COMPLETION_INTERVAL) {
- stale = true;
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("isStale: Exiting and returning stale=" + stale + ", timeDifference=" + timeDifference);
- }
-
- return stale;
- }
-
- private void logIntegrityAuditEntity(IntegrityAuditEntity integrityAuditEntity) {
-
- logger.debug("logIntegrityAuditEntity: id=" + integrityAuditEntity.getId() + ", jdbcDriver="
- + integrityAuditEntity.getJdbcDriver() + ", jdbcPassword=" + integrityAuditEntity.getJdbcPassword()
- + ", jdbcUrl=" + integrityAuditEntity.getJdbcUrl() + ", jdbcUser=" + integrityAuditEntity.getJdbcUser()
- + ", nodeType=" + integrityAuditEntity.getNodeType() + PERSISTENCE_MESSAGE
- + integrityAuditEntity.getPersistenceUnit() + ", resourceName=" + integrityAuditEntity.getResourceName()
- + ", site=" + integrityAuditEntity.getSite() + ", createdDate=" + integrityAuditEntity.getCreatedDate()
- + LAST_UPDATED_MESSAGE + integrityAuditEntity.getLastUpdated() + ", designated="
- + integrityAuditEntity.isDesignated());
- }
-
- /*
- * If more than (auditCompletionIntervalMillis * 2) milliseconds have elapsed since we last ran
- * the audit, reset auditCompleted, so
- *
- * 1) we'll eventually re-run the audit, if no other node picks up the designation.
- *
- * or
- *
- * 2) We'll run the audit when the round robin comes back to us.
- */
- private boolean resetAuditCompleted(boolean auditCompleted, IntegrityAuditEntity thisEntity) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("resetAuditCompleted: auditCompleted=" + auditCompleted + "; for thisEntity, resourceName="
- + thisEntity.getResourceName() + PERSISTENCE_MESSAGE + thisEntity.getPersistenceUnit()
- + LAST_UPDATED_MESSAGE + thisEntity.getLastUpdated());
- }
-
- long timeDifference;
-
- var currentTime = AuditorTime.getInstance().getDate();
- var lastUpdated = thisEntity.getLastUpdated();
-
- long lastUpdatedTime = lastUpdated.getTime();
- timeDifference = currentTime.getTime() - lastUpdatedTime;
-
- if (timeDifference > (AUDIT_COMPLETION_INTERVAL * AUDIT_RESET_CYCLES)) {
- if (logger.isDebugEnabled()) {
- logger.debug("resetAuditCompleted: Resetting auditCompleted for resourceName=" + this.resourceName);
- }
- auditCompleted = false;
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "resetAuditCompleted: For resourceName=" + resourceName + ", time since last update is only "
- + timeDifference + "; retaining current value for auditCompleted");
- }
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("resetAuditCompleted: Exiting and returning auditCompleted=" + auditCompleted
- + ", timeDifference=" + timeDifference);
- }
- return auditCompleted;
- }
-
- private void runAudit(DbAudit dbAudit) throws IntegrityAuditException {
-
- if (logger.isDebugEnabled()) {
- logger.debug("runAudit: Entering, dbAudit=" + dbAudit + "; notifying other resources that resourceName="
- + this.resourceName + " is current");
- }
-
- /*
- * changeDesignated marks all other nodes as non-designated and this node as designated.
- */
- dbDao.changeDesignated(this.resourceName, this.persistenceUnit, this.nodeType);
-
- if (logger.isDebugEnabled()) {
- logger.debug("runAudit: Running audit for persistenceUnit=" + this.persistenceUnit + " on resourceName="
- + this.resourceName);
- }
-
- dbAudit.dbAudit(this.resourceName, this.persistenceUnit, this.nodeType);
-
- if (logger.isDebugEnabled()) {
- logger.debug("runAudit: Exiting");
- }
-
- }
-
- /**
- * Indicates that the {@link #run()} method has started. This method simply returns,
- * and may overridden by junit tests.
- *
- * @throws InterruptedException can be interrupted
- */
- public void runStarted() throws InterruptedException {
- // does nothing
- }
-
- /**
- * Indicates that an audit has completed. This method simply returns, and may
- * overridden by junit tests.
- *
- * @throws InterruptedException can be interrupted
- */
- public void auditCompleted() throws InterruptedException {
- // does nothing
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java
deleted file mode 100644
index 5bfedaac..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/AuditorTime.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import java.util.function.Supplier;
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-import org.onap.policy.common.utils.time.CurrentTime;
-
-/**
- * "Current" time used by IntegrityMonitor classes.
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class AuditorTime {
-
- /**
- * Instance to be used.
- */
- private static final CurrentTime currentTime = new CurrentTime();
-
- /**
- * Supplies the instance to be used for accessing the current time. This may be
- * overridden by junit tests to provide a different time instance for each thread when
- * multiple threads are run in parallel.
- */
- private static Supplier<CurrentTime> supplier = () -> currentTime;
-
- /**
- * Get instance.
- *
- * @return the CurrentTime singleton
- */
- public static CurrentTime getInstance() {
- return supplier.get();
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java
deleted file mode 100644
index 22ffa08e..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAudit.java
+++ /dev/null
@@ -1,503 +0,0 @@
-/*--
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import jakarta.persistence.Table;
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.Set;
-import org.apache.commons.lang3.SerializationUtils;
-import org.apache.commons.lang3.builder.RecursiveToStringStyle;
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-/**
- * class DbAudit does actual auditing of DB tables.
- */
-public class DbAudit {
-
- private static final Logger logger = FlexLogger.getLogger(DbAudit.class);
-
- private static final String COMMA_RESOURCE_NAME = ", resourceName=";
-
- private static final long DB_AUDIT_UPDATE_MS = 5000L;
- private static final long DB_AUDIT_SLEEP_MS = 2000L;
-
- DbDao dbDao = null;
-
- /**
- * Construct an instance with the given DbDao.
- *
- * @param dbDao the DbDao
- */
- public DbAudit(DbDao dbDao) {
-
- logger.debug("Constructor: Entering");
-
- this.dbDao = dbDao;
-
- logger.debug("Constructor: Exiting");
- }
-
- /**
- * dbAudit actually does the audit.
- *
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param nodeType the node type
- * @throws IntegrityAuditException if an error occurs
- */
- public void dbAudit(String resourceName, String persistenceUnit, String nodeType) throws IntegrityAuditException {
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Entering, resourceName=" + resourceName + ", persistenceUnit=" + persistenceUnit
- + ", nodeType=" + nodeType);
- }
-
- // Get all IntegrityAudit entries so we can get the DB access info
- List<IntegrityAuditEntity> iaeList = dbDao.getIntegrityAuditEntities(persistenceUnit, nodeType);
- if (iaeList == null || iaeList.isEmpty()) {
-
- String msg = "DbAudit: for node " + resourceName + " Found no IntegrityAuditEntity entries";
- logger.error(MessageCodes.ERROR_AUDIT, msg);
- throw new DbAuditException(msg);
-
- } else if (iaeList.size() == 1) {
-
- Long iaeId = null;
- String iaeRn = null;
- String iaeNt = null;
- String iaeS = null;
- for (IntegrityAuditEntity iae : iaeList) {
- iaeId = iae.getId();
- iaeRn = iae.getResourceName();
- iaeNt = iae.getNodeType();
- iaeS = iae.getSite();
- }
- String msg = "DbAudit: Found only one IntegrityAuditEntity entry:" + " ID = " + iaeId + " ResourceName = "
- + iaeRn + " NodeType = " + iaeNt + " Site = " + iaeS;
- logger.warn(msg);
- return;
- }
-
- // Obtain all persistence class names for the PU we are auditing
- Set<String> classNameSet = dbDao.getPersistenceClassNames();
- if (classNameSet == null || classNameSet.isEmpty()) {
-
- String msg = "DbAudit: For node " + resourceName + " Found no persistence class names";
- logger.error(MessageCodes.ERROR_AUDIT, msg);
- throw new DbAuditException(msg);
-
- }
-
- /*
- * Retrieve myIae. We are going to compare the local class entries against all other DB
- * nodes. Since the audit is run in a round-robin, every instance will be compared against
- * every other instance.
- */
- var myIae = dbDao.getMyIntegrityAuditEntity();
-
- if (myIae == null) {
-
- String msg = "DbAudit: Found no IntegrityAuditEntity entry for resourceName: " + resourceName
- + " persistenceUnit: " + persistenceUnit;
- logger.error(MessageCodes.ERROR_AUDIT, msg);
- throw new DbAuditException(msg);
-
- }
- /*
- * This is the map of mismatched entries indexed by className. For each class name there is
- * a list of mismatched entries
- */
- Map<String, Set<Object>> misMatchedMap = new HashMap<>();
-
- compareList(persistenceUnit, iaeList, myIae, classNameSet, misMatchedMap);
-
- // If misMatchedMap is not empty, retrieve the entries in each misMatched list and compare
- // again
- recompareList(resourceName, persistenceUnit, iaeList, myIae, misMatchedMap);
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Exiting");
- }
- }
-
- private void compareList(String persistenceUnit, List<IntegrityAuditEntity> iaeList, IntegrityAuditEntity myIae,
- Set<String> classNameSet, Map<String, Set<Object>> misMatchedMap)
- throws IntegrityAuditException {
-
- // We need to keep track of how long the audit is taking
- long startTime = AuditorTime.getInstance().getMillis();
-
- // Retrieve all instances of the class for each node
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Traversing classNameSet, size=" + classNameSet.size());
- }
- for (String clazzName : classNameSet) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: clazzName=" + clazzName);
- }
-
- // all instances of the class for myIae
- Map<Object, Object> myEntries = dbDao.getAllMyEntries(clazzName);
- // get a map of the objects indexed by id. Does not necessarily have any entries
-
- compareMineWithTheirs(persistenceUnit, iaeList, myIae, misMatchedMap, clazzName, myEntries);
-
- // Time check
- startTime = timeCheck("First", startTime);
- }
-
- // check if misMatchedMap is empty
- if (misMatchedMap.isEmpty()) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Exiting, misMatchedMap is empty");
- }
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Doing another comparison; misMatchedMap.size()=" + misMatchedMap.size());
- }
- }
- }
-
- private void compareMineWithTheirs(String persistenceUnit, List<IntegrityAuditEntity> iaeList,
- IntegrityAuditEntity myIae, Map<String, Set<Object>> misMatchedMap, String clazzName,
- Map<Object, Object> myEntries) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Traversing iaeList, size=" + iaeList.size());
- }
- for (IntegrityAuditEntity iae : iaeList) {
- if (iae.getId() == myIae.getId()) {
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: My Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName());
- }
- continue; // no need to compare with self
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Id=" + iae.getId() + COMMA_RESOURCE_NAME + iae.getResourceName());
- }
-
- // get a map of the instances for their iae indexed by id
- Map<Object, Object> theirEntries =
- dbDao.getAllEntries(persistenceUnit, getTheirDaoProperties(iae), clazzName);
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: For persistenceUnit=" + persistenceUnit + ", clazzName=" + clazzName
- + ", theirEntries.size()=" + theirEntries.size());
- }
-
- /*
- * Compare myEntries with theirEntries and get back a set of mismatched IDs.
- * Collect the IDs for the class where a mismatch occurred. We will check them
- * again for all nodes later.
- */
- compareMineWithTheirs(myEntries, theirEntries, clazzName, misMatchedMap);
- }
- }
-
- private void compareMineWithTheirs(Map<Object, Object> myEntries, Map<Object, Object> theirEntries,
- String clazzName, Map<String, Set<Object>> misMatchedMap) {
-
- Set<Object> misMatchedKeySet = compareEntries(myEntries, theirEntries);
- if (misMatchedKeySet.isEmpty()) {
- return;
- }
-
- Set<Object> misMatchedEntry = misMatchedMap.get(clazzName);
- if (misMatchedEntry == null) {
- misMatchedMap.put(clazzName, misMatchedKeySet);
- } else {
- misMatchedEntry.addAll(misMatchedKeySet);
- }
- }
-
- private long timeCheck(String type, long startTime) throws IntegrityAuditException {
- if ((AuditorTime.getInstance().getMillis() - startTime) >= DB_AUDIT_UPDATE_MS) {
- // update the timestamp
- dbDao.setLastUpdated();
- // reset the startTime
- return AuditorTime.getInstance().getMillis();
- } else {
- // sleep a couple seconds to break up the activity
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: " + type + " comparison; sleeping " + DB_AUDIT_SLEEP_MS + "ms");
- }
- sleep();
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: " + type + " comparison; waking from sleep");
- }
- return startTime;
- }
- }
-
- /**
- * Creates properties for the other db node.
- * @param iae target DB node
- * @return DAO properties for the given DB node
- */
- private Properties getTheirDaoProperties(IntegrityAuditEntity iae) {
- var theirProperties = new Properties();
-
- theirProperties.put(IntegrityAuditProperties.DB_DRIVER, iae.getJdbcDriver());
- theirProperties.put(IntegrityAuditProperties.DB_URL, iae.getJdbcUrl());
- theirProperties.put(IntegrityAuditProperties.DB_USER, iae.getJdbcUser());
- theirProperties.put(IntegrityAuditProperties.DB_PWD, iae.getJdbcPassword());
- theirProperties.put(IntegrityAuditProperties.SITE_NAME, iae.getSite());
- theirProperties.put(IntegrityAuditProperties.NODE_TYPE, iae.getNodeType());
-
- return theirProperties;
- }
-
- private void recompareList(String resourceName, String persistenceUnit, List<IntegrityAuditEntity> iaeList,
- IntegrityAuditEntity myIae, Map<String, Set<Object>> misMatchedMap)
- throws IntegrityAuditException {
-
- Set<String> classNameSet;
- long startTime;
- classNameSet = new HashSet<>(misMatchedMap.keySet());
- // We need to keep track of how long the audit is taking
- startTime = AuditorTime.getInstance().getMillis();
-
- // Retrieve all instances of the class for each node
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Second comparison; traversing classNameSet, size=" + classNameSet.size());
- }
-
- var errorCount = 0;
-
- for (String clazzName : classNameSet) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Second comparison; clazzName=" + clazzName);
- }
-
- // all instances of the class for myIae
- Set<Object> keySet = misMatchedMap.get(clazzName);
- Map<Object, Object> myEntries = dbDao.getAllMyEntries(clazzName, keySet);
- // get a map of the objects indexed by id
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Second comparison; traversing iaeList, size=" + iaeList.size());
- }
- errorCount += recompareMineWithTheirs(resourceName, persistenceUnit, iaeList, myIae, clazzName,
- keySet, myEntries);
- // Time check
- startTime = timeCheck("Second", startTime);
- }
-
- if (errorCount > 0) {
- String msg = " DB Audit: " + errorCount
- + " errors found. A large number of errors may indicate DB replication has stopped";
- logger.error(MessageCodes.ERROR_AUDIT, msg);
- }
- }
-
- private int recompareMineWithTheirs(String resourceName, String persistenceUnit, List<IntegrityAuditEntity> iaeList,
- IntegrityAuditEntity myIae, String clazzName, Set<Object> keySet, Map<Object, Object> myEntries)
- throws IntegrityAuditException {
-
- var errorCount = 0;
- for (IntegrityAuditEntity iae : iaeList) {
- if (iae.getId() == myIae.getId()) {
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Second comparison; My Id=" + iae.getId() + COMMA_RESOURCE_NAME
- + iae.getResourceName());
- }
- continue; // no need to compare with self
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("dbAudit: Second comparison; Id=" + iae.getId() + COMMA_RESOURCE_NAME
- + iae.getResourceName());
- }
-
- // get a map of the instances for their iae indexed by id
- Map<Object, Object> theirEntries =
- dbDao.getAllEntries(persistenceUnit, getTheirDaoProperties(iae), clazzName, keySet);
-
- /*
- * Compare myEntries with theirEntries and get back a set of mismatched IDs.
- * Collect the IDs for the class where a mismatch occurred. We will now write
- * an error log for each.
- */
- errorCount += recompareMineWithTheirs(resourceName, clazzName, myEntries, iae, theirEntries);
- }
- return errorCount;
- }
-
- private int recompareMineWithTheirs(String resourceName, String clazzName, Map<Object, Object> myEntries,
- IntegrityAuditEntity iae, Map<Object, Object> theirEntries) throws IntegrityAuditException {
- Set<Object> misMatchedKeySet = compareEntries(myEntries, theirEntries);
- if (misMatchedKeySet.isEmpty()) {
- return 0;
- }
-
- var keyBuilder = new StringBuilder();
- for (Object key : misMatchedKeySet) {
- keyBuilder.append(key.toString());
- keyBuilder.append(", ");
- }
- writeAuditSummaryLog(clazzName, resourceName, iae.getResourceName(), keyBuilder.toString());
- if (logger.isDebugEnabled()) {
- for (Object key : misMatchedKeySet) {
- writeAuditDebugLog(clazzName, resourceName, iae.getResourceName(), myEntries.get(key),
- theirEntries.get(key));
- }
- }
- return misMatchedKeySet.size();
- }
-
- /**
- * Sleeps a bit.
- *
- * @throws IntegrityAuditException if interrupted
- */
- private void sleep() throws IntegrityAuditException {
- try {
- AuditorTime.getInstance().sleep(DB_AUDIT_SLEEP_MS);
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new IntegrityAuditException(e);
- }
- }
-
- /**
- * compareEntries() will compare the lists of entries from the DB.
- *
- * @param myEntries the entries
- * @param theirEntries the entries to compare against myEntries
- * @return the set of differences
- */
- public Set<Object> compareEntries(Map<Object, Object> myEntries, Map<Object, Object> theirEntries) {
- /*
- * Compare the entries for the same key in each of the hashmaps. The comparison will be done
- * by serializing the objects (create a byte array) and then do a byte array comparison. The
- * audit will walk the local repository hash map comparing to the remote cluster hashmap and
- * then turn it around and walk the remote hashmap and look for any entries that are not
- * present in the local cluster hashmap.
- *
- * If the objects are not identical, the audit will put the object IDs on a list to try
- * after completing the audit of the table it is currently working on.
- *
- */
- HashSet<Object> misMatchedKeySet = new HashSet<>();
- for (Entry<Object, Object> ent : myEntries.entrySet()) {
- Object key = ent.getKey();
- byte[] mySerializedEntry = SerializationUtils.serialize((Serializable) ent.getValue());
- byte[] theirSerializedEntry = SerializationUtils.serialize((Serializable) theirEntries.get(key));
- if (!Arrays.equals(mySerializedEntry, theirSerializedEntry)) {
- logger.debug("compareEntries: For myEntries.key=" + key + ", entries do not match");
- misMatchedKeySet.add(key);
- } else {
- logger.debug("compareEntries: For myEntries.key=" + key + ", entries match");
- }
- }
- // now compare it in the other direction to catch entries in their set that is not in my set
- for (Entry<Object, Object> ent : theirEntries.entrySet()) {
- Object key = ent.getKey();
- byte[] mySerializedEntry = SerializationUtils.serialize((Serializable) myEntries.get(key));
- byte[] theirSerializedEntry = SerializationUtils.serialize((Serializable) ent.getValue());
- if (!Arrays.equals(mySerializedEntry, theirSerializedEntry)) {
- logger.debug("compareEntries: For theirEntries.key=" + key + ", entries do not match");
- misMatchedKeySet.add(key);
- } else {
- logger.debug("compareEntries: For theirEntries.key=" + key + ", entries match");
- }
- }
-
- // return a Set of the object IDs
- logger.debug("compareEntries: misMatchedKeySet.size()=" + misMatchedKeySet.size());
- return misMatchedKeySet;
- }
-
- /**
- * writeAuditDebugLog() writes the mismatched entry details to the debug log.
- *
- * @param clazzName the class name
- * @param resourceName1 resource name 1
- * @param resourceName2 resource name 2
- * @param entry1 entry 1
- * @param entry2 entry 2
- * @throws IntegrityAuditException if the given class cannot be found
- */
- public void writeAuditDebugLog(String clazzName, String resourceName1, String resourceName2, Object entry1,
- Object entry2) throws IntegrityAuditException {
- try {
- Class<?> entityClass = Class.forName(clazzName);
- String tableName = entityClass.getAnnotation(Table.class).name();
- String msg = "\nDB Audit Error: " + "\n Table Name: " + tableName
- + "\n Entry 1 (short prefix style): " + resourceName1 + ": "
- + new ReflectionToStringBuilder(entry1, ToStringStyle.SHORT_PREFIX_STYLE)
- + "\n Entry 2 (short prefix style): " + resourceName2 + ": "
- + (entry2 != null
- ? new ReflectionToStringBuilder(entry2, ToStringStyle.SHORT_PREFIX_STYLE).toString()
- : "null")
- + "\n Entry 1 (recursive style): " + resourceName1 + ": "
- + new ReflectionToStringBuilder(entry1, new RecursiveToStringStyle())
- + "\n Entry 2 (recursive style): " + resourceName2 + ": "
- + (entry2 != null
- ? new ReflectionToStringBuilder(entry2, new RecursiveToStringStyle()).toString()
- : "null");
- logger.debug(msg);
-
- } catch (ClassNotFoundException e) {
- throw new IntegrityAuditException(e);
- }
-
- }
-
- /**
- * writeAuditSummaryLog() writes a summary of the DB mismatches to the error log.
- *
- * @param clazzName the name of the class
- * @param resourceName1 resource name 1
- * @param resourceName2 resource name 2
- * @param keys the mismatched entry keys
- * @throws IntegrityAuditException if the given class cannot be found
- */
- public void writeAuditSummaryLog(String clazzName, String resourceName1, String resourceName2, String keys)
- throws IntegrityAuditException {
- try {
- Class<?> entityClass = Class.forName(clazzName);
- String tableName = entityClass.getAnnotation(Table.class).name();
- String msg = " DB Audit Error: Table Name: " + tableName + "; Mismatch between nodes: " + resourceName1
- + " and " + resourceName2 + "; Mismatched entries (keys): " + keys;
- logger.info(msg);
- } catch (ClassNotFoundException e) {
- throw new IntegrityAuditException(e);
- }
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java
deleted file mode 100644
index a539f6bd..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbAuditException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-public class DbAuditException extends IntegrityAuditException {
- private static final long serialVersionUID = 1L;
-
- public DbAuditException() {
- super();
- }
-
- public DbAuditException(String message) {
- super(message);
- }
-
- public DbAuditException(Throwable cause) {
- super(cause);
- }
-
- public DbAuditException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java
deleted file mode 100644
index ad96432d..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDao.java
+++ /dev/null
@@ -1,722 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.EntityTransaction;
-import jakarta.persistence.Persistence;
-import jakarta.persistence.Query;
-import jakarta.persistence.TypedQuery;
-import jakarta.persistence.criteria.CriteriaQuery;
-import jakarta.persistence.criteria.Root;
-import jakarta.persistence.metamodel.ManagedType;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.function.BiConsumer;
-import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-/**
- * class DbDao provides the inteface to the DBs for the purpose of audits.
- */
-public class DbDao {
- private static final Logger logger = FlexLogger.getLogger();
-
- private String resourceName;
- private String persistenceUnit;
- private String dbDriver;
- private String dbUrl;
- private String dbUser;
- private String siteName;
- private String nodeType;
- private Properties properties = null;
-
- private final EntityManagerFactory emf;
-
- /*
- * Supports designation serialization.
- */
- private static final Object lock = new Object();
-
- /*
- * Common strings.
- */
- private static final String RESOURCE_MESSAGE = "Resource: ";
- private static final String WITH_PERSISTENCE_MESSAGE = " with PersistenceUnit: ";
- private static final String DBDAO_MESSAGE = "DbDao: ";
- private static final String ENCOUNTERED_MESSAGE = "ecountered a problem in execution: ";
-
- /*
- * DB SELECT String.
- */
- private static final String SELECT_STRING = "Select i from IntegrityAuditEntity i "
- + "where i.resourceName=:rn and i.persistenceUnit=:pu";
-
- /**
- * DbDao Constructor.
- *
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @throws IntegrityAuditException if an error occurs
- */
- public DbDao(String resourceName, String persistenceUnit, Properties properties) throws IntegrityAuditException {
- this(resourceName, persistenceUnit, properties, null);
- }
-
- /**
- * DbDao Constructor.
- *
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @param altDbUrl may be {@code null}
- * @throws IntegrityAuditException if an error occurs
- */
- protected DbDao(String resourceName, String persistenceUnit, Properties properties, String altDbUrl)
- throws IntegrityAuditException {
- logger.debug("DbDao contructor: enter");
-
- validateProperties(resourceName, persistenceUnit, properties);
-
- emf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
-
- register(altDbUrl);
-
- logger.debug("DbDao contructor: exit");
- }
-
- /**
- * Release resources (i.e., the EntityManagerFactory).
- */
- public void destroy() {
- emf.close();
- }
-
- /**
- * validateProperties will validate the properties.
- *
- * @param resourceName the rseource name
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @throws IntegrityAuditPropertiesException if an error occurs
- */
- private void validateProperties(String resourceName, String persistenceUnit, Properties properties)
- throws IntegrityAuditPropertiesException {
- var badparams = new StringBuilder();
- if (IntegrityAudit.parmsAreBad(resourceName, persistenceUnit, properties, badparams)) {
- String msg = "DbDao: Bad parameters: badparams" + badparams;
- throw new IntegrityAuditPropertiesException(msg);
- }
- this.resourceName = resourceName;
- this.persistenceUnit = persistenceUnit;
- this.dbDriver = properties.getProperty(IntegrityAuditProperties.DB_DRIVER).trim();
- this.dbUrl = properties.getProperty(IntegrityAuditProperties.DB_URL).trim();
- this.dbUser = properties.getProperty(IntegrityAuditProperties.DB_USER).trim();
- this.siteName = properties.getProperty(IntegrityAuditProperties.SITE_NAME).trim();
- this.nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE).trim().toLowerCase();
- this.properties = properties;
- logger.debug("DbDao.assignProperties: exit:" + "\nresourceName: " + this.resourceName + "\npersistenceUnit: "
- + this.persistenceUnit + "\nproperties: " + this.properties);
- }
-
- /**
- * getAllMyEntries gets all the DB entries for a particular class.
- *
- * @param className the class name
- * @return all the DB entries for the given class
- */
- public Map<Object, Object> getAllMyEntries(String className) {
- logger.debug("getAllMyEntries: Entering, className=" + className);
- HashMap<Object, Object> resultMap = new HashMap<>();
- var em = emf.createEntityManager();
- try {
- getObjectsFromCriteriaBuilder(className, emf, em, resultMap);
- } catch (Exception e) {
- logger.error("getAllEntries encountered exception: ", e);
- }
- em.close();
- logger.debug("getAllMyEntries: Exit, resultMap.keySet()=" + resultMap.keySet());
- return resultMap;
- }
-
- /**
- * getAllMyEntries gets all entries for a class.
- *
- * @param className the name of the class
- * @param keySet the keys to get the entries for
- * @return the map of requested entries
- */
- public Map<Object, Object> getAllMyEntries(String className, Set<Object> keySet) {
- logger.debug("getAllMyEntries: Entering, className=" + className + ",\n keySet=" + keySet);
-
- HashMap<Object, Object> resultMap = new HashMap<>();
- var em = emf.createEntityManager();
- try {
- Class<?> clazz = Class.forName(className);
- for (Object key : keySet) {
- Object entry = em.find(clazz, key);
- resultMap.put(key, entry);
- }
- } catch (Exception e) {
- logger.error("getAllMyEntries encountered exception: ", e);
- }
- em.close();
-
- logger.debug("getAllMyEntries: Returning resultMap, size=" + resultMap.size());
- return resultMap;
- }
-
- /**
- * getAllEntries gets all entries for a particular persistence unit adn className.
- *
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @param className the class name
- * @return the map of entries
- */
- public Map<Object, Object> getAllEntries(String persistenceUnit, Properties properties, String className) {
-
- logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n className=" + className);
- HashMap<Object, Object> resultMap = new HashMap<>();
-
- var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
- var em = theEmf.createEntityManager();
-
- try {
- getObjectsFromCriteriaBuilder(className, theEmf, em, resultMap);
- } catch (Exception e) {
- logger.error("getAllEntries encountered exception:", e);
- }
- em.close();
- theEmf.close();
-
- logger.debug("getAllEntries: Returning resultMap, size=" + resultMap.size());
-
- return resultMap;
- }
-
-
- /**
- * getAllEntries gets all entries for a persistence unit.
- *
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @param className the class name
- * @param keySet the keys
- * @return the map of entries
- */
-
- public Map<Object, Object> getAllEntries(String persistenceUnit, Properties properties, String className,
- Set<Object> keySet) {
- logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n properties= " + properties
- + ",\n className=" + className + ",\n keySet= " + keySet);
- var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
- var em = theEmf.createEntityManager();
- HashMap<Object, Object> resultMap = new HashMap<>();
- try {
- Class<?> clazz = Class.forName(className);
- for (Object key : keySet) {
- Object entry = em.find(clazz, key);
- resultMap.put(key, entry);
- }
- } catch (Exception e) {
- String msg = "getAllEntries encountered exception: " + e;
- logger.error(msg, e);
- }
- em.close();
- theEmf.close();
- logger.debug("getAllEntries: Exit, resultMap, size=" + resultMap.size());
- return resultMap;
- }
-
- /**
- * getIntegrityAuditEntities() Get all the IntegrityAuditEntities for a particular persistence
- * unit and node type.
- *
- * @param persistenceUnit the persistence unit
- * @param nodeType the node type
- * @return the list of IntegrityAuditEntity
- * @throws DbDaoTransactionException if an error occurs
- */
- @SuppressWarnings("unchecked")
- public List<IntegrityAuditEntity> getIntegrityAuditEntities(String persistenceUnit, String nodeType)
- throws DbDaoTransactionException {
- logger.debug("getIntegrityAuditEntities: Entering, persistenceUnit=" + persistenceUnit + ",\n nodeType= "
- + nodeType);
- try {
- List<IntegrityAuditEntity> iaeList;
- try (var em = emf.createEntityManager()) {
- // Start a transaction
- EntityTransaction et = em.getTransaction();
-
- et.begin();
-
- // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
- // found, create a new entry
- var iaequery = em
- .createQuery("Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt");
- iaequery.setParameter("pu", persistenceUnit);
- iaequery.setParameter("nt", nodeType);
-
- iaeList = iaequery.getResultList();
-
- // commit transaction
- et.commit();
- }
- logger.debug("getIntegrityAuditEntities: Exit, iaeList=" + iaeList);
- return iaeList;
- } catch (Exception e) {
- String msg = DBDAO_MESSAGE + "getIntegrityAuditEntities() " + ENCOUNTERED_MESSAGE;
- logger.error(msg, e);
- throw new DbDaoTransactionException(e);
- }
-
- }
-
- /**
- * getMyIntegrityAuditEntity() gets my IntegrityAuditEntity.
- *
- * @return the IntegrityAuditEntity
- * @throws DbDaoTransactionException if an error occurs
- */
- public IntegrityAuditEntity getMyIntegrityAuditEntity() throws DbDaoTransactionException {
-
- return updateIae("getMyIntegrityAuditEntity", this.resourceName, this.persistenceUnit, (em, iae) -> {
-
- if (iae != null) {
- // refresh the object from DB in case cached data was returned
- em.refresh(iae);
- logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit
- + " exists");
- } else {
- // If it does not exist, log an error
- logger.error("Attempting to setLastUpdated" + " on an entry that does not exist: resource "
- + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit);
- }
- });
- }
-
-
- /**
- * getIntegrityAuditEntity() gets the IntegrityAuditEntity with a particular ID.
- *
- * @param id the ID
- * @return the IntegrityAuditEntity
- * @throws DbDaoTransactionException if an error occurs
- */
- public IntegrityAuditEntity getIntegrityAuditEntity(long id) throws DbDaoTransactionException {
- try {
- IntegrityAuditEntity iae;
- try (var em = emf.createEntityManager()) {
-
- // Start a transaction
- EntityTransaction et = em.getTransaction();
-
- et.begin();
-
- iae = em.find(IntegrityAuditEntity.class, id);
-
- et.commit();
- }
-
- return iae;
- } catch (Exception e) {
- String msg = DBDAO_MESSAGE + "getIntegrityAuditEntity() " + ENCOUNTERED_MESSAGE;
- logger.error(msg + e);
- throw new DbDaoTransactionException(e);
- }
- }
-
- /**
- * getPersistenceClassNames() gets all the persistence class names.
- *
- * @return the persistence class names
- */
- public Set<String> getPersistenceClassNames() {
- logger.debug("DbDao: getPersistenceClassNames() entry");
- HashSet<String> returnList = new HashSet<>();
- final var mm = emf.getMetamodel();
- logger.debug("\n" + persistenceUnit + " persistence unit classes:");
- for (final ManagedType<?> managedType : mm.getManagedTypes()) {
- Class<?> clazz = managedType.getJavaType();
- logger.debug(" " + clazz.getSimpleName());
- returnList.add(clazz.getName()); // the full class name needed to make a query using jpa
- }
- logger.debug("DbDao: getPersistenceClassNames() exit");
- return returnList;
- }
-
- /**
- * Register the IntegrityAudit instance.
- *
- * @param altDbUrl alternate DB URL to be placed into the record, or {@code null} to use the
- * default
- */
- private void register(String altDbUrl) throws DbDaoTransactionException {
-
- updateIae("register", this.resourceName, this.persistenceUnit, (em, iae) -> {
- IntegrityAuditEntity iae2 = iae;
-
- // If it already exists, we just want to update the properties and lastUpdated date
- if (iae2 != null) {
- // refresh the object from DB in case cached data was returned
- em.refresh(iae2);
- logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit
- + " exists and entry be updated");
- } else {
- // If it does not exist, we also must add teh resourceName, persistenceUnit and
- // designated values
- logger.info("Adding resource " + resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit
- + " to IntegrityAuditEntity table");
- iae2 = new IntegrityAuditEntity();
- iae2.setResourceName(this.resourceName);
- iae2.setPersistenceUnit(this.persistenceUnit);
- iae2.setDesignated(false);
- }
-
- register2(altDbUrl, em, iae2);
- });
-
- }
-
- private void register2(String altDbUrl, EntityManager em, IntegrityAuditEntity iae) {
- // update/set properties in entry
- iae.setSite(this.siteName);
- iae.setNodeType(this.nodeType);
- iae.setJdbcDriver(this.dbDriver);
- iae.setJdbcPassword(properties.getProperty(IntegrityAuditProperties.DB_PWD).trim());
- iae.setJdbcUrl(altDbUrl == null ? this.dbUrl : altDbUrl);
- iae.setJdbcUser(dbUser);
-
- em.persist(iae);
- // flush to the DB
- em.flush();
- }
-
- public void setDesignated(boolean designated) throws DbDaoTransactionException {
- setDesignated(this.resourceName, this.persistenceUnit, designated);
- }
-
- /**
- * Set designated.
- *
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param desig true if is designated
- * @throws DbDaoTransactionException if an error occurs
- */
- public void setDesignated(String resourceName, String persistenceUnit, boolean desig)
- throws DbDaoTransactionException {
- logger.debug("setDesignated: enter, resourceName: " + resourceName + ", persistenceUnit: " + persistenceUnit
- + ", designated: " + desig);
-
- updateIae("setDesignated", resourceName, persistenceUnit, (em, iae) -> {
-
- if (iae != null) {
- // refresh the object from DB in case cached data was returned
- em.refresh(iae);
- logger.info(RESOURCE_MESSAGE + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit
- + " exists and designated be updated");
- iae.setDesignated(desig);
-
- em.persist(iae);
- // flush to the DB
- em.flush();
- } else {
- // If it does not exist, log an error
- logger.error("Attempting to setDesignated(" + desig + ") on an entry that does not exist:"
- + " resource " + resourceName + WITH_PERSISTENCE_MESSAGE + persistenceUnit);
- }
- });
-
- }
-
- /**
- * Queries for an audit entity and then updates it using an "updater" function.
- *
- * @param methodName name of the method that invoked this
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param updater function to update the entity; the argument will be the entity to be
- * updated, or {@code null} if the entity is not found
- * @return the entity that was found, or {@code null} if the entity is not found
- * @throws DbDaoTransactionException if an error occurs
- */
- private IntegrityAuditEntity updateIae(String methodName, String resourceName, String persistenceUnit,
- BiConsumer<EntityManager, IntegrityAuditEntity> updater)
- throws DbDaoTransactionException {
- try {
-
- IntegrityAuditEntity iae;
- try (var em = emf.createEntityManager()) {
-
- // Start a transaction
- EntityTransaction et = em.getTransaction();
-
- et.begin();
-
- // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
- // found, create a new entry
- TypedQuery<IntegrityAuditEntity> iaequery = em.createQuery(SELECT_STRING, IntegrityAuditEntity.class);
- iaequery.setParameter("rn", resourceName);
- iaequery.setParameter("pu", persistenceUnit);
-
- List<IntegrityAuditEntity> iaeList = iaequery.getResultList();
-
- if (!iaeList.isEmpty()) {
- // ignores multiple results
- iae = iaeList.get(0);
-
- } else {
- // If it does not exist
- iae = null;
- }
-
- updater.accept(em, iae);
-
- // close the transaction
- et.commit();
- }
-
- return iae;
-
- } catch (Exception e) {
- String msg = DBDAO_MESSAGE + methodName + "() " + ENCOUNTERED_MESSAGE;
- logger.error(msg + e);
- throw new DbDaoTransactionException(e);
- }
-
- }
-
- /**
- * Set last updated.
- *
- * @throws DbDaoTransactionException if an error occurs
- */
- public void setLastUpdated() throws DbDaoTransactionException {
- logger.debug("setLastUpdated: enter, resourceName: " + this.resourceName + ", persistenceUnit: "
- + this.persistenceUnit);
-
- updateIae("setLastUpdated", this.resourceName, this.persistenceUnit, (em, iae) -> {
-
- if (iae != null) {
- // refresh the object from DB in case cached data was returned
- em.refresh(iae);
- logger.info(RESOURCE_MESSAGE + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit
- + " exists and lastUpdated be updated");
- iae.setLastUpdated(AuditorTime.getInstance().getDate());
-
- em.persist(iae);
- // flush to the DB
- em.flush();
- } else {
- // If it does not exist, log an error
- logger.error("Attempting to setLastUpdated" + " on an entry that does not exist:" + " resource "
- + this.resourceName + WITH_PERSISTENCE_MESSAGE + this.persistenceUnit);
- }
- });
- }
-
- /**
- * Normally this method should only be used in a JUnit test environment. Manually deletes all
- * PDP records in droolspdpentity table.
- */
- public int deleteAllIntegrityAuditEntities() throws DbDaoTransactionException {
-
- try {
-
- if (!IntegrityAudit.isUnitTesting()) {
- String msg = DBDAO_MESSAGE + "deleteAllIntegrityAuditEntities() "
- + "should only be invoked during JUnit testing";
- logger.error(msg);
- throw new DbDaoTransactionException(msg);
- }
-
- int returnCode;
- try (var em = emf.createEntityManager()) {
- // Start a transaction
- EntityTransaction et = em.getTransaction();
-
- et.begin();
-
- // if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
- // found, create a new entry
- var iaequery = em.createQuery("Delete from IntegrityAuditEntity");
-
- returnCode = iaequery.executeUpdate();
-
- // commit transaction
- et.commit();
- }
-
- logger.info("deleteAllIntegrityAuditEntities: returnCode=" + returnCode);
-
- return returnCode;
-
- } catch (Exception e) {
- String msg = DBDAO_MESSAGE + "deleteAllIntegrityAuditEntities() " + "encountered a problem in execution: ";
- logger.error(msg + e);
- throw new DbDaoTransactionException(e);
- }
-
- }
-
- /**
- * Changes designation to specified resourceName
- *
- * <p>static lock object in conjunction with synchronized keyword ensures that designation
- * changes are done serially within a resource. I.e. static lock ensures that multiple
- * instantiations of DbDao don't interleave changeDesignated() invocations and potentially
- * produce simultaneous designations.
- *
- * <p>Optimistic locking (the default, versus pessimistic) is sufficient to avoid simultaneous
- * designations from interleaved changeDesignated() invocations from different resources
- * (entities), because it prevents "dirty" and "non-repeatable" reads.
- *
- * <p>See www.objectdb.com/api/java/jpa/LockModeType
- *
- * <p>and
- *
- * <p>stackoverflow.com/questions/2120248/how-to-synchronize-a-static-
- * variable-among-threads-running-different-instances-o
- */
- public void changeDesignated(String resourceName, String persistenceUnit, String nodeType)
- throws DbDaoTransactionException {
-
- if (logger.isDebugEnabled()) {
- logger.debug("changeDesignated: Entering, resourceName=" + resourceName + ", persistenceUnit="
- + persistenceUnit + ", nodeType=" + nodeType);
- }
-
- long startTime = AuditorTime.getInstance().getMillis();
-
- synchronized (lock) {
- try (var em = emf.createEntityManager()) {
- try {
- em.getTransaction().begin();
-
- /*
- * Define query
- */
- var query = em.createQuery(
- "Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt");
- query.setParameter("pu", persistenceUnit);
- query.setParameter("nt", nodeType);
-
- /*
- * Execute query using pessimistic write lock. This ensures that if anyone else is
- * currently reading the records we'll throw a LockTimeoutException.
- */
- setDesignatedEntity(resourceName, query);
-
- if (logger.isDebugEnabled()) {
- logger.debug("changeDesignated: Committing designation to resourceName=" + resourceName);
- }
- em.getTransaction().commit();
-
- /*
- * If we get a LockTimeoutException, no harm done really. We'll probably be
- * successful on the next attempt. The odds of another DbDao instance on this entity
- * or another entity attempting a simultaneous IntegrityAuditEntity table
- * read/update are pretty slim (we're only in this method for two or three
- * milliseconds)
- */
- } catch (Exception e) {
- String errorMsg;
- try {
- em.getTransaction().rollback();
- errorMsg = "DbDao: changeDesignated() caught Exception, message=" + e.getMessage();
- } catch (Exception rollbackException) {
- errorMsg = "DbDao: changeDesignated() caught Exception, message="
- + e.getMessage() + ". Error rolling back transaction.";
- }
- logger.error(errorMsg + e);
- throw new DbDaoTransactionException(errorMsg, e);
- }
- }
-
- } // end synchronized block
-
- if (logger.isDebugEnabled()) {
- logger.debug("changeDesignated: Exiting; time expended="
- + (AuditorTime.getInstance().getMillis() - startTime) + "ms");
- }
-
- }
-
- private void setDesignatedEntity(String resourceName, Query query) {
- for (Object o : query.getResultList()) {
- if (!(o instanceof IntegrityAuditEntity integrityAuditEntity)) {
- continue;
- }
-
- if (integrityAuditEntity.getResourceName().equals(resourceName)) {
- if (logger.isDebugEnabled()) {
- logger.debug("changeDesignated: Designating resourceName="
- + integrityAuditEntity.getResourceName());
- }
- integrityAuditEntity.setDesignated(true);
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("changeDesignated: Removing designation from resourceName="
- + integrityAuditEntity.getResourceName());
- }
- integrityAuditEntity.setDesignated(false);
- }
- }
- }
-
- /**
- * Collects all objects from a criteria builder based on className.
- *
- * @param className type of objects for resultMap
- * @param emf the entity manager factory to be used
- * @param em entity manager to be used
- * @param resultMap the result map for objects queried
- * @throws ClassNotFoundException if class for criteria builder doesn't exist
- */
- private void getObjectsFromCriteriaBuilder(String className, EntityManagerFactory emf, EntityManager em,
- HashMap<Object, Object> resultMap)
- throws ClassNotFoundException {
- var cb = em.getCriteriaBuilder();
- CriteriaQuery<Object> cq = cb.createQuery();
- Root<?> rootEntry = cq.from(Class.forName(className));
- CriteriaQuery<Object> all = cq.select(rootEntry);
- TypedQuery<Object> allQuery = em.createQuery(all);
- List<Object> objectList = allQuery.getResultList();
- // Now create the map
-
- var util = emf.getPersistenceUnitUtil();
- for (Object o : objectList) {
- Object key = util.getIdentifier(o);
- resultMap.put(key, o);
- }
- }
-
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java
deleted file mode 100644
index dc1c6f14..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/DbDaoTransactionException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-public class DbDaoTransactionException extends IntegrityAuditException {
- private static final long serialVersionUID = 1L;
-
- public DbDaoTransactionException() {
- super();
- }
-
- public DbDaoTransactionException(String message) {
- super(message);
- }
-
- public DbDaoTransactionException(Throwable cause) {
- super(cause);
- }
-
- public DbDaoTransactionException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java
deleted file mode 100644
index 66ab307c..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import java.util.Properties;
-import lombok.Getter;
-import lombok.Setter;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.ia.IntegrityAuditProperties.NodeTypeEnum;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-/**
- * class IntegrityAudit Audits all persisted entities for all resource clusters for all sites and
- * logs any anomalies.
- */
-public class IntegrityAudit {
-
- private static final Logger logger = FlexLogger.getLogger(IntegrityAudit.class);
-
- @Getter
- @Setter
- private static boolean unitTesting;
-
- @Getter
- private boolean threadInitialized = false;
-
- AuditThread auditThread = null;
-
- private String persistenceUnit;
- private Properties properties;
- private String resourceName;
-
-
- /*
- * This is the audit period in milliseconds. For example, if it had a value of 3600000, the
- * audit can only run once per hour. If it has a value of 6000, it can run once per minute.
- *
- * Values: integrityAuditPeriodSeconds < 0 (negative number) indicates the audit is off
- * integrityAuditPeriodSeconds == 0 indicates the audit is to run continuously
- * integrityAuditPeriodSeconds > 0 indicates the audit is to run at most once during the
- * indicated period
- *
- */
- @Getter
- private int integrityAuditPeriodSeconds;
-
- /**
- * IntegrityAudit constructor.
- *
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @throws IntegrityAuditException if an error occurs
- */
- public IntegrityAudit(String resourceName, String persistenceUnit, Properties properties)
- throws IntegrityAuditException {
-
- logger.info("Constructor: Entering and checking for nulls");
- var parmList = new StringBuilder();
- if (parmsAreBad(resourceName, persistenceUnit, properties, parmList)) {
- logger.error("Constructor: Parms contain nulls; cannot run audit for resourceName=" + resourceName
- + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList);
- throw new IntegrityAuditException("Constructor: Parms contain nulls; cannot run audit for resourceName="
- + resourceName + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList);
- }
-
- this.persistenceUnit = persistenceUnit;
- this.properties = properties;
- this.resourceName = resourceName;
-
- // IntegrityAuditProperties.AUDIT_PERIOD_SECONDS and
- // IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS are allowed to be null
- if (properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS) != null) {
- this.integrityAuditPeriodSeconds =
- Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim());
- } else {
- // If it is null, set it to the default value
- this.integrityAuditPeriodSeconds = IntegrityAuditProperties.DEFAULT_AUDIT_PERIOD_SECONDS;
- }
- logger.info("Constructor: Exiting");
-
- }
-
- /**
- * Determine if the nodeType conforms to the required node types.
- */
- public static boolean isNodeTypeEnum(String nt) {
- for (NodeTypeEnum n : NodeTypeEnum.values()) {
- if (n.toString().equalsIgnoreCase(nt)) {
- return true;
- }
- }
- return false;
- }
-
-
- /**
- * Makes sure we don't try to run the audit with bad parameters.
- */
- public static boolean parmsAreBad(String resourceName, String persistenceUnit, Properties properties,
- StringBuilder badparams) {
-
- boolean parmsAreBad = checkEmpty(badparams, "resourceName", resourceName);
- parmsAreBad = checkEmpty(badparams, "persistenceUnit", persistenceUnit) || parmsAreBad;
-
- if (properties == null || properties.isEmpty()) {
- badparams.append("properties ");
- parmsAreBad = true;
- } else {
- parmsAreBad = checkProperties(properties, badparams) || parmsAreBad;
- } // End else
- logger.debug("parmsAreBad: exit:" + "\nresourceName: " + resourceName + "\npersistenceUnit: " + persistenceUnit
- + "\nproperties: " + properties);
-
- return parmsAreBad;
- }
-
- private static boolean checkEmpty(StringBuilder builder, String name, String value) {
- if (StringUtils.isEmpty(value)) {
- builder.append(name);
- builder.append(' ');
- return true;
-
- } else {
- return false;
- }
- }
-
- private static boolean checkProperties(Properties properties, StringBuilder badparams) {
- boolean parmsAreBad =
- checkEmpty(badparams, "dbDriver", properties.getProperty(IntegrityAuditProperties.DB_DRIVER));
- parmsAreBad = checkEmpty(badparams, "dbUrl", properties.getProperty(IntegrityAuditProperties.DB_URL))
- || parmsAreBad;
- parmsAreBad = checkEmpty(badparams, "dbUser", properties.getProperty(IntegrityAuditProperties.DB_USER))
- || parmsAreBad;
-
- // dbPwd may be empty
- checkEmpty(badparams, "dbPwd", properties.getProperty(IntegrityAuditProperties.DB_PWD));
-
- parmsAreBad = checkEmpty(badparams, "siteName", properties.getProperty(IntegrityAuditProperties.SITE_NAME))
- || parmsAreBad;
- parmsAreBad = checkNodeType(properties, badparams) || parmsAreBad;
-
- return checkAuditPeriod(properties, badparams) || parmsAreBad;
- }
-
- private static boolean checkNodeType(Properties properties, StringBuilder badparams) {
- String nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE);
- if (nodeType == null || nodeType.isEmpty()) {
- badparams.append("nodeType ");
- return true;
- } else {
- nodeType = nodeType.trim();
- if (!isNodeTypeEnum(nodeType)) {
- badparams.append("nodeType must be one of[");
- for (NodeTypeEnum n : NodeTypeEnum.values()) {
- badparams.append(n.toString());
- badparams.append(' ');
- }
- badparams.append("] ");
- return true;
- }
- }
- return false;
- }
-
- private static boolean checkAuditPeriod(Properties properties, StringBuilder badparams) {
- // IntegrityAuditProperties.AUDIT_PERIOD_SECONDS and
- // IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS are allowed to be null
- if (properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS) != null) {
- try {
- Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim());
- } catch (NumberFormatException nfe) {
- badparams.append(", auditPeriodSeconds="
- + properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim());
- return true;
- }
- }
- return false;
- }
-
- /**
- * Starts the audit thread.
- *
- * @throws IntegrityAuditException if an error occurs
- */
- public void startAuditThread() throws IntegrityAuditException {
- logger.info("startAuditThread: Entering");
-
- if (integrityAuditPeriodSeconds >= 0) {
- this.auditThread = makeAuditThread(this.resourceName, this.persistenceUnit,
- this.properties, integrityAuditPeriodSeconds);
- logger.info("startAuditThread: Audit started and will run every " + integrityAuditPeriodSeconds
- + " seconds");
- this.auditThread.start();
-
- } else {
- logger.info("startAuditThread: Suppressing integrity audit, integrityAuditPeriodSeconds="
- + integrityAuditPeriodSeconds);
- }
-
- logger.info("startAuditThread: Exiting");
- }
-
- /**
- * Stops the audit thread.
- */
- public void stopAuditThread() {
-
- logger.info("stopAuditThread: Entering");
-
- if (this.auditThread != null) {
- this.auditThread.interrupt();
- } else {
- logger.info("stopAuditThread: auditThread never instantiated; no need to interrupt");
- }
-
- logger.info("stopAuditThread: Exiting");
- }
-
- public void setThreadInitialized(boolean isThreadInitialized) {
- logger.info("setThreadInitialized: Setting isThreadInitialized=" + isThreadInitialized);
- this.threadInitialized = isThreadInitialized;
- }
-
- /**
- * Waits a bit for the AuditThread to complete. Used by JUnit tests.
- *
- * @param twaitms wait time, in milliseconds
- * @return {@code true} if the thread stopped within the given time, {@code false} otherwise
- * @throws InterruptedException if the thread is interrupted
- */
- protected boolean joinAuditThread(long twaitms) throws InterruptedException {
- if (this.auditThread == null) {
- return true;
-
- } else {
- this.auditThread.join(twaitms);
- return !this.auditThread.isAlive();
- }
- }
-
- /**
- * Return if audit thread.
- *
- * @return {@code true} if an audit thread exists, {@code false} otherwise
- */
- protected boolean haveAuditThread() {
- return (this.auditThread != null);
- }
-
- /**
- * Creates an audit thread. May be overridden by junit tests.
- *
- * @param resourceName2 the resource name
- * @param persistenceUnit2 the persistence unit
- * @param properties2 properties
- * @param integrityAuditPeriodSeconds2
- *
- * @return a new audit thread
- * @throws IntegrityAuditException audit exception
- */
- protected AuditThread makeAuditThread(String resourceName2, String persistenceUnit2, Properties properties2,
- int integrityAuditPeriodSeconds2) throws IntegrityAuditException {
-
- return new AuditThread(resourceName2, persistenceUnit2, properties2, integrityAuditPeriodSeconds2, this);
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditException.java
deleted file mode 100644
index 81e8b90c..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-public class IntegrityAuditException extends Exception {
- private static final long serialVersionUID = 1L;
-
- public IntegrityAuditException() {
- super();
- }
-
- public IntegrityAuditException(String message) {
- super(message);
- }
-
- public IntegrityAuditException(Throwable cause) {
- super(cause);
- }
-
- public IntegrityAuditException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java
deleted file mode 100644
index cd80f56f..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditProperties.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class IntegrityAuditProperties {
-
- public static final int DEFAULT_AUDIT_PERIOD_SECONDS = -1; // Audit does not run
-
- public static final String DB_DRIVER = "jakarta.persistence.jdbc.driver";
- public static final String DB_URL = "jakarta.persistence.jdbc.url";
- public static final String DB_USER = "jakarta.persistence.jdbc.user";
- public static final String DB_PWD = "jakarta.persistence.jdbc.password"; //NOSONAR
- public static final String AUDIT_PERIOD_SECONDS = "integrity_audit_period_seconds";
-
-
- public static final String SITE_NAME = "site_name";
- public static final String NODE_TYPE = "node_type";
-
- public enum NodeTypeEnum {
- PDP_XACML, PDP_DROOLS, PAP, PAP_ADMIN, LOGPARSER, BRMS_GATEWAY, ASTRA_GATEWAY, ELK_SERVER, PYPDP
-
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java
deleted file mode 100644
index d3c92fa5..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAuditPropertiesException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-public class IntegrityAuditPropertiesException extends IntegrityAuditException {
- private static final long serialVersionUID = 1L;
-
- public IntegrityAuditPropertiesException() {
- super();
- }
-
- public IntegrityAuditPropertiesException(String message) {
- super(message);
- }
-
- public IntegrityAuditPropertiesException(Throwable cause) {
- super(cause);
- }
-
- public IntegrityAuditPropertiesException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java b/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java
deleted file mode 100644
index 64ec7fd0..00000000
--- a/integrity-audit/src/main/java/org/onap/policy/common/ia/jpa/IntegrityAuditEntity.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Table;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.IOException;
-import java.io.ObjectOutputStream;
-import java.io.Serial;
-import java.io.Serializable;
-import java.util.Date;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.common.ia.AuditorTime;
-
-@Entity
-@Table(name = "IntegrityAuditEntity")
-@NamedQuery(name = " IntegrityAuditEntity.findAll", query = "SELECT e FROM IntegrityAuditEntity e ")
-@NamedQuery(name = "IntegrityAuditEntity.deleteAll", query = "DELETE FROM IntegrityAuditEntity WHERE 1=1")
-@NoArgsConstructor
-@Getter
-@Setter
-public class IntegrityAuditEntity implements Serializable {
-
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Getter
- @Setter
- private static boolean unitTesting;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "id")
- @Setter(AccessLevel.PRIVATE)
- private long id;
-
- @Column(name = "persistenceUnit", nullable = false)
- private String persistenceUnit;
-
- @Column(name = "site", nullable = true)
- private String site;
-
- @Column(name = "nodeType", nullable = true)
- private String nodeType;
-
- @Column(name = "resourceName", nullable = false, unique = true)
- private String resourceName;
-
- @Column(name = "designated", nullable = true)
- private boolean designated = false;
-
- @Column(name = "jdbcDriver", nullable = false)
- private String jdbcDriver;
-
- @Column(name = "jdbcUrl", nullable = false)
- private String jdbcUrl;
-
- @Column(name = "jdbcUser", nullable = false)
- private String jdbcUser;
-
- @Column(name = "jdbcPassword", nullable = false)
- private String jdbcPassword;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "createdDate", updatable = true)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "lastUpdated")
- private Date lastUpdated;
-
- /**
- * Pre persist.
- */
- @PrePersist
- public void prePersist() {
- var date = AuditorTime.getInstance().getDate();
- this.createdDate = date;
- this.lastUpdated = date;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.lastUpdated = AuditorTime.getInstance().getDate();
- }
-
- private void writeObject(ObjectOutputStream out) throws IOException {
- if (isUnitTesting()) {
- /*
- * Note: other fields may be added here, as long as the created-date and last-updated
- * date are not included.
- */
- out.writeObject(jdbcUrl);
-
- } else {
- out.defaultWriteObject();
- }
- }
-}
diff --git a/integrity-audit/src/main/resources/META-INF/persistence.xml b/integrity-audit/src/main/resources/META-INF/persistence.xml
deleted file mode 100644
index 1d72eeba..00000000
--- a/integrity-audit/src/main/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ============LICENSE_START=======================================================
- Integrity Audit
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023-2024 Nordix Foundation.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd">
- <persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
- <!-- Limited use for generating the DB and schema files for iatest DB - uses hibernate -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.common.ia.jpa.IntegrityAuditEntity</class>
- <class>org.onap.policy.common.ia.jpa.IaTestEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <property name="jakarta.persistence.schema-generation.database.action" value="create"/>
- <property name="hibernate.show_sql" value="false"/>
- </properties>
- </persistence-unit>
-
- <persistence-unit name="integrityAuditPU" transaction-type="RESOURCE_LOCAL">
- <!-- For operational use -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.common.ia.jpa.IntegrityAuditEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <property name="hibernate.show_sql" value="false"/>
- </properties>
- </persistence-unit>
-</persistence>
diff --git a/integrity-audit/src/main/resources/log4j.properties b/integrity-audit/src/main/resources/log4j.properties
deleted file mode 100644
index 65b9e55e..00000000
--- a/integrity-audit/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,48 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# Integrity Audit
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END=========================================================
-###
-
-#
-# Use this properties for debugging and development.
-#
-#
-# Set root logger level to DEBUG and its only appender to A1.
-log4j.rootLogger=INFO, FILE
-
-# A1 is set to be a DailyRollingFileAppender.
-log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
-
-# Set the name of the file
-log4j.appender.FILE.File=IntegrityMonitor.log
-
-# Set the immediate flush to true (default)
-log4j.appender.FILE.ImmediateFlush=true
-
-# Set the threshold to debug mode
-log4j.appender.FILE.Threshold=debug
-
-# Set the append to false, should not overwrite
-log4j.appender.FILE.Append=true
-
-# Set the DatePattern
-log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
-
-# A1 uses PatternLayout.
-log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
-log4j.appender.FILE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java
deleted file mode 100644
index 1d47f7d0..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
-
-/*
- * All JUnits are designed to run in the local development environment
- * where they have write privileges and can execute time-sensitive
- * tasks.
- */
-class AuditPeriodTest extends IntegrityAuditTestBase {
-
- private static Logger logger = FlexLogger.getLogger(AuditPeriodTest.class);
-
- @BeforeAll
- public static void setUpBeforeClass() throws Exception {
- IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + AuditPeriodTest.class.getSimpleName());
- }
-
- @AfterAll
- public static void tearDownAfterClass() {
- IntegrityAuditTestBase.tearDownAfterClass();
- }
-
- /**
- * Set up for test case.
- */
- @Override
- @BeforeEach
- public void setUp() {
- logger.info("setUp: Entering");
-
- super.setUp();
-
- logger.info("setUp: Exiting");
-
- }
-
- /**
- * Tear down after test cases.
- */
- @Override
- @AfterEach
- public void tearDown() {
- logger.info("tearDown: Entering");
-
- super.tearDown();
-
- logger.info("tearDown: Exiting");
- }
-
- /*
- * Verifies (via log parsing) that when a negative audit period is specified, the audit is
- * suppressed.
- */
- @Test
- void testNegativeAuditPeriod() throws Exception {
-
- logger.info("testNegativeAuditPeriod: Entering");
-
- properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "-1");
-
- ExtractAppender logA = watch(debugLogger, "Suppressing integrity audit, integrityAuditPeriodSeconds=([^,]*)");
-
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Sleep long enough to allow
- *
- * 1) audit to immediately terminate.
- */
- waitThread(integrityAudit);
-
- verifyItemsInLog(logA, "-1");
-
- logger.info("testNegativeAuditPeriod: Exiting");
-
- }
-
- /*
- * Verifies (via log parsing) that when an audit period of zero is specified, the audit runs
- * continuously, generating a number of sleep/wake sequences in a short period of time (e.g.
- * 100ms).
- */
- @Test
- void testZeroAuditPeriod() throws Exception {
-
- logger.info("testZeroAuditPeriod: Entering");
-
- properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "0");
-
- final ExtractAppender logA = watch(debugLogger, "[Aa]waking from (0s) sleep");
-
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Wait for
- *
- * 1) audit to generate a bunch of sleep wake sequences.
- */
- String[] awakings = new String[10];
- for (int x = 0; x < awakings.length; ++x) {
- awakings[x] = "0s";
- runAudit(integrityAudit);
- }
-
- // run a couple more audits
- runAudit(integrityAudit);
- runAudit(integrityAudit);
-
- /*
- * We should get at least 10 sleep/wake sequences.
- */
-
- verifyItemsInLog(logA, awakings);
-
- logger.info("testZeroAuditPeriod: Exiting");
-
- }
-
- /**
- * Verifies that when different audit periods are specified, there is an appropriate interval
- * between the audits.
- */
- @Test
- void testLongAuditPeriod() throws Exception {
-
- logger.info("testLongAuditPeriod: Entering");
-
- testAuditPeriod(100);
- testAuditPeriod(200);
-
- logger.info("testLongAuditPeriod: Exiting");
- }
-
- /**
- * Verifies that audits actually take as long as expected, even with multiple auditors running
- * simultaneously.
- *
- * @param periodSec audit period, in seconds
- * @throws Exception if an error occurs
- * @throws InterruptedException if the thread is interrupted
- */
- private void testAuditPeriod(long periodSec) throws Exception {
-
- properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, String.valueOf(periodSec));
-
- /*
- * Start several auditors.
- */
- MyIntegrityAudit[] ia = new MyIntegrityAudit[3];
- for (int x = 0; x < ia.length; ++x) {
- ia[x] = makeAuditor("pdp" + x, A_SEQ_PU);
- }
-
- /*
- * Run an audit on all of them.
- */
- runAudit(ia);
-
- /*
- * Now run again and ensure it waited long enough between runs.
- */
- long tmin = minAuditTime(ia);
- assertTrue(tmin >= periodSec + AuditThread.AUDIT_COMPLETION_INTERVAL * AuditThread.AUDIT_RESET_CYCLES);
-
- /*
- * Now run again and ensure it waited long enough between runs.
- */
- tmin = minAuditTime(ia);
- assertTrue(tmin >= periodSec + AuditThread.AUDIT_COMPLETION_INTERVAL * AuditThread.AUDIT_RESET_CYCLES);
- }
-
- /**
- * Runs simultaneous audits on several auditors.
- *
- * @param auditors the auditors
- * @return the minimum time, in milliseconds, elapsed for any given auditor
- * @throws InterruptedException if the thread is interrupted
- */
- private long minAuditTime(MyIntegrityAudit... auditors) throws InterruptedException {
- List<Thread> threads = new ArrayList<>(auditors.length);
- AtomicLong tmin = new AtomicLong(Long.MAX_VALUE);
-
- // create the threads
- for (MyIntegrityAudit p : auditors) {
- Thread auditThread = new Thread() {
-
- @Override
- public void run() {
- try {
- long tbegin = p.getTimeInMillis();
- runAudit(p);
- long elapsed = p.getTimeInMillis() - tbegin;
-
- synchronized (tmin) {
- tmin.set(Math.min(tmin.get(), elapsed));
- }
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- };
-
- auditThread.setDaemon(true);
- threads.add(auditThread);
- }
-
- // start the threads
- for (Thread t : threads) {
- t.start();
- }
-
- // wait for them to complete
- for (Thread t : threads) {
- t.join();
- }
-
- return tmin.get();
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditorTimeTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditorTimeTest.java
deleted file mode 100644
index 9899ca25..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditorTimeTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.utils.time.CurrentTime;
-
-/**
- * Tests the AuditorTime class.
- */
-class AuditorTimeTest {
-
- @Test
- void testGetInstance() {
- CurrentTime inst = AuditorTime.getInstance();
- assertNotNull(inst);
-
- assertEquals(inst, AuditorTime.getInstance());
- }
-
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java
deleted file mode 100644
index c9837e03..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java
+++ /dev/null
@@ -1,551 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.ia.jpa.IaTestEntity;
-import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
-import org.onap.policy.common.ia.jpa.PersonSample;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-/*
- * All JUnits are designed to run in the local development environment
- * where they have write privileges and can execute time-sensitive
- * tasks.
- */
-class DbAuditCompareEntriesTest extends IntegrityAuditTestBase {
- private static final String ZAPHOD = "Zaphod";
-
- private static Logger logger = FlexLogger.getLogger(DbAuditCompareEntriesTest.class);
-
- private DbDao dbDao;
- private static String resourceName = "pdp1";
-
- @BeforeAll
- public static void setUpBeforeClass() throws Exception {
- IntegrityAuditTestBase
- .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditCompareEntriesTest.class.getSimpleName());
- }
-
- @AfterAll
- public static void tearDownAfterClass() {
- IntegrityAuditTestBase.tearDownAfterClass();
- }
-
- /**
- * Set up for test cases.
- */
- @Override
- @BeforeEach
- public void setUp() {
-
- logger.info("setUp: Entering");
-
- super.setUp();
-
- truncateTables(makeProperties());
-
- logger.info("setUp: Exiting");
- }
-
- /**
- * Clean up DB after each test.
- */
- @Override
- @AfterEach
- public void tearDown() {
- logger.info("tearDown: Entering");
-
- dbDao.destroy();
-
- super.tearDown();
-
- logger.info("tearDown: Exiting");
- }
-
- /*
- * Tests that a comparison between hashsets is successful if the entries match
- */
- // @Ignore
- @Test
- void testSuccessfulComparison() throws Exception {
- logger.info("testSuccessfulComparison: Entering");
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties());
- final DbAudit dbAudit = new DbAudit(dbDao);
-
- String className = null;
- // There is only one entry IntegrityAuditEntity, but we will check
- // anyway
- Set<String> classNameSet = dbDao.getPersistenceClassNames();
- for (String c : classNameSet) {
- if ("org.onap.policy.common.ia.jpa.IntegrityAuditEntity".equals(c)) {
- className = c;
- }
- }
- final String resourceName1 = resourceName;
- final String resourceName2 = resourceName;
-
- final IntegrityAuditEntity entry1 = new IntegrityAuditEntity();
- final IntegrityAuditEntity entry2 = new IntegrityAuditEntity();
- Date date = new Date();
-
- /*
- * Two entries with the same field values
- */
- entry1.setDesignated(false);
- entry1.setJdbcDriver(DB_DRIVER);
- entry1.setJdbcPassword(DB_PASS);
- entry1.setJdbcUrl(dbUrl);
- entry1.setJdbcUser(DB_USER);
- entry1.setLastUpdated(date);
- entry1.setNodeType(NODE_TYPE);
- entry1.setPersistenceUnit(A_SEQ_PU);
- entry1.setResourceName(resourceName1);
- entry1.setSite(SITE_NAME);
-
- entry2.setDesignated(false);
- entry2.setJdbcDriver(DB_DRIVER);
- entry2.setJdbcPassword(DB_PASS);
- entry2.setJdbcUrl(dbUrl);
- entry2.setJdbcUser(DB_USER);
- entry2.setLastUpdated(date);
- entry2.setNodeType(NODE_TYPE);
- entry2.setPersistenceUnit(A_SEQ_PU);
- entry2.setResourceName(resourceName2);
- entry2.setSite(SITE_NAME);
-
- dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
- /*
- * Assert that there are no mismatches returned
- */
- assertTrue(result.isEmpty());
-
- logger.info("testSuccessfulComparison: Exit");
- }
-
- /*
- * Tests that an error is detected if an entry in one hashset doesn't match the other
- */
- // @Ignore
- @Test
- void testComparisonError() throws Exception {
- logger.info("testComparisonError: Entering");
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties());
- final DbAudit dbAudit = new DbAudit(dbDao);
-
- final String resourceName1 = resourceName;
- final String resourceName2 = resourceName;
-
- final IntegrityAuditEntity entry1 = new IntegrityAuditEntity();
- final IntegrityAuditEntity entry2 = new IntegrityAuditEntity();
- Date date = new Date();
-
- /*
- * Create two entries with different designated values
- */
- entry1.setDesignated(false);
- entry1.setJdbcDriver(DB_DRIVER);
- entry1.setJdbcPassword(DB_PASS);
- entry1.setJdbcUrl(dbUrl);
- entry1.setJdbcUser(DB_USER);
- entry1.setLastUpdated(date);
- entry1.setNodeType(NODE_TYPE);
- entry1.setPersistenceUnit(A_SEQ_PU);
- entry1.setResourceName(resourceName1);
- entry1.setSite(SITE_NAME);
-
- entry2.setDesignated(true);
- entry2.setJdbcDriver(DB_DRIVER);
- entry2.setJdbcPassword(DB_PASS);
- entry2.setJdbcUrl(dbUrl);
- entry2.setJdbcUser(DB_USER);
- entry2.setLastUpdated(date);
- entry2.setNodeType(NODE_TYPE);
- entry2.setPersistenceUnit(A_SEQ_PU);
- entry2.setResourceName(resourceName2);
- entry2.setSite(SITE_NAME);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
- /*
- * Assert that there was one mismatch
- */
- assertEquals(1, result.size());
-
- logger.info("testComparisonError: Exit");
- }
-
- /*
- * Tests that a mismatch/miss entry is detected if there are missing entries in one or both of
- * the hashsets
- */
- // @Ignore
- @Test
- void testCompareMissingEntries() throws Exception {
- logger.info("testCompareMissingEntries: Entering");
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties());
- final DbAudit dbAudit = new DbAudit(dbDao);
-
- final String resourceName1 = resourceName;
- final String resourceName2 = resourceName;
-
- final IntegrityAuditEntity entry1 = new IntegrityAuditEntity();
- final IntegrityAuditEntity entry2 = new IntegrityAuditEntity();
- final IntegrityAuditEntity entry3 = new IntegrityAuditEntity();
- final IntegrityAuditEntity entry4 = new IntegrityAuditEntity();
-
- Date date = new Date();
-
- /*
- * 4 entries, one mismatch, two miss entries
- */
- entry1.setDesignated(false);
- entry1.setJdbcDriver(DB_DRIVER);
- entry1.setJdbcPassword(DB_PASS);
- entry1.setJdbcUrl(dbUrl);
- entry1.setJdbcUser(DB_USER);
- entry1.setLastUpdated(date);
- entry1.setNodeType(NODE_TYPE);
- entry1.setPersistenceUnit(A_SEQ_PU);
- entry1.setResourceName(resourceName1);
- entry1.setSite(SITE_NAME);
-
- entry2.setDesignated(true);
- entry2.setJdbcDriver(DB_DRIVER);
- entry2.setJdbcPassword(DB_PASS);
- entry2.setJdbcUrl(dbUrl);
- entry2.setJdbcUser(DB_USER);
- entry2.setLastUpdated(date);
- entry2.setNodeType(NODE_TYPE);
- entry2.setPersistenceUnit(A_SEQ_PU);
- entry2.setResourceName(resourceName2);
- entry2.setSite(SITE_NAME);
-
- entry3.setDesignated(false);
- entry3.setJdbcDriver(DB_DRIVER);
- entry3.setJdbcPassword(DB_PASS);
- entry3.setJdbcUrl(dbUrl);
- entry3.setJdbcUser(DB_USER);
- entry3.setLastUpdated(date);
- entry3.setNodeType(NODE_TYPE);
- entry3.setPersistenceUnit(A_SEQ_PU);
- entry3.setResourceName(resourceName2);
- entry3.setSite("SiteB");
-
- entry4.setDesignated(false);
- entry4.setJdbcDriver(DB_DRIVER);
- entry4.setJdbcPassword(DB_PASS);
- entry4.setJdbcUrl(dbUrl);
- entry4.setJdbcUser(DB_USER);
- entry4.setLastUpdated(date);
- entry4.setNodeType(NODE_TYPE);
- entry4.setPersistenceUnit(A_SEQ_PU);
- entry4.setResourceName(resourceName2);
- entry4.setSite("SiteB");
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("0", entry1);
- myEntries.put("1", entry3);
- theirEntries.put("0", entry2);
- theirEntries.put("2", entry4);
-
- Set<Object> mismatchResult = dbAudit.compareEntries(myEntries, theirEntries);
-
- /*
- * Assert 3 mismatches/missing entries were found
- */
- assertEquals(3, mismatchResult.size());
-
- logger.info("testCompareMissingEntries: Exit");
- }
-
- /*
- * Tests that comparison algorithm works for each entity in the hashsets
- */
- // @Ignore
- @Test
- void testCompareAllHashEntities() throws Exception {
- logger.info("testCompareAllHashEntities: Entering");
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, makeProperties());
- DbAudit dbAudit = new DbAudit(dbDao);
-
- Set<String> classNameSet = dbDao.getPersistenceClassNames();
- for (String className : classNameSet) {
- if ("org.onap.policy.common.ia.jpa.IntegrityAuditEntity".equals(className)) {
- final String resourceName1 = resourceName;
- final String resourceName2 = resourceName;
-
- final IntegrityAuditEntity entry1 = new IntegrityAuditEntity();
- final IntegrityAuditEntity entry2 = new IntegrityAuditEntity();
- Date date = new Date();
-
- /*
- * Two entries with the same field values
- */
- entry1.setDesignated(false);
- entry1.setJdbcDriver(DB_DRIVER);
- entry1.setJdbcPassword(DB_PASS);
- entry1.setJdbcUrl(dbUrl);
- entry1.setJdbcUser(DB_USER);
- entry1.setLastUpdated(date);
- entry1.setNodeType(NODE_TYPE);
- entry1.setPersistenceUnit(A_SEQ_PU);
- entry1.setResourceName(resourceName1);
- entry1.setSite(SITE_NAME);
-
- entry2.setDesignated(false);
- entry2.setJdbcDriver(DB_DRIVER);
- entry2.setJdbcPassword(DB_PASS);
- entry2.setJdbcUrl(dbUrl);
- entry2.setJdbcUser(DB_USER);
- entry2.setLastUpdated(date);
- entry2.setNodeType(NODE_TYPE);
- entry2.setPersistenceUnit(A_SEQ_PU);
- entry2.setResourceName(resourceName2);
- entry2.setSite(SITE_NAME);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("pdp1", entry1);
- theirEntries.put("pdp1", entry2);
-
- /*
- * Assert there was no mismatches
- */
- assertTrue(dbAudit.compareEntries(myEntries, theirEntries).isEmpty());
- } else if ("org.onap.policy.common.ia.jpa.IaTestEntity".equals(className)) {
- final IaTestEntity iate = new IaTestEntity();
- final IaTestEntity iate2 = new IaTestEntity();
- final IaTestEntity iate3 = new IaTestEntity();
- final IaTestEntity iate4 = new IaTestEntity();
-
- Date date = new Date();
-
- /*
- * Four entries, 2 mismatches
- */
- iate.setCreatedBy("Ford");
- iate.setModifiedBy("Ford");
- iate.setModifiedDate(date);
-
- iate2.setCreatedBy("Ford");
- iate2.setModifiedBy(ZAPHOD);
- iate2.setModifiedDate(date);
-
- iate3.setCreatedBy(ZAPHOD);
- iate3.setModifiedBy("Ford");
- iate3.setModifiedDate(date);
-
- iate4.setCreatedBy("Ford");
- iate4.setModifiedBy("Ford");
- iate4.setModifiedDate(date);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("0", iate);
- myEntries.put("1", iate2);
- theirEntries.put("0", iate3);
- theirEntries.put("1", iate4);
-
-
- /*
- * Assert that there is 2 mismatches
- */
- assertEquals(2, dbAudit.compareEntries(myEntries, theirEntries).size());
- }
- }
-
- logger.info("testCompareAllHashEntities: Exit");
- }
-
- /*
- * Tests that comparison algorithm works for each entity in the database
- */
- @Test
- void testCompareAllDbEntities() throws Exception {
- logger.info("testCompareAllDbEntities: Entering");
-
- logger.info("Setting up DB");
-
- IntegrityAudit.setUnitTesting(true);
-
- Properties properties = makeProperties();
-
- Properties properties2 = makeProperties();
- properties2.put(IntegrityAuditProperties.DB_URL,
- "jdbc:h2:mem:" + DbAuditCompareEntriesTest.class.getSimpleName() + "2");
-
- // Clean up the two DBs
- truncateTables(properties);
- truncateTables(properties2);
-
- // Add entries into DB1
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- new DbDao("pdp2", A_SEQ_PU, properties).destroy();
- DbAudit dbAudit = new DbAudit(dbDao);
-
- // Add entries into DB2
- DbDao dbDao3 = new DbDao(resourceName, A_SEQ_PU, properties2);
- new DbDao("pdp2", A_SEQ_PU, properties2).destroy();
-
- // Pull all entries and compare
- Set<String> classNameSet = dbDao.getPersistenceClassNames();
- Map<Object, Object> myEntries;
- Map<Object, Object> theirEntries;
- Set<Object> mismatchResult = new HashSet<>();
- for (String className : classNameSet) {
- logger.info("classNameSet entry = " + className);
- myEntries = dbDao.getAllEntries(A_SEQ_PU, properties, className);
- theirEntries = dbDao3.getAllEntries(A_SEQ_PU, properties2, className);
- mismatchResult = dbAudit.compareEntries(myEntries, theirEntries);
- if (className.contains("IntegrityAuditEntity")) {
- break;
- }
- }
-
- dbDao3.destroy();
-
- // Assert that there is 2 mismatches between IntegrityAuditEntity tables
- assertEquals(2, mismatchResult.size());
-
- logger.info("testCompareAllDbEntities: Exit");
- }
-
- /**
- * Truncate the tables.
- *
- * @param properties the properties
- */
- private void truncateTables(Properties properties) {
- truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity");
- truncateTable(properties, A_SEQ_PU, "IaTestEntity");
- }
-
- /*
- * Tests that differences in embedded classes are still caught
- */
- // @Ignore
- @Test
- void testEmbeddedClass() throws Exception {
- logger.info("testEmbeddedClasses: Entering");
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- final DbAudit dbAudit = new DbAudit(dbDao);
-
- String className = null;
- // There is only one entry IntegrityAuditEntity, but we will check
- // anyway
- Set<String> classNameSet = dbDao.getPersistenceClassNames();
- for (String classNameInClassNameSet : classNameSet) {
- if ("org.onap.policy.common.ia.jpa.IaTestEntity".equals(classNameInClassNameSet)) {
- className = classNameInClassNameSet;
- }
- }
-
- final IaTestEntity iate = new IaTestEntity();
- final IaTestEntity iate2 = new IaTestEntity();
-
- final Date date = new Date();
-
- PersonSample person = new PersonSample("Ford", "Prefect", 21);
- PersonSample person2 = new PersonSample(ZAPHOD, "Beeblebrox", 25);
-
- /*
- * Silly tests to bump coverage stats, not sure why they are counting PersonSample to begin
- * with. Will have to look into that at some point.
- */
- assertNotEquals(person.getAge(), person2.getAge());
- assertNotEquals(person.getFirstName(), person2.getFirstName());
- assertNotEquals(person.getLasttName(), person2.getLasttName());
- PersonSample personTest = new PersonSample(null, null, 0);
- personTest.setAge(person.getAge());
- personTest.setFirstName(person.getFirstName());
- personTest.setLastName(person.getLasttName());
- /*
- * Two entries, 1 mismatch
- */
- iate.setCreatedBy("Ford");
- iate.setModifiedBy(ZAPHOD);
- iate.setModifiedDate(date);
- iate.setPersonTest(person);
-
- iate2.setCreatedBy("Ford");
- iate2.setModifiedBy(ZAPHOD);
- iate2.setModifiedDate(date);
- iate2.setPersonTest(person2);
-
- dbAudit.writeAuditDebugLog(className, "resource1", "resource2", iate, iate2);
-
- HashMap<Object, Object> myEntries = new HashMap<>();
- HashMap<Object, Object> theirEntries = new HashMap<>();
-
- myEntries.put("0", iate);
- theirEntries.put("0", iate2);
-
- Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
-
- /*
- * Assert that there are no mismatches returned
- */
- assertTrue(!result.isEmpty());
-
- logger.info("testEmbeddedClasses: Exit");
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java
deleted file mode 100644
index 507587b7..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-
-import com.google.re2j.Pattern;
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.Persistence;
-import java.util.List;
-import java.util.Properties;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
-
-/*
- * All JUnits are designed to run in the local development environment
- * where they have write privileges and can execute time-sensitive
- * tasks.
- *
- * If any have been ignored (@Ignore) they will not run at the same time
- * as others. You should run them as JUnits by themselves.
- */
-class DbAuditTest extends IntegrityAuditTestBase {
-
- private static Logger logger = FlexLogger.getLogger(DbAuditTest.class);
-
- private static final Pattern COMMA_PAT = Pattern.compile(",");
- private static final String RESOURCE_NAME = "pdp1";
-
- private EntityManagerFactory emf2;
- private EntityManager em2;
- private DbDao dbDao;
-
- @BeforeAll
- public static void setUpBeforeClass() throws Exception {
- IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditTest.class.getSimpleName());
- IntegrityAuditEntity.setUnitTesting(true);
- }
-
- @AfterAll
- public static void tearDownAfterClass() {
- IntegrityAuditTestBase.tearDownAfterClass();
- IntegrityAuditEntity.setUnitTesting(false);
- }
-
- /**
- * Set up for test cases.
- */
- @Override
- @BeforeEach
- public void setUp() {
- logger.info("setUp: Entering");
-
- super.setUp();
-
- dbDao = null;
- emf2 = null;
- em2 = null;
-
- logger.info("setUp: Exiting");
- }
-
- /**
- * Tear down after test cases.
- */
- @Override
- @AfterEach
- public void tearDown() {
- logger.info("tearDown: Entering");
-
- if (dbDao != null) {
- dbDao.destroy();
- }
-
- if (em2 != null) {
- em2.close();
- }
-
- if (emf2 != null) {
- emf2.close();
- }
-
- super.tearDown();
-
- logger.info("tearDown: Exiting");
- }
-
- private void createDb(Properties properties) {
- if (emf2 != null) {
- throw new IllegalStateException("DB2 has already been created");
- }
-
- // open the DB and ensure it stays open until the test completes
- emf2 = Persistence.createEntityManagerFactory(A_SEQ_PU, properties);
- em2 = emf2.createEntityManager();
-
- truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity");
- }
-
- /**
- * Tests printing an error to the log in the event where there are no entities saved in the database.
- */
- @Test
- void testNoEntities() throws Exception {
- Properties properties = makeProperties();
-
- logger.info("noEntitiesTest: Entering");
-
- dbDao = new DbDao(RESOURCE_NAME, A_SEQ_PU, properties);
- dbDao.deleteAllIntegrityAuditEntities();
-
- assertThatThrownBy(() -> {
- DbAudit dbAudit = new DbAudit(dbDao);
- dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE);
- }).isInstanceOf(DbAuditException.class);
-
- logger.info("noEntitiesTest: Exit");
- }
-
- /**
- * Tests the detection of only one entry in the database.
- */
- @Test
- void testOneEntity() throws Exception {
- Properties properties = makeProperties();
-
- logger.info("oneEntityTest: Entering");
-
- final ExtractAppender log = watch(debugLogger, "DbAudit: Found only (one) IntegrityAuditEntity entry:");
-
- // Add one entry in the database
- dbDao = new DbDao(RESOURCE_NAME, A_SEQ_PU, properties);
- DbAudit dbAudit = new DbAudit(dbDao);
- dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE);
-
- List<IntegrityAuditEntity> iaeList = dbDao.getIntegrityAuditEntities(A_SEQ_PU, NODE_TYPE);
- logger.info("List size: " + iaeList.size());
-
- verifyItemsInLog(log, "one");
-
- logger.info("oneEntityTest: Exit");
- }
-
- /**
- * Tests reporting mismatches and missing entries using the error log.
- */
- @Test
- void testMismatch() throws Exception {
- logger.info("mismatchTest: Entering");
-
- // use new URLs so we get a completely new DB
- String dbUrl = DbAuditTest.dbUrl + "_mismatchTest";
- String dbUrl2 = dbUrl + "2";
-
- Properties properties = makeProperties();
- properties.put(IntegrityAuditProperties.DB_URL, dbUrl);
-
- // Properties for DB2
- Properties properties2 = makeProperties();
- properties2.put(IntegrityAuditProperties.DB_URL, dbUrl2);
-
- /*
- * We must drop and re-create DB1 so that it's sequence generator is in step with the sequence generator for
- * DB2.
- */
- recreateDb1(properties);
-
- // create/open DB2
- createDb(properties2);
-
- final ExtractAppender dbglog = watch(debugLogger, "Mismatched entries [(]keys[)]:(.*)");
- final ExtractAppender errlog = watch(errorLogger, "DB Audit: ([0-9])");
-
- /*
- * Create entries in DB1 & DB2 for the resource of interest
- */
- dbDao = new DbDao(RESOURCE_NAME, A_SEQ_PU, properties);
-
- new DbDao(RESOURCE_NAME, A_SEQ_PU, properties2).destroy();
-
- /*
- * Entries in DB1, pointing to DB2, except for pdp3
- */
- new DbDao("pdp2", A_SEQ_PU, properties, dbUrl2).destroy();
- new DbDao("pdp1", A_SEQ_PU, properties, dbUrl2).destroy();
- new DbDao("pdp3", A_SEQ_PU, properties).destroy(); // mismatched URL
- new DbDao("pdp4", A_SEQ_PU, properties, dbUrl2).destroy();
-
- /*
- * Identical entries in DB2, all pointing to DB2, including pdp3, but leaving out pdp4
- */
- new DbDao("pdp2", A_SEQ_PU, properties2).destroy();
- new DbDao("pdp1", A_SEQ_PU, properties2).destroy();
- new DbDao("pdp3", A_SEQ_PU, properties2).destroy();
-
- /*
- * Run the DB Audit, once it finds a mismatch and sleeps, update DB1 to have the same entry as DB2 it can be
- * confirmed that the mismatch is resolved
- */
- DbAudit dbAudit = new DbAudit(dbDao);
- dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE);
-
- // update pdp3 entry in DB1 to point to DB2
- new DbDao("pdp3", A_SEQ_PU, properties, dbUrl2).destroy();
-
- /*
- * Run the audit again and correct the mismatch, the result should be one entry in the mismatchKeySet because of
- * the missing entry from the beginning of the test
- */
- dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, NODE_TYPE);
-
- assertFalse(dbglog.getExtracted().isEmpty());
-
- String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1);
- int mismatchEntries = COMMA_PAT.split(mismatchIndex.trim()).length;
- logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" + " mismatachEntries = "
- + mismatchEntries);
-
- // Assert there is only one entry index
- assertEquals(1, mismatchEntries);
-
- // Now check the entry in the error.log
- assertFalse(errlog.getExtracted().isEmpty());
-
- String mismatchNum = errlog.getExtracted().get(errlog.getExtracted().size() - 1);
-
- logger.info("mismatchTest: mismatchNum found: '" + mismatchNum + "'");
-
- // Assert that there are a total of 3 mismatches - 1 between each
- // comparison node.
- assertEquals("3", mismatchNum);
-
- logger.info("mismatchTest: Exit");
- }
-
- /**
- * Re-creates DB1, using the specified properties.
- *
- * @param properties the properties
- */
- private void recreateDb1(Properties properties) {
- em.close();
- emf.close();
-
- createDb(properties);
-
- em = em2;
- emf = emf2;
-
- em2 = null;
- emf2 = null;
- }
-
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java
deleted file mode 100644
index da6f0bd5..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDaoTest.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import jakarta.persistence.PersistenceUnitUtil;
-import jakarta.persistence.Query;
-import jakarta.persistence.TypedQuery;
-import jakarta.persistence.criteria.CriteriaBuilder;
-import jakarta.persistence.criteria.CriteriaQuery;
-import jakarta.persistence.criteria.Root;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
-import org.onap.policy.common.utils.jpa.EntityTransCloser;
-import org.onap.policy.common.utils.time.TestTime;
-
-/*
- * All JUnits are designed to run in the local development environment
- * where they have write privileges and can execute time-sensitive
- * tasks.
- */
-class DbDaoTest extends IntegrityAuditTestBase {
- private static final String SELECT_ENTITIES =
- "Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu";
- private static final String SITE_B = "SiteB";
- private static final String ENTITY_CLASS_NAME = "org.onap.policy.common.ia.jpa.IntegrityAuditEntity";
-
- private static final String resourceName = "pdp0";
-
- private DbDao dbDao;
-
- @BeforeAll
- public static void setUpBeforeClass() throws Exception {
- IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbDaoTest.class.getSimpleName());
- }
-
- @AfterAll
- public static void tearDownAfterClass() {
- IntegrityAuditTestBase.tearDownAfterClass();
- }
-
- @Override
- @BeforeEach
- public void setUp() {
- super.setUp();
- dbDao = null;
- }
-
- /**
- * Tear down after test cases.
- */
- @Override
- @AfterEach
- public void tearDown() {
- if (dbDao != null) {
- dbDao.destroy();
- }
-
- super.tearDown();
- }
-
- /* Tests registering a new IntegrityAuditEntity object in the DB */
- @Test
- void testNewRegistration() throws Exception {
- Properties properties = makeProperties();
-
- try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) {
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
-
- // Find the proper entry in the database
- Query iaequery = em.createQuery(SELECT_ENTITIES);
- iaequery.setParameter("rn", DbDaoTest.resourceName);
- iaequery.setParameter("pu", DbDaoTest.A_SEQ_PU);
-
- @SuppressWarnings("rawtypes")
- List iaeList = iaequery.getResultList();
-
- // Assert that the IntegrityAuditEntity object was found
- assertNotNull(iaeList);
-
- // flush to the DB
- em.flush();
- et.commit();
- }
- }
-
- /*
- * Tests updating an IntegrityAuditEntity if it has already been registered
- */
- @Test
- void testUpdateRegistration() throws Exception {
- Properties properties = makeProperties();
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
-
- // Change site_name in properties to test that an update was made to
- // an existing entry in the table
- properties.put(IntegrityAuditProperties.SITE_NAME, SITE_B);
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
-
- try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) {
- // Find the proper entry in the database
- Query iaequery = em.createQuery(SELECT_ENTITIES);
- iaequery.setParameter("rn", DbDaoTest.resourceName);
- iaequery.setParameter("pu", DbDaoTest.A_SEQ_PU);
-
- @SuppressWarnings("rawtypes")
- List iaeList = iaequery.getResultList();
- IntegrityAuditEntity iae = null;
- if (!iaeList.isEmpty()) {
- // ignores multiple results
- iae = (IntegrityAuditEntity) iaeList.get(0);
-
- em.refresh(iae);
- em.persist(iae);
-
- // flush to the DB
- em.flush();
-
- // commit transaction
- et.commit();
-
- // Assert that the site_name for the existing entry was updated
- assertEquals(SITE_B, iae.getSite());
- }
- }
- }
-
- /* Tests obtaining all Integrity Audit Entities from a table */
- @Test
- void testGetIntegrityAuditEntities() throws Exception {
- Properties properties = makeProperties();
-
- // Add some entries to the DB
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- new DbDao("pdp1", A_SEQ_PU, properties).destroy();
- properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_drools");
- new DbDao("pdp2", A_SEQ_PU, properties).destroy();
-
- List<IntegrityAuditEntity> entities;
- // Obtain entries based on persistenceUnit and nodeType
- entities = dbDao.getIntegrityAuditEntities(A_SEQ_PU, "pdp_xacml");
- assertEquals(2, entities.size());
- }
-
- /* Tests retrieving a DbDao instance's IntegrityAuditEntity */
- @Test
- void testGetMyIntegrityAuditEntity() throws Exception {
- Properties properties = makeProperties();
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- IntegrityAuditEntity iae = dbDao.getMyIntegrityAuditEntity();
- assertEquals(A_SEQ_PU, iae.getPersistenceUnit());
- }
-
- /* Tests obtaining an IntegrityAuditEntity by ID */
- @Test
- void testGetIntegrityAuditEntity() throws Exception {
- Properties properties = makeProperties();
-
- // Obtain an entry from the database based on ID
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
-
- // Find the proper database entry
- Query iaequery = em.createQuery(SELECT_ENTITIES);
- iaequery.setParameter("rn", DbDaoTest.resourceName);
- iaequery.setParameter("pu", DbDaoTest.A_SEQ_PU);
-
- @SuppressWarnings("rawtypes")
- List iaeList = iaequery.getResultList();
- IntegrityAuditEntity iae = null;
- if (!iaeList.isEmpty()) {
- // ignores multiple results
- iae = (IntegrityAuditEntity) iaeList.get(0);
-
- // refresh the object from DB in case cached data was returned
- em.refresh(iae);
-
- // Obtain ID for an IntegrityAuditEntity
- PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
- Object iaeId = util.getIdentifier(iae);
-
- // Obtain the same IntegrityAuditEntity based on ID
- IntegrityAuditEntity iaeDuplicate = dbDao.getIntegrityAuditEntity((long) iaeId);
- Object duplicateId = util.getIdentifier(iaeDuplicate);
-
- // Assert that the proper entry was retrieved based on ID
- assertEquals((long) iaeId, (long) duplicateId);
- }
- }
-
- /* Tests setting an IntegrityAuditEntity as the designated node */
- @Test
- void testSetDesignated() throws Exception {
- Properties properties = makeProperties();
-
- try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) {
- // Create an entry and set it's designated field to true
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- dbDao.setDesignated(resourceName, A_SEQ_PU, true);
-
- // Find the proper entry in the database
- Query iaequery = em.createQuery(SELECT_ENTITIES);
- iaequery.setParameter("rn", resourceName);
- iaequery.setParameter("pu", A_SEQ_PU);
-
- @SuppressWarnings("rawtypes")
- List iaeList = iaequery.getResultList();
- IntegrityAuditEntity iae = null;
-
- if (!iaeList.isEmpty()) {
- // ignores multiple results
- iae = (IntegrityAuditEntity) iaeList.get(0);
- em.refresh(iae);
-
- // Check if the node is designated
- boolean result = iae.isDesignated();
-
- // Assert that it is designated
- assertTrue(result);
- }
-
- // flush to the DB
- em.flush();
-
- // close the transaction
- et.commit();
- }
- }
-
- /* Tests that the lastUpdated column in the database is updated properly */
- @Test
- void testSetLastUpdated() throws Exception {
- Properties properties = makeProperties();
-
- try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) {
- TestTime testTime = getTestTime();
-
- // Create an entry
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
-
- // Find the proper entry in the database
- Query iaequery = em.createQuery(SELECT_ENTITIES);
- iaequery.setParameter("rn", resourceName);
- iaequery.setParameter("pu", A_SEQ_PU);
-
- @SuppressWarnings("rawtypes")
- List iaeList = iaequery.getResultList();
- IntegrityAuditEntity iae = null;
-
- if (!iaeList.isEmpty()) {
- // ignores multiple results
- iae = (IntegrityAuditEntity) iaeList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(iae);
-
- // Obtain old update value and set new update value
- final Date oldDate = iae.getLastUpdated();
-
- // ensure dates are different by sleeping for a bit
- testTime.sleep(1);
-
- iae.setSite(SITE_B);
- iae.setLastUpdated(testTime.getDate());
- final Date newDate = iae.getLastUpdated();
-
- em.persist(iae);
- // flush to the DB
- em.flush();
- // close the transaction
- et.commit();
-
- // Assert that the old and new update times are different
- assertNotEquals(oldDate, newDate);
- }
- }
- }
-
- /* Tests that all the entries from a class can be retrieved */
- @Test
- void testGetAllMyEntriesString() throws Exception {
- Properties properties = makeProperties();
-
- // create entries for the IntegrityAuditEntity table
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- new DbDao("pdp1", A_SEQ_PU, properties).destroy();
- new DbDao("pdp2", A_SEQ_PU, properties).destroy();
-
- // Obtain a hash with the persisted objects
- Map<Object, Object> entries = dbDao.getAllMyEntries(ENTITY_CLASS_NAME);
-
- // Assert there were 3 entries for that class
- assertEquals(3, entries.size());
- }
-
- /*
- * Tests retrieving all entities in a Persistence Unit using the class name and a hashset of IDs
- */
- @Test
- void testGetAllMyEntriesStringHashSet() throws Exception {
- Properties properties = makeProperties();
-
- // create entries for the IntegrityAuditEntity table
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- new DbDao("pdp1", A_SEQ_PU, properties).destroy();
- new DbDao("pdp2", A_SEQ_PU, properties).destroy();
-
- // Obtain all entity keys
- CriteriaBuilder cb = em.getCriteriaBuilder();
- CriteriaQuery<Object> cq = cb.createQuery();
- Root<?> rootEntry = cq.from(Class.forName(ENTITY_CLASS_NAME));
- CriteriaQuery<Object> all = cq.select(rootEntry);
- TypedQuery<Object> allQuery = em.createQuery(all);
- List<Object> objectList = allQuery.getResultList();
- HashSet<Object> resultSet = new HashSet<>();
- PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
- for (Object o : objectList) {
- Object key = util.getIdentifier(o);
- resultSet.add(key);
- }
-
- // Obtain a hash with the persisted objects
- Map<Object, Object> entries =
- dbDao.getAllMyEntries(ENTITY_CLASS_NAME, resultSet);
-
- // Assert there were 3 entries for that class
- assertEquals(3, entries.size());
- }
-
- /*
- * Tests retrieving all entities in a Persistence Unit using the persistence unit, properties,
- * and class name
- */
- @Test
- void testGetAllEntriesStringPropertiesString() throws Exception {
- Properties properties = makeProperties();
-
- // create entries for the IntegrityAuditEntity table
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- new DbDao("pdp1", A_SEQ_PU, properties).destroy();
- new DbDao("pdp2", A_SEQ_PU, properties).destroy();
-
- // Obtain a hash with the persisted objects
- Map<Object, Object> entries = dbDao.getAllEntries("integrityAuditPU", properties,
- ENTITY_CLASS_NAME);
-
- // Assert there were 3 entries for that class
- assertEquals(3, entries.size());
- }
-
- /*
- * Tests retrieving all entities in a Persistence Unit using the persistence unit, properties,
- * class name, and a hashset of IDs
- */
- @Test
- void testGetAllEntriesStringPropertiesStringHashSet() throws Exception {
- Properties properties = makeProperties();
-
- // create entries for the IntegrityAuditEntity table
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- new DbDao("pdp1", A_SEQ_PU, properties).destroy();
- new DbDao("pdp2", A_SEQ_PU, properties).destroy();
-
- // Obtain all entity keys
- CriteriaBuilder cb = em.getCriteriaBuilder();
- CriteriaQuery<Object> cq = cb.createQuery();
- Root<?> rootEntry = cq.from(Class.forName(ENTITY_CLASS_NAME));
- CriteriaQuery<Object> all = cq.select(rootEntry);
- TypedQuery<Object> allQuery = em.createQuery(all);
- List<Object> objectList = allQuery.getResultList();
- HashSet<Object> resultSet = new HashSet<>();
- PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
- for (Object o : objectList) {
- Object key = util.getIdentifier(o);
- resultSet.add(key);
- }
-
- // Obtain a hash with the persisted objects
- Map<Object, Object> entries = dbDao.getAllEntries("integrityAuditPU", properties,
- ENTITY_CLASS_NAME, resultSet);
-
- // Assert there were 3 entries for that class
- assertEquals(3, entries.size());
- }
-
- /*
- * Tests getting all the entries from a class based on persistenceUnit, properties, and
- * className
- */
- @Test
- void testGetAllEntries() throws Exception {
- Properties properties = makeProperties();
-
- // create entries for the IntegrityAuditEntity table
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
- new DbDao("pdp1", A_SEQ_PU, properties).destroy();
- new DbDao("pdp2", A_SEQ_PU, properties).destroy();
-
- // Obtain a hash with the persisted objects
- Map<Object, Object> entries =
- dbDao.getAllEntries(A_SEQ_PU, properties, ENTITY_CLASS_NAME);
-
- // Assert there were 3 entries for that class
- assertEquals(3, entries.size());
- }
-
- /**
- * Tests obtaining all class names of persisted classes.
- */
- void testGetPersistenceClassNames() throws Exception {
- Properties properties = makeProperties();
-
- dbDao = new DbDao(resourceName, A_SEQ_PU, properties);
-
- // Retrieve persistence class names
- Set<String> result = dbDao.getPersistenceClassNames();
- assertEquals(1, result.size());
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java
deleted file mode 100644
index d35260dd..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DefaultLoggingPatternTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import java.io.File;
-import java.io.IOException;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.utils.resources.TextFileUtils;
-import org.slf4j.Logger;
-import org.slf4j.MDC;
-import org.slf4j.ext.XLogger;
-import org.slf4j.ext.XLoggerFactory;
-
-/**
- * Test the default logging pattern.
- *
- */
-class DefaultLoggingPatternTest {
- // XLogger for this class
- private static final XLogger XLOGGER = XLoggerFactory.getXLogger(DefaultLoggingPatternTest.class);
-
- // Logger for this class
- private static final Logger LOGGER = XLoggerFactory.getXLogger(DefaultLoggingPatternTest.class);
-
- /**
- * Delete logging file after test.
- */
- @AfterAll
- public static void deleteLogFile() {
- new File("testingLogs/common-modules/integrity-audit/logging-pattern-test.log").deleteOnExit();
- }
-
- /**
- * Test XLogger output.
- *
- * @throws IOException on errors
- */
- @Test
- void testDefaultLoggingPatternXLogger() throws IOException {
- testDefaultLoggingPattern(XLOGGER, "xlogger");
- }
-
- /**
- * Test Logger output.
- *
- * @throws IOException on errors
- */
- @Test
- void testDefaultLoggingPatternLogger() throws IOException {
- testDefaultLoggingPattern(LOGGER, "logger");
- }
-
- /**
- * Test Logger output.
- *
- * @throws IOException on errors
- */
- void testDefaultLoggingPattern(final Logger logger, final String loggerString) throws IOException {
- MDC.put("requestId", "TheRequestId");
- MDC.put("serviceInstanceId", "TheServiceInstanceId");
- MDC.put("serverName", "TheServerName");
- MDC.put("serviceName", "TheServiceName");
- MDC.put("instanceUuid", "TheInstanceUuid");
- MDC.put("severity", "TheSeverity");
- MDC.put("serverIpAddress", "TheServerIpAddress");
- MDC.put("server", "TheServer");
- MDC.put("clientIpAddress", "TheClientIpAddress");
-
- logger.info("This is a test logging string for {}", loggerString);
-
- // Jump past the date, and the actual and expected logged strings should be the same
- String actualLoggedString =
- TextFileUtils.getTextFileAsString("testingLogs/common-modules/integrity-audit/logging-pattern-test.log")
- .substring(23);
- String expectedLoggedString = TextFileUtils
- .getTextFileAsString("src/test/resources/" + loggerString + "-test.expectedlog").substring(23).trim();
-
- assertThat(actualLoggedString).contains(expectedLoggedString);
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java
deleted file mode 100644
index 988d875d..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.utils.test.ExceptionsTester;
-
-/**
- * Tests various Exception subclasses.
- */
-class ExceptionsTest extends ExceptionsTester {
-
- @Test
- void testDbAuditException() {
- assertEquals(4, test(DbAuditException.class));
- }
-
- @Test
- void testDbDaoTransactionException() {
- assertEquals(4, test(DbDaoTransactionException.class));
- }
-
- @Test
- void testIntegrityAuditException() {
- assertEquals(4, test(IntegrityAuditException.class));
- }
-
- @Test
- void testIntegrityAuditPropertiesException() {
- assertEquals(4, test(IntegrityAuditPropertiesException.class));
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java
deleted file mode 100644
index 499d29a0..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java
+++ /dev/null
@@ -1,593 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
-
-/**
- * All JUnits are designed to run in the local development environment where they have write
- * privileges and can execute time-sensitive tasks.
- *
- * <p>Many of the test verification steps are performed by scanning for items written to the log
- * file. Rather than actually scan the log file, an {@link ExtractAppender} is used to monitor
- * events that are logged and extract relevant items. In order to attach the appender to the debug
- * log, it assumes that the debug log is a <i>logback</i> Logger configured per EELF.
- *
- * <p>These tests use a temporary, in-memory DB, which is dropped once the tests complete.
- */
-class IntegrityAuditDesignationTest extends IntegrityAuditTestBase {
-
- private static Logger logger = FlexLogger.getLogger(IntegrityAuditDesignationTest.class);
-
- /**
- * Matches specified PDPs in the debug log. A regular expression matching the desired PDPs
- * should be appended, followed by a right parenthesis. For example:
- *
- * <pre>
- * <code>new ExtractAppender(START_AUDIT_RE_PREFIX + "pdp[124])")
- * </code>
- * </pre>
- */
- private static final String START_AUDIT_RE_PREFIX = "Running audit for persistenceUnit=\\w+ on resourceName=(";
-
- @BeforeAll
- public static void setUpBeforeClass() throws Exception {
- IntegrityAuditTestBase
- .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + IntegrityAuditDesignationTest.class.getSimpleName());
- }
-
- @AfterAll
- public static void tearDownAfterClass() {
- IntegrityAuditTestBase.tearDownAfterClass();
- }
-
- /**
- * Set up before test cases.
- */
- @Override
- @BeforeEach
- public void setUp() {
- logger.info("setUp: Entering");
-
- super.setUp();
-
- logger.info("setUp: Exiting");
- }
-
- /**
- * Tear down after test cases.
- */
- @Override
- @AfterEach
- public void tearDown() {
- logger.info("tearDown: Entering");
-
- super.tearDown();
-
- logger.info("tearDown: Exiting");
-
- }
-
- /*
- * Tests designation logic when only one functioning resource is in play. Designation should
- * stay with single resource.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testOneResource() throws Exception {
-
- logger.info("testOneResource: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE);
-
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Wait for
- *
- * 1) pdp1 to run audit
- *
- * 2) Logic to detect that no other node is available for designation
- *
- * 3) pdp1 to run audit again
- */
- runAudit(integrityAudit);
- waitStaleAndRun(integrityAudit);
-
- logger.info("testOneResource: Stopping audit thread");
- integrityAudit.stopAuditThread();
-
- verifyItemsInLog(logA, "pdp1");
-
- /*
- * Test fix for ONAPD2TD-783: Audit fails to run when application is restarted.
- */
- integrityAudit.startAuditThread();
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp1 to run audit
- *
- * 2) Logic to detect that no other node is available for designation
- *
- * 3) pdp1 to run audit again
- */
- runAudit(integrityAudit);
- waitStaleAndRun(integrityAudit);
-
- verifyItemsInLog(logA, "pdp1");
-
- logger.info("testOneResource: Exiting");
-
- }
-
- /*
- * Tests designation logic when two functioning resources are in play. Designation should
- * alternate between resources.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testTwoResources() throws Exception {
-
- logger.info("testTwoResources: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE);
-
- /*
- * Start audit for pdp1.
- */
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Start audit for pdp2.
- */
- MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU);
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp1 to run audit
- *
- * 2) Logic to detect that pdp1 is stale and designate pdp2
- *
- * 3) pdp2 to run audit
- *
- * 4) Logic to detect that pdp2 is stale and designate pdp1
- *
- * 5) pdp1 to run audit
- */
- runAudit(integrityAudit);
- waitStaleAndRun(integrityAudit2);
- waitStaleAndRun(integrityAudit);
-
- verifyItemsInLog(logA, "pdp1", "pdp2", "pdp1");
-
- logger.info("testTwoResources: Exiting");
-
- }
-
- /*
- * Tests designation logic when two functioning resources are in play, each with different PUs.
- * Audits for persistenceUnit and PU_B should run simultaneously. Designation should not
- * alternate.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testTwoResourcesDifferentPus() throws Exception {
-
- logger.info("testTwoResourcesDifferentPus: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1)");
- final ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2)");
-
- /*
- * Start audit for pdp1.
- */
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Start audit for pdp2.
- */
- MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU);
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp1 and pdp2 to run audit simultaneously
- *
- * 2) Logic to detect that no other node is available for designation for either pdp1 or
- * pdp2
- *
- * 3) pdp1 and pdp2 to again run audit simultaneously
- */
- runAudit(integrityAudit, integrityAudit2);
- waitStaleAndRun(integrityAudit, integrityAudit2);
-
- verifyItemsInLog(logA, "pdp1", "pdp1");
- verifyItemsInLog(logB, "pdp2", "pdp2");
-
- logger.info("testTwoResourcesDifferentPus: Exiting");
-
- }
-
- /*
- * Tests designation logic when two resources are in play but one of them is dead/hung.
- * Designation should move to second resource but then get restored back to original resource
- * when it's discovered that second resource is dead.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testTwoResourcesOneDead() throws Exception {
-
- logger.info("testTwoResourcesOneDead: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE);
-
- /*
- * Start audit for pdp1.
- */
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Populate DB for pdp2, which will simulate it having registered but then having died.
- */
- new DbDao("pdp2", A_SEQ_PU, makeProperties()).destroy();
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp1 to run audit
- *
- * 2) Logic to detect that other node, pdp2, is not available for designation
- *
- * 3) pdp1 to run audit again
- */
- runAudit(integrityAudit);
- waitStaleAndRun(integrityAudit);
-
- verifyItemsInLog(logA, "pdp1", "pdp1");
-
- logger.info("testTwoResourcesOneDead: Exiting");
-
- }
-
- /*
- * Tests designation logic when three functioning resources are in play. Designation should
- * round robin among resources.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testThreeResources() throws Exception {
-
- logger.info("testThreeResources: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE);
-
- /*
- * Start audit for pdp1.
- */
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Start audit for pdp2.
- */
- MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU);
-
- /*
- * Start audit for pdp3.
- */
- MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU);
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp1 to run audit
- *
- * 2) Logic to detect that pdp1 is stale and designate pdp2
- *
- * 3) pdp2 to run audit
- *
- * 4) Logic to detect that pdp2 is stale and designate pdp3
- *
- * 5) pdp3 to run audit
- *
- * 6) Logic to detect that pdp3 is stale and designate pdp1
- *
- * 7) pdp1 to run audit
- */
- runAudit(integrityAudit);
- waitStaleAndRun(integrityAudit2);
- waitStaleAndRun(integrityAudit3);
- waitStaleAndRun(integrityAudit);
-
- verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1");
-
- logger.info("testThreeResources: Exiting");
-
- }
-
- /*
- * Tests designation logic when four functioning resources are in play, two with one PU, two
- * with another. Audits for persistenceUnit and PU_B should run simultaneously. Designation
- * should alternate between resources for each of the two persistence units.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testFourResourcesDifferentPus() throws Exception {
-
- logger.info("testFourResourcesDifferentPus: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1|pdp3)");
- final ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2|pdp4)");
-
- /*
- * Start audit for "pdp1", testPU.
- */
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Start audit for pdp2, integrityAuditPU.
- */
- MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU);
-
- /*
- * Start audit for pdp3, testPU.
- */
- MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU);
-
- /*
- * Start audit for pdp4, integrityAuditPU.
- */
- MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", B_SEQ_PU);
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp1 and pdp2 to run audit simultaneously
- *
- * 2) Logic to detect that pdp1 and pdp2 are stale and designate pdp3 (one's counterpart)
- * and pdp4 (two's counterpart)
- *
- * 3) pdp3 and pdp4 to run audit simultaneously
- *
- * 4) Logic to detect that pdp3 and pdp4 are stale and designate pdp1 (three's counterpart)
- * and pdp2 (four's counterpart)
- *
- * 5) pdp1 and pdp2 to run audit simultaneously
- */
- runAudit(integrityAudit, integrityAudit2);
- waitStaleAndRun(integrityAudit3, integrityAudit4);
- waitStaleAndRun(integrityAudit, integrityAudit2);
-
- /*
- * These sequences may be intermingled, so we extract and compare one sequence at a time.
- */
-
- // only care about pdp1 & pdp3 in this sequence
- verifyItemsInLog(logA, "pdp1", "pdp3", "pdp1");
-
- // only care about pdp2 & pdp4 in this sequence
- verifyItemsInLog(logB, "pdp2", "pdp4", "pdp2");
-
- logger.info("testFourResourcesDifferentPus: Exiting");
-
- }
-
- /*
- * Tests designation logic when four resources are in play but one is not functioning.
- * Designation should round robin among functioning resources only.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testFourResourcesOneDead() throws Exception {
-
- logger.info("testFourResourcesOneDead: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE);
-
- /*
- * Start audit for pdp1.
- */
- MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Start audit for pdp2.
- */
- MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU);
-
- /*
- * Populate DB for pdp3, which will simulate it having registered but then having died.
- */
- new DbDao("pdp3", A_SEQ_PU, makeProperties()).destroy();
-
- /*
- * Start audit for pdp4.
- */
- MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", A_SEQ_PU);
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp1 to run audit
- *
- * 2) Logic to detect that pdp1 is stale and designate pdp2
- *
- * 3) pdp2 to run audit
- *
- * 4) Logic to detect that pdp2 is stale and designate pdp4
- *
- * 5) pdp4 to run audit
- *
- * 6) Logic to detect that pdp4 is stale and designate pdp1
- *
- * 7) pdp1 to run audit
- *
- * 8) Logic to detect that pdp1 is stale and designate pdp2
- *
- * 7) pdp2 to run audit
- */
- runAudit(integrityAudit);
- waitStaleAndRun(integrityAudit2);
- waitStaleAndRun(integrityAudit4);
- waitStaleAndRun(integrityAudit);
- waitStaleAndRun(integrityAudit2);
- waitStaleAndRun(integrityAudit4);
-
- verifyItemsInLog(logA, "pdp1", "pdp2", "pdp4", "pdp1", "pdp2", "pdp4");
-
- logger.info("testFourResourcesOneDead: Exiting");
-
- }
-
- /*
- * Tests designation logic when four resources are in play but only one is functioning.
- * Designation should remain with sole functioning resource.
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testFourResourcesThreeDead() throws Exception {
-
- logger.info("testFourResourcesThreeDead: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE);
-
- /*
- * Populate DB for "pdp1", which will simulate it having registered but then having died.
- */
- new DbDao("pdp1", A_SEQ_PU, makeProperties()).destroy();
-
- /*
- * Populate DB for pdp2, which will simulate it having registered but then having died.
- */
- new DbDao("pdp2", A_SEQ_PU, makeProperties()).destroy();
-
- /*
- * Start audit for pdp3.
- */
- MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU);
-
- /*
- * Populate DB for pdp4, which will simulate it having registered but then having died.
- */
- new DbDao("pdp4", A_SEQ_PU, makeProperties()).destroy();
-
- /*
- * Sleep long enough to allow
- *
- * 1) pdp3 to discover that all other designation candidates are stale
- *
- * 1) pdp3 to run audit
- *
- * 2) Logic to detect that no other nodes are available for designation
- *
- * 3) pdp3 to run audit again
- */
- runAudit(integrityAudit3);
- waitStaleAndRun(integrityAudit3);
-
- verifyItemsInLog(logA, "pdp3", "pdp3");
-
- logger.info("testFourResourcesThreeDead: Exiting");
-
- }
-
- /*
- * Tests designation logic when the designated node dies and is no longer current
- *
- * Note: console.log must be examined to ascertain whether or not this test was successful.
- */
- @Test
- void testDesignatedNodeDead() throws Exception {
- logger.info("testDesignatedNodeDead: Entering");
-
- final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE);
-
- /*
- * Instantiate audit object for pdp1.
- */
- final MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU);
-
- /*
- * Start audit for pdp2.
- */
- final MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU);
-
- /*
- * Instantiate audit object for pdp3.
- */
- final MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU);
-
- // Start audit on pdp1
- logger.info("testDesignatedNodeDead: Start audit on pdp1");
- runAudit(integrityAudit);
-
- // Start the auditing threads on other nodes.
- logger.info("testDesignatedNodeDead: Start audit on pdp2");
- runAudit(integrityAudit2);
-
- // Kill audit on pdp1
- logger.info("testDesignatedNodeDead: Kill audit on pdp1");
- integrityAudit.stopAuditThread();
-
- // Wait long enough for pdp1 to get stale and pdp2 to take over
- waitStaleAndRun(integrityAudit2);
-
- // Start audit thread on pdp1 again.
- logger.info("testDesignatedNodeDead: Start audit thread on pdp1 again.");
- integrityAudit.startAuditThread();
-
- // Wait long enough for pdp2 to complete its audit and get stale, at
- // which point pdp3 should take over
- logger.info(
- "testDesignatedNodeDead: Wait long enough for pdp2 to complete its audit and get stale, at which point"
- + " pdp3 should take over");
- waitStaleAndRun(integrityAudit3);
-
- // Kill audit on pdp3
- logger.info("testDesignatedNodeDead: Killing audit on pdp3");
- integrityAudit3.stopAuditThread();
-
- // Wait long enough for pdp3 to get stale and pdp1 to take over
- logger.info("testDesignatedNodeDead: Wait long enough for pdp3 to get stale and pdp1 to take over");
- waitStaleAndRun(integrityAudit);
-
- verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1");
-
- logger.info("testDesignatedNodeDead: Exiting");
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java
deleted file mode 100644
index bd0aad55..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Properties;
-import org.junit.jupiter.api.Test;
-
-class IntegrityAuditTest {
- private static final String PROPERTIES = "properties";
- private static final String RESOURCE_NAME = "resourceName";
- private static final String SOMETHING = "something";
-
- /**
- * Test if we can access the updated bad params outside of the parmsAreBad method.
- */
- @Test
- void testParmsAreBad() {
- // Try with 2 null params
- StringBuilder badParams = new StringBuilder();
- IntegrityAudit.parmsAreBad(null, SOMETHING, null, badParams);
-
- assertNotEquals("", badParams.toString());
- assertTrue(badParams.toString().contains(RESOURCE_NAME));
- assertTrue(badParams.toString().contains(PROPERTIES));
-
- // Try with 1 null params
- badParams = new StringBuilder();
- Properties props = new Properties();
- props.put(IntegrityAuditProperties.DB_DRIVER, "test_db_driver");
- IntegrityAudit.parmsAreBad(null, SOMETHING, props, badParams);
-
- assertNotEquals("", badParams.toString());
- assertTrue(badParams.toString().contains(RESOURCE_NAME));
- assertFalse(badParams.toString().contains(PROPERTIES));
-
- // Try with 0 null params
- badParams = new StringBuilder();
- IntegrityAudit.parmsAreBad("someting", SOMETHING, props, badParams);
- assertNotEquals("", badParams.toString());
- assertFalse(badParams.toString().contains(RESOURCE_NAME));
- assertFalse(badParams.toString().contains(PROPERTIES));
-
- // Try with invalid node type
- props.put(IntegrityAuditProperties.NODE_TYPE, "bogus");
- badParams = new StringBuilder();
- IntegrityAudit.parmsAreBad("someting", SOMETHING, props, badParams);
- assertNotEquals("", badParams.toString());
- assertTrue(badParams.toString().contains("nodeType"));
-
- }
-
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java
deleted file mode 100644
index e0c22a1e..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java
+++ /dev/null
@@ -1,658 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.Logger;
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.EntityTransaction;
-import jakarta.persistence.Persistence;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import java.util.function.Supplier;
-import org.onap.policy.common.utils.jpa.EntityMgrCloser;
-import org.onap.policy.common.utils.jpa.EntityMgrFactoryCloser;
-import org.onap.policy.common.utils.jpa.EntityTransCloser;
-import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
-import org.onap.policy.common.utils.time.CurrentTime;
-import org.onap.policy.common.utils.time.TestTime;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.util.ReflectionTestUtils;
-
-/**
- * All JUnits are designed to run in the local development environment where they have write
- * privileges and can execute time-sensitive tasks.
- *
- * <p>Many of the test verification steps are performed by scanning for items written to the log
- * file. Rather than actually scan the log file, an {@link ExtractAppender} is used to monitor
- * events that are logged and extract relevant items. In order to attach the appender to the debug
- * log, it assumes that the debug log is a <i>logback</i> Logger configured per EELF.
- *
- * <p>These tests use a temporary, in-memory DB, which is dropped once the tests complete.
- */
-class IntegrityAuditTestBase {
-
- /**
- * Root of the debug logger, as defined in the logback-test.xml.
- */
- protected static final Logger debugLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.debug");
-
- /**
- * Root of the error logger, as defined in the logback-test.xml.
- */
- protected static final Logger errorLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.error");
-
- /**
- * Directory containing the log files.
- */
- private static final String LOG_DIR = "testingLogs/common-modules/integrity-audit";
-
-
- /**
- * Name of the field within the AuditorTime class that supplies the time.
- */
- public static final String TIME_SUPPLY_FIELD = "supplier";
-
-
- /**
- * Max time, in milliseconds, to wait for a semaphore.
- */
- protected static final long WAIT_MS = 5000L;
-
- /**
- * Number of seconds in an audit period.
- */
- public static final int AUDIT_PERIOD_SEC = 5;
-
- public static final String DEFAULT_DB_URL_PREFIX = "jdbc:h2:mem:";
-
- protected static final String DB_DRIVER = "org.h2.Driver";
- protected static final String DB_USER = "testu";
- protected static final String DB_PASS = "testp";
- protected static final String SITE_NAME = "SiteA";
- protected static final String NODE_TYPE = "pdp_xacml";
-
- // will be defined by the test *Classes*
- protected static String dbUrl;
-
- /**
- * Persistence unit for PDP sequence A.
- */
- protected static final String A_SEQ_PU = "testPU";
-
- /**
- * Persistence unit for PDP sequence B.
- */
- protected static final String B_SEQ_PU = "integrityAuditPU";
-
- /**
- * Matches the start of an audit for arbitrary PDPs in the debug log.
- */
- protected static final String START_AUDIT_RE = "Running audit for persistenceUnit=\\w+ on resourceName=([^,]*)";
-
- /**
- * Properties to be used in all tests.
- */
- protected static Properties properties;
-
- /**
- * Entity manager factory pointing to the in-memory DB for A_SEQ_PU.
- */
- protected static EntityManagerFactory emf;
-
- /**
- * Entity manager factory pointing to the in-memory DB associated with emf.
- */
- protected static EntityManager em;
-
- /**
- * Current time used by given test.
- */
- private static ThreadLocal<TestTime> testTime = ThreadLocal.withInitial(() -> null);
-
- /**
- * Supplies the test time so that each thread maintains its own notion of "current"
- * time.
- */
- private static Supplier<TestTime> timeSupplier = () -> testTime.get();
-
- /**
- * Saved debug logger level, to be restored once all tests complete.
- */
- private static Level savedDebugLevel;
-
- /**
- * Saved error logger level, to be restored once all tests complete.
- */
- private static Level savedErrorLevel;
-
- /**
- * Saved time, to be restored once all tests complete.
- */
- private static Supplier<CurrentTime> savedTime;
-
- /**
- * List of auditors whose threads must be stopped when a given test case ends.
- */
- private List<MyIntegrityAudit> auditors;
-
- /**
- * List of appenders that must be removed from loggers when a given test case ends.
- */
- private List<LogApp> appenders;
-
- /**
- * Saves current configuration information and then sets new values.
- *
- * @param dbUrl the URL to the DB
- * @throws IOException if an IO error occurs
- */
- @SuppressWarnings("unchecked")
- protected static void setUpBeforeClass(String dbUrl) throws IOException {
-
- // truncate the logs
- new FileOutputStream(LOG_DIR + "/audit.log").close();
- new FileOutputStream(LOG_DIR + "/debug.log").close();
- new FileOutputStream(LOG_DIR + "/error.log").close();
- new FileOutputStream(LOG_DIR + "/metrics.log").close();
-
- IntegrityAuditTestBase.dbUrl = dbUrl;
-
- // save data that we have to restore at the end of the test
- savedTime = (Supplier<CurrentTime>) ReflectionTestUtils.getField(AuditorTime.class, TIME_SUPPLY_FIELD);
- savedDebugLevel = debugLogger.getLevel();
- savedErrorLevel = errorLogger.getLevel();
-
- IntegrityAudit.setUnitTesting(true);
-
- properties = new Properties();
- properties.put(IntegrityAuditProperties.DB_DRIVER, DB_DRIVER);
- properties.put(IntegrityAuditProperties.DB_URL, dbUrl);
- properties.put(IntegrityAuditProperties.DB_USER, DB_USER);
- properties.put(IntegrityAuditProperties.DB_PWD, DB_PASS);
- properties.put(IntegrityAuditProperties.SITE_NAME, SITE_NAME);
- properties.put(IntegrityAuditProperties.NODE_TYPE, NODE_TYPE);
-
- emf = Persistence.createEntityManagerFactory(A_SEQ_PU, makeProperties());
-
- // keep this open so the in-memory DB stays around until all tests are
- // done
- em = emf.createEntityManager();
-
- ReflectionTestUtils.setField(AuditorTime.class, TIME_SUPPLY_FIELD, timeSupplier);
- debugLogger.setLevel(Level.DEBUG);
- errorLogger.setLevel(Level.ERROR);
- }
-
- /**
- * Restores the configuration to what it was before the test.
- */
- protected static void tearDownAfterClass() {
-
- IntegrityAudit.setUnitTesting(false);
-
- ReflectionTestUtils.setField(AuditorTime.class, TIME_SUPPLY_FIELD, savedTime);
- debugLogger.setLevel(savedDebugLevel);
- errorLogger.setLevel(savedErrorLevel);
-
- // this should result in the in-memory DB being deleted
- em.close();
- emf.close();
- }
-
- /**
- * Sets up for a test, which includes deleting all records from the IntegrityAuditEntity table.
- */
- protected void setUp() {
- auditors = new LinkedList<>();
- appenders = new LinkedList<>();
-
- properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, String.valueOf(AUDIT_PERIOD_SEC));
-
- TestTime time = new TestTime();
- testTime.set(time);
-
- // Clean up the DB
- try (EntityTransCloser etc = new EntityTransCloser(em.getTransaction())) {
- EntityTransaction et = etc.getTransaction();
-
- em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
-
- // commit transaction
- et.commit();
- }
- }
-
- /**
- * Cleans up after a test, removing any ExtractAppenders from the logger and stopping any
- * AuditThreads.
- */
- protected void tearDown() {
- for (LogApp p : appenders) {
- p.detach();
- }
-
- for (MyIntegrityAudit p : auditors) {
- p.stopAuditThread();
- }
- }
-
- /**
- * Get the test time.
- *
- * @return the {@link TestTime} in use by this thread
- */
- public static TestTime getTestTime() {
- return testTime.get();
- }
-
- /**
- * Truncate the table.
- *
- * @param properties the properties
- * @param persistenceUnit the persistence unit
- * @param tableName the name of the table
- */
- void truncateTable(Properties properties, String persistenceUnit, String tableName) {
-
- try (EntityMgrFactoryCloser emfc =
- new EntityMgrFactoryCloser(Persistence.createEntityManagerFactory(persistenceUnit, properties));
- EntityMgrCloser emc = new EntityMgrCloser(emfc.getFactory().createEntityManager());
- EntityTransCloser etc = new EntityTransCloser(emc.getManager().getTransaction())) {
-
- EntityManager entmgr = emc.getManager();
- EntityTransaction entrans = etc.getTransaction();
-
- // Clean up the DB
- entmgr.createQuery("Delete from " + tableName).executeUpdate();
-
- // commit transaction
- entrans.commit();
- }
- }
-
- /**
- * Verifies that items appear within the log, in order. A given item may appear more than once.
- * In addition, the log may contain extra items; those are ignored.
- *
- * @param app where data has been logged
- * @param items items that should be matched by the items extracted from the log, in order
- * @throws IOException if an IO error occurs
- * @throws AssertionError if the desired items were not all found
- */
- protected void verifyItemsInLog(ExtractAppender app, String... items) throws IOException {
-
- Iterator<String> it = new ArrayList<>(Arrays.asList(items)).iterator();
- if (!it.hasNext()) {
- return;
- }
-
- String expected = it.next();
- String last = null;
-
- for (String extractedText : app.getExtracted()) {
- if (extractedText.equals(expected)) {
- if (!it.hasNext()) {
- // matched all of the items
- return;
- }
-
- last = expected;
- expected = it.next();
-
- } else if (!extractedText.equals(last)) {
- List<String> remaining = getRemaining(expected, it);
- fail("missing items " + remaining + ", but was: " + extractedText);
- }
- }
-
- List<String> remaining = getRemaining(expected, it);
- assertTrue(remaining.isEmpty(), "missing items " + remaining);
- }
-
- /**
- * Gets the remaining items from an iterator.
- *
- * @param current the current item, to be included within the list
- * @param it iterator from which to get the remaining items
- * @return a list of the remaining items
- */
- private LinkedList<String> getRemaining(String current, Iterator<String> it) {
- LinkedList<String> remaining = new LinkedList<>();
- remaining.add(current);
-
- while (it.hasNext()) {
- remaining.add(it.next());
- }
- return remaining;
- }
-
- /**
- * Waits for a thread to stop. If the thread doesn't complete in the allotted time, then it
- * interrupts it and waits again.
- *
- * @param auditor the thread for which to wait
- * @return {@code true} if the thread stopped, {@code false} otherwise
- */
- public boolean waitThread(MyIntegrityAudit auditor) {
- if (auditor != null) {
- try {
- auditor.interrupt();
-
- if (!auditor.joinAuditThread(WAIT_MS)) {
- errorLogger.error("failed to stop audit thread");
- return false;
- }
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
-
- return true;
- }
-
- /**
- * Makes a new auditor.
- *
- * @param resourceName2 the name of the resource
- * @param persistenceUnit2 the persistence unit
- * @return a new auditor
- * @throws Exception if an error occurs
- */
- protected MyIntegrityAudit makeAuditor(String resourceName2, String persistenceUnit2) throws Exception {
- // each auditor gets its own notion of time
- TestTime time = new TestTime();
-
- // use the auditor-specific time while this thread constructs things
- testTime.set(time);
-
- return new MyIntegrityAudit(resourceName2, persistenceUnit2, makeProperties(), time);
- }
-
- /**
- * Watches for patterns in a logger by attaching a ExtractAppender to it.
- *
- * @param logger the logger to watch
- * @param regex regular expression used to extract relevant text
- * @return a new appender
- */
- protected ExtractAppender watch(Logger logger, String regex) {
- ExtractAppender app = new ExtractAppender(regex);
- appenders.add(new LogApp(logger, app));
-
- return app;
- }
-
- /**
- * Makes a new Property set that's a clone of {@link #properties}.
- *
- * @return a new Property set containing all of a copy of all of the {@link #properties}
- */
- protected static Properties makeProperties() {
- Properties props = new Properties();
- props.putAll(properties);
- return props;
- }
-
- /**
- * Waits for data to become stale and then runs an audit on several auditors in parallel.
- *
- * @param auditors the auditors
- * @throws InterruptedException if a thread is interrupted
- */
- protected void waitStaleAndRun(MyIntegrityAudit... auditors) throws InterruptedException {
- waitStale();
- runAudit(auditors);
- }
-
- /**
- * Runs an audit on several auditors in parallel.
- *
- * @param auditors the auditors
- * @throws InterruptedException if a thread is interrupted
- */
- protected void runAudit(MyIntegrityAudit... auditors) throws InterruptedException {
-
- // start an audit cycle on each auditor
- List<Semaphore> semaphores = new ArrayList<>(auditors.length);
- for (MyIntegrityAudit p : auditors) {
- semaphores.add(p.startAudit());
- }
-
- // wait for each auditor to complete its cycle
- for (Semaphore sem : semaphores) {
- waitSem(sem);
- }
- }
-
- /**
- * Waits for a semaphore to be released.
- *
- * @param sem the semaphore for which to wait
- * @throws InterruptedException if the thread is interrupted
- * @throws AssertionError if the semaphore did not reach zero in the allotted time
- */
- protected void waitSem(Semaphore sem) throws InterruptedException {
- assertTrue(sem.tryAcquire(WAIT_MS, TimeUnit.MILLISECONDS));
- }
-
- /**
- * Sleep a bit so that the currently designated pdp becomes stale.
- *
- * @throws InterruptedException if the thread is interrupted
- */
- protected void waitStale() throws InterruptedException {
- // waits for ALL auditors to become stale, as each has its own timer
- for (MyIntegrityAudit auditor : auditors) {
- auditor.sleep(AuditThread.AUDIT_COMPLETION_INTERVAL * AuditThread.AUDIT_RESET_CYCLES + 1);
- }
- }
-
- /**
- * Tracks which appender has been added to a logger.
- */
- private static class LogApp {
- private final Logger logger;
- private final ExtractAppender appender;
-
- public LogApp(Logger logger, ExtractAppender appender) {
- this.logger = logger;
- this.appender = appender;
-
- logger.addAppender(appender);
-
- appender.start();
- }
-
- void detach() {
- logger.detachAppender(appender);
- }
- }
-
- /**
- * Manages audits by inserting semaphores into a queue for the AuditThread to count.
- */
- protected class MyIntegrityAudit extends IntegrityAudit {
-
- private final TestTime myTime;
-
- /**
- * Semaphore on which the audit thread should wait.
- */
- private Semaphore auditSem = null;
-
- /**
- * Semaphore on which the junit management thread should wait.
- */
- private Semaphore junitSem = null;
-
- /**
- * Constructs an auditor and starts the AuditThread.
- *
- * @param resourceName the resource name
- * @param persistenceUnit the persistence unit
- * @param properties the properties
- * @param time the time
- * @throws Exception if an error occurs
- */
- public MyIntegrityAudit(String resourceName, String persistenceUnit,
- Properties properties, TestTime time) throws Exception {
- super(resourceName, persistenceUnit, properties);
-
- myTime = time;
- testTime.set(myTime);
-
- auditors.add(this);
-
- startAuditThread();
- }
-
- /**
- * Get time in milliseconds.
- *
- * @return the "current" time for the auditor
- */
- public long getTimeInMillis() {
- return myTime.getMillis();
- }
-
- /**
- * Sleeps for a period of time.
- *
- * @param sleepMs time to sleep
- * @throws InterruptedException can be interrupted
- */
- void sleep(long sleepMs) throws InterruptedException {
- myTime.sleep(sleepMs);
- }
-
- /**
- * Interrupts the AuditThread.
- */
- void interrupt() {
- super.stopAuditThread();
- }
-
- /**
- * Triggers an audit by releasing the audit thread's semaphore.
- *
- * @return the semaphore on which to wait
- * @throws InterruptedException if the thread is interrupted
- */
- public Semaphore startAudit() throws InterruptedException {
- auditSem.release();
- return junitSem;
- }
-
- /**
- * Starts a new AuditThread. Creates a new pair of semaphores and associates them
- * with the thread.
- */
- @Override
- public final void startAuditThread() throws IntegrityAuditException {
- if (auditSem != null) {
- // release a bunch of semaphores, in case a thread is still running
- auditSem.release(1000);
- }
-
- auditSem = new Semaphore(0);
- junitSem = new Semaphore(0);
-
- super.startAuditThread();
-
- if (haveAuditThread()) {
- // tell the thread it can run
- auditSem.release();
-
- // wait for the thread to start
- try {
- waitSem(junitSem);
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new IntegrityAuditException(e);
- }
- }
- }
-
- /**
- * Stops the AuditThread and waits for it to stop.
- *
- * @throws AssertionError if the thread is still running
- */
- @Override
- public void stopAuditThread() {
- super.stopAuditThread();
-
- assertTrue(waitThread(this));
- }
-
- @Override
- protected AuditThread makeAuditThread(String resourceName2, String persistenceUnit2, Properties properties2,
- int integrityAuditPeriodSeconds2) throws IntegrityAuditException {
-
- // make sure we're still using the auditor's time while we construct things
- testTime.set(myTime);
-
- return new AuditThread(resourceName2, persistenceUnit2, properties2, integrityAuditPeriodSeconds2, this) {
-
- private Semaphore auditSem = MyIntegrityAudit.this.auditSem;
- private Semaphore junitSem = MyIntegrityAudit.this.junitSem;
-
- @Override
- public void run() {
- // make sure our thread uses this auditor's time
- testTime.set(myTime);
- super.run();
- }
-
- @Override
- public void runStarted() throws InterruptedException {
- auditSem.acquire();
-
- junitSem.release();
- auditSem.acquire();
- }
-
- @Override
- public void auditCompleted() throws InterruptedException {
- junitSem.release();
- auditSem.acquire();
- }
-
- };
- }
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java
deleted file mode 100644
index 8a34909a..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021, 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQueries;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Table;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.Serializable;
-import java.util.Date;
-
-@Entity
-@Table(name = "IaTestEntity")
-@NamedQueries({@NamedQuery(name = " IaTestEntity.findAll", query = "SELECT e FROM IaTestEntity e "),
- @NamedQuery(name = "IaTestEntity.deleteAll", query = "DELETE FROM IaTestEntity WHERE 1=1")})
-
-public class IaTestEntity implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "ImTestId")
- private long imTestId;
-
- @Column(name = "created_by", nullable = false, length = 255)
- private String createdBy = "guest";
-
- @Column(name = "person", nullable = false, length = 255)
- private PersonSample person;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_date", updatable = false)
- private Date createdDate;
-
- @Column(name = "modified_by", nullable = false, length = 255)
- private String modifiedBy = "guest";
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "modified_date", nullable = false)
- private Date modifiedDate;
-
- public IaTestEntity() {
- super();
- }
-
- /**
- * PrePersist call back method.
- */
- @PrePersist
- public void prePersist() {
- Date date = new Date();
- this.createdDate = date;
- this.modifiedDate = date;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.modifiedDate = new Date();
- }
-
- /**
- * The the Im test Id.
- *
- * @return the Id
- */
- public long getImTestId() {
- return imTestId;
- }
-
- /**
- * Get the createdBy.
- *
- * @return the createdBy
- */
- public String getCreatedBy() {
- return createdBy;
- }
-
- /**
- * Set the createdBy.
- *
- * @param createdBy the createdBy to set
- */
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
-
- /**
- * Get the modifiedBy.
- *
- * @return the modifiedBy
- */
- public String getModifiedBy() {
- return modifiedBy;
- }
-
- /**
- * Set the ModifiedBy.
- *
- * @param modifiedBy the modifiedBy to set
- */
- public void setModifiedBy(String modifiedBy) {
- this.modifiedBy = modifiedBy;
- }
-
- /**
- * Get the ModifiedDate.
- *
- * @return the modifiedDate
- */
- public Date getModifiedDate() {
- return modifiedDate;
- }
-
- /**
- * Set the ModifiedDate.
- *
- * @param modifiedDate the modifiedDate to set
- */
- public void setModifiedDate(Date modifiedDate) {
- this.modifiedDate = modifiedDate;
- }
-
- /**
- * Get the CreatedDate.
- *
- * @return the createdDate
- */
- public Date getCreatedDate() {
- return createdDate;
- }
-
- /**
- * Set the person.
- *
- * @param person the person to set
- */
- public void setPersonTest(PersonSample person) {
- this.person = person;
- }
-
- /**
- * Get the person.
- *
- * @return the person
- */
- public PersonSample getPersonTest() {
- return person;
- }
-}
diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java
deleted file mode 100644
index 47fa843b..00000000
--- a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.ia.jpa;
-
-import java.io.Serializable;
-
-public class PersonSample implements Serializable {
-
- private static final long serialVersionUID = 1L;
- private String firstName;
- private String lastName;
- private int age;
-
- /**
- * Create an instance.
- *
- * @param first first name
- * @param last last name
- * @param age age
- */
- public PersonSample(String first, String last, int age) {
- this.firstName = first;
- this.lastName = last;
- this.age = age;
- }
-
- public String getFirstName() {
- return this.firstName;
- }
-
- public void setFirstName(String name) {
- this.firstName = name;
- }
-
- public String getLasttName() {
- return this.lastName;
- }
-
- public void setLastName(String name) {
- this.lastName = name;
- }
-
- public int getAge() {
- return this.age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
-}
diff --git a/integrity-audit/src/test/resources/log4j.properties b/integrity-audit/src/test/resources/log4j.properties
deleted file mode 100644
index 3defb164..00000000
--- a/integrity-audit/src/test/resources/log4j.properties
+++ /dev/null
@@ -1,54 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# Integrity Audit
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END=========================================================
-###
-
-#
-# Use this properties for debugging and development.
-#
-#
-# For debug output, set root logger level to DEBUG and output to FILE and CONSOLE
-log4j.rootLogger=DEBUG, FILE, CONSOLE
-#log4j.rootLogger=INFO, FILE, CONSOLE
-
-# A1 is set to be a DailyRollingFileAppender.
-log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
-
-# Set the name of the file
-log4j.appender.FILE.File=IntegrityAudit.log
-
-# Set the immediate flush to true (default)
-log4j.appender.FILE.ImmediateFlush=true
-
-# Set the threshold to debug mode
-log4j.appender.FILE.Threshold=debug
-
-# Set the append to false, should not overwrite
-log4j.appender.FILE.Append=true
-
-# Set the DatePattern
-log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
-
-# A1 uses PatternLayout.
-log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
-log4j.appender.FILE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n
-
-# for Developments and Debugging
-log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
-log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
-log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n
diff --git a/integrity-audit/src/test/resources/logback-test.xml b/integrity-audit/src/test/resources/logback-test.xml
deleted file mode 100644
index e3867e79..00000000
--- a/integrity-audit/src/test/resources/logback-test.xml
+++ /dev/null
@@ -1,258 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- Integrity Audit
- ================================================================================
- Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-<!-- Controls the output of logs for JUnit tests -->
-
-<configuration
- scan="false"
- debug="true">
- <!--<jmxConfigurator /> -->
- <!-- directory path for all other type logs -->
- <property
- name="logDir"
- value="testingLogs" />
-
- <!-- directory path for debugging type logs -->
- <property
- name="debugDir"
- value="testingLogs" />
-
- <!-- specify the component name
- <ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
- <property
- name="componentName"
- value="common-modules"></property>
- <property
- name="subComponentName"
- value="integrity-audit"></property>
-
- <!-- log file names -->
- <property
- name="errorLogName"
- value="error" />
- <property
- name="metricsLogName"
- value="metrics" />
- <property
- name="auditLogName"
- value="audit" />
- <property
- name="debugLogName"
- value="debug" />
-
- <property
- name="defaultPatternTimestamp"
- value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}" />
-
- <property
- name="defaultPatternTarget"
- value="%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}" />
-
-
- <property
- name="defaultPatternDetails"
- value="%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}" />
-
- <property
- name="defaultPattern"
- value="${defaultPatternTimestamp}|${defaultPatternTarget}|%p|${defaultPatternDetails}|%c||%msg%n" />
-
- <property
- name="logDirectory"
- value="${logDir}/${componentName}/${subComponentName}" />
- <property
- name="debugLogDirectory"
- value="${debugDir}/${componentName}/${subComponentName}" />
- <!--
- <property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
- <property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
- -->
- <!-- example from old log4j.properties: ${catalina.base}/logs/pdp-rest.log -->
- <!-- Example evaluator filter applied against console appender -->
- <appender
- name="STDOUT"
- class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
- <!-- ============================================================================ -->
- <!-- EELF Appenders -->
- <!-- ============================================================================ -->
-
- <!-- The EELFAppender is used to record events to the general application
- log -->
-
-
-
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
- these events as part of the application root log. -->
-
- <appender
- name="EELFAudit"
- class="ch.qos.logback.core.FileAppender">
- <file>${logDirectory}/${auditLogName}.log</file>
- <param
- name="Append"
- value="false" />
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
- <appender
- name="asyncEELFAudit"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFAudit" />
- </appender>
-
- <appender
- name="EELFMetrics"
- class="ch.qos.logback.core.FileAppender">
- <file>${logDirectory}/${metricsLogName}.log</file>
- <param
- name="Append"
- value="false" />
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
-
- <appender
- name="asyncEELFMetrics"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFMetrics" />
- </appender>
-
- <appender
- name="EELFError"
- class="ch.qos.logback.core.FileAppender">
- <file>${logDirectory}/${errorLogName}.log</file>
- <param
- name="Append"
- value="false" />
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>ERROR</level>
- </filter>
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
- <appender
- name="asyncEELFError"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFError" />
- </appender>
-
- <appender
- name="EELFDebug"
- class="ch.qos.logback.core.FileAppender">
- <file>${debugLogDirectory}/${debugLogName}.log</file>
- <param
- name="Append"
- value="false" />
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>DEBUG</level>
- </filter>
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
- <appender
- name="asyncEELFDebug"
- class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>256</queueSize>
- <appender-ref ref="EELFDebug" />
- <includeCallerData>true</includeCallerData>
- </appender>
-
- <!-- Appender for log testing -->
- <appender
- name="LoggingPatternTestAppender"
- class="ch.qos.logback.core.FileAppender">
- <file>${logDirectory}/logging-pattern-test.log</file>
- <param
- name="Append"
- value="false" />
- <encoder>
- <pattern>${defaultPattern}</pattern>
- </encoder>
- </appender>
-
-
- <!-- ============================================================================ -->
- <!-- EELF loggers -->
- <!-- ============================================================================ -->
-
- <logger
- name="com.att.eelf.audit"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFAudit" />
- </logger>
-
- <logger
- name="com.att.eelf.metrics"
- level="info"
- additivity="false">
- <appender-ref ref="asyncEELFMetrics" />
- </logger>
-
- <logger
- name="com.att.eelf.error"
- level="error"
- additivity="false">
- <appender-ref ref="asyncEELFError" />
- </logger>
-
- <!-- <logger name="com.att.eelf.debug" level="info" additivity="false"> -->
- <logger
- name="com.att.eelf.debug"
- level="debug"
- additivity="false">
- <appender-ref ref="asyncEELFDebug" />
- </logger>
-
-
- <!-- <root level="INFO"> -->
- <root level="DEBUG">
- <appender-ref ref="asyncEELFDebug" />
- <appender-ref ref="asyncEELFError" />
- </root>
-
- <!-- Logger for default pattern test -->
- <logger
- name="org.onap.policy.common.ia.DefaultLoggingPatternTest"
- level="trace"
- additivity="false">
- <appender-ref ref="LoggingPatternTestAppender" />
- </logger>
-
-</configuration>
diff --git a/integrity-audit/src/test/resources/logger-test.expectedlog b/integrity-audit/src/test/resources/logger-test.expectedlog
deleted file mode 100644
index 69df8f96..00000000
--- a/integrity-audit/src/test/resources/logger-test.expectedlog
+++ /dev/null
@@ -1 +0,0 @@
-2019-12-05T13:24:14.110Z|TheRequestId|TheServiceInstanceId|main|TheServerName|TheServiceName|TheInstanceUuid|INFO|TheSeverity|TheServerIpAddress|TheServer|TheClientIpAddress|org.onap.policy.common.ia.DefaultLoggingPatternTest||This is a test logging string for logger
diff --git a/integrity-audit/src/test/resources/policyLogger.properties b/integrity-audit/src/test/resources/policyLogger.properties
deleted file mode 100644
index 42cf1cfd..00000000
--- a/integrity-audit/src/test/resources/policyLogger.properties
+++ /dev/null
@@ -1,45 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# Integrity Audit
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END=========================================================
-###
-
-################################### Set concurrentHashMap and timer info #######################
-#Timer initial delay and the delay between in milliseconds before task is to be execute.
-timer.delay.time=1000
-#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions.
-check.interval= 30000
-#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds.
-event.expired.time=86400
-#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer
-# gets executed to remove all expired records from this concurrentHashMap.
-concurrentHashMap.limit=5000
-#Size of the concurrentHashMap - when its size drops to this point, stop the Timer
-stop.check.point=2500
-################################### Set logging format #############################################
-# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println
-logger.type=EELF
-#################################### Set level for EELF or SYSTEMOUT logging ##################################
-# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to
-# disable all
-debugLogger.level=DEBUG
-# Set level for metrics file. Set OFF to disable; set ON to enable
-metricsLogger.level=ON
-# Set level for error file. Set OFF to disable; set ON to enable
-error.level=ON
-# Set level for audit file. Set OFF to disable; set ON to enable
-audit.level=ON
diff --git a/integrity-audit/src/test/resources/xlogger-test.expectedlog b/integrity-audit/src/test/resources/xlogger-test.expectedlog
deleted file mode 100644
index a9ad4992..00000000
--- a/integrity-audit/src/test/resources/xlogger-test.expectedlog
+++ /dev/null
@@ -1 +0,0 @@
-2019-12-05T13:24:14.110Z|TheRequestId|TheServiceInstanceId|main|TheServerName|TheServiceName|TheInstanceUuid|INFO|TheSeverity|TheServerIpAddress|TheServer|TheClientIpAddress|org.onap.policy.common.ia.DefaultLoggingPatternTest||This is a test logging string for xlogger
diff --git a/integrity-monitor/config/policyLogger.properties b/integrity-monitor/config/policyLogger.properties
deleted file mode 100644
index 1e7187f2..00000000
--- a/integrity-monitor/config/policyLogger.properties
+++ /dev/null
@@ -1,44 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# Integrity Audit
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ============LICENSE_END=========================================================
-###
-
-################################### Set concurrentHashMap and timer info #######################
-#Timer initial delay and the delay between in milliseconds before task is to be execute.
-timer.delay.time=1000
-#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions.
-check.interval= 30000
-#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds.
-event.expired.time=86400
-#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed
-#to remove all expired records from this concurrentHashMap.
-concurrentHashMap.limit=5000
-#Size of the concurrentHashMap - when its size drops to this point, stop the Timer
-stop.check.point=2500
-################################### Set logging format #############################################
-# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println
-logger.type=EELF
-#################################### Set level for EELF or SYSTEMOUT logging ##################################
-# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all
-debugLogger.level=INFO
-# Set level for metrics file. Set OFF to disable; set ON to enable
-metricsLogger.level=ON
-# Set level for error file. Set OFF to disable; set ON to enable
-error.level=ON
-# Set level for audit file. Set OFF to disable; set ON to enable
-audit.level=ON
diff --git a/integrity-monitor/policyLogger.properties b/integrity-monitor/policyLogger.properties
deleted file mode 100644
index 6a4c2d1a..00000000
--- a/integrity-monitor/policyLogger.properties
+++ /dev/null
@@ -1,44 +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=========================================================
-###
-
-################################### Set concurrentHashMap and timer info #######################
-#Timer initial delay and the delay between in milliseconds before task is to be execute.
-timer.delay.time=1000
-#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions.
-check.interval= 30000
-#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds.
-event.expired.time=86400
-#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed
-#to remove all expired records from this concurrentHashMap.
-concurrentHashMap.limit=5000
-#Size of the concurrentHashMap - when its size drops to this point, stop the Timer
-stop.check.point=2500
-################################### Set logging format #############################################
-# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println
-logger.type=EELF
-#################################### Set level for EELF or SYSTEMOUT logging ##################################
-# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all
-debugLogger.level=INFO
-# Set level for metrics file. Set OFF to disable; set ON to enable
-metricsLogger.level=ON
-# Set level for error file. Set OFF to disable; set ON to enable
-error.level=ON
-# Set level for audit file. Set OFF to disable; set ON to enable
-audit.level=ON
diff --git a/integrity-monitor/pom.xml b/integrity-monitor/pom.xml
deleted file mode 100644
index 442566fb..00000000
--- a/integrity-monitor/pom.xml
+++ /dev/null
@@ -1,87 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- ONAP Policy Engine - Common Modules
- ================================================================================
- Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023-2024 Nordix Foundation.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
- <modelVersion>4.0.0</modelVersion>
-
- <artifactId>integrity-monitor</artifactId>
-
- <packaging>jar</packaging>
-
- <parent>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>common-modules</artifactId>
- <version>3.0.1-SNAPSHOT</version>
- </parent>
-
- <name>Integrity Monitor</name>
-
- <dependencies>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>utils</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>ONAP-Logging</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate.orm</groupId>
- <artifactId>hibernate-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.hibernate.validator</groupId>
- <artifactId>hibernate-validator</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>utils-test</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-</project>
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java
deleted file mode 100644
index 14e0f0a8..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class AdministrativeStateException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public AdministrativeStateException() {
- super();
- }
-
- public AdministrativeStateException(String message) {
- super(message);
- }
-
- public AdministrativeStateException(Throwable cause) {
- super(cause);
- }
-
- public AdministrativeStateException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java
deleted file mode 100644
index 1583a9d5..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class AllSeemsWellException extends IntegrityMonitorException {
-
- private static final long serialVersionUID = 1L;
-
- public AllSeemsWellException() {
- super();
- }
-
- public AllSeemsWellException(String msg) {
- super(msg);
- }
-
- public AllSeemsWellException(String msg, Exception cause) {
- super(msg, cause);
- }
-
- public AllSeemsWellException(Exception cause) {
- super(cause);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java
deleted file mode 100644
index a72fe9e2..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class ForwardProgressException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public ForwardProgressException() {
- super();
- }
-
- public ForwardProgressException(String message) {
- super(message);
- }
-
- public ForwardProgressException(Throwable cause) {
- super(cause);
- }
-
- public ForwardProgressException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
deleted file mode 100644
index 7031c50a..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
+++ /dev/null
@@ -1,1915 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import com.google.re2j.Pattern;
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.EntityTransaction;
-import jakarta.persistence.FlushModeType;
-import jakarta.persistence.LockModeType;
-import jakarta.persistence.Persistence;
-import jakarta.persistence.TypedQuery;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Consumer;
-import java.util.function.IntConsumer;
-import java.util.function.LongConsumer;
-import java.util.function.Supplier;
-import javax.management.JMX;
-import javax.management.MBeanServerConnection;
-import lombok.Getter;
-import lombok.Setter;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.im.jmx.ComponentAdmin;
-import org.onap.policy.common.im.jmx.ComponentAdminMBean;
-import org.onap.policy.common.im.jmx.JmxAgentConnection;
-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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * IntegrityMonitor Main class for monitoring the integrity of a resource and managing its state. State management
- * follows the X.731 ITU standard.
- */
-public class IntegrityMonitor {
-
- private static final Logger logger = LoggerFactory.getLogger(IntegrityMonitor.class.getName());
-
- private static final Pattern COMMA_PAT = Pattern.compile(",");
- private static final Pattern SEMICOLON_PAT = Pattern.compile(";");
-
- // only allow one instance of IntegrityMonitor
- private static IntegrityMonitor instance = null;
-
- /*
- * Common strings
- */
- private static final String NULL_PROPERTY_STRING = " property is null";
- private static final String IGNORE_INVALID_PROPERTY_STRING = "Ignored invalid property: {}";
- private static final String PROPERTY_EXCEPTION_STRING = "IntegrityMonitor Property Exception: ";
- private static final String EXCEPTION_STRING = "IntegrityMonitor threw exception.";
- private static final String STATE_CHECK_STRING =
- "IntegrityMonitor.stateCheck(): " + "Failed to disableFail dependent resource = ";
- private static final String RESOURCE_STRING = "Resource ";
- private static final String LC_RESOURCE_STRING = "resource";
-
- /*
- * Query String
- */
- private static final String QUERY_STRING = "Select f from ForwardProgressEntity f where f.resourceName=:rn";
-
- private static String resourceName = null;
- boolean alarmExists = false;
-
- /*
- * Error message that is written by the dependencyCheck() method. It is made available externally through the
- * evaluateSanity() method.
- */
- private String dependencyCheckErrorMsg = "";
-
- // The entity manager factory for JPA access
- private final EntityManagerFactory emf;
- private final EntityManager em;
-
- // Persistence Unit for JPA
- public static final String PERSISTENCE_UNIT = "operationalPU";
-
- public static final long CYCLE_INTERVAL_MILLIS = 1000L;
-
- @Getter
- private StateManagement stateManager = null;
-
- /**
- * Set to {@code null} if to stop running.
- */
- private AtomicReference<Thread> fpManager = new AtomicReference<>();
-
- // The forward progress counter is incremented as the
- // process being monitored makes forward progress
- private int fpCounter = 0;
- private int lastFpCounter = 0;
-
- // elapsed time since last FP counter check
- private long elapsedTime = 0;
-
- // elapsed time since last test transaction check
- private long elapsedTestTransTime = 0;
-
- // elapsed time since last write Fpc check
- private long elapsedWriteFpcTime = 0;
-
- // last dependency health check time. Initialize so that the periodic check
- // starts after 60 seconds.
- // This allows time for dependents to come up.
- private long lastDependencyCheckTime = MonitorTime.getInstance().getMillis();
-
- // Time of the last state audit. It is initialized at the time of the IM
- // construction
- private Date lastStateAuditTime = MonitorTime.getInstance().getDate();
-
- // Interval between state audits in ms. We leave it turned off by default so
- // that it will only
- // be run on the nodes which we want doing the audit. In particular, we only
- // want it to run
- // on the droolspdps
- private static long stateAuditIntervalMs = 0L;
-
- // the number of cycles since 'fpCounter' was last changed
- private int missedCycles = 0;
-
- // forward progress monitoring interval
- private static long monitorIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_MONITOR_INTERVAL);
- // The number of periods the counter fails to increment before an alarm is
- // raised.
- private static int failedCounterThreshold = IntegrityMonitorProperties.DEFAULT_FAILED_COUNTER_THRESHOLD;
- // test transaction interval
- private static long testTransIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_TEST_INTERVAL);
- // write Fpc to DB interval
- private static long writeFpcIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_WRITE_FPC_INTERVAL);
- // check the health of dependencies
- private static long checkDependencyIntervalMs =
- toMillis(IntegrityMonitorProperties.DEFAULT_CHECK_DEPENDENCY_INTERVAL);
-
- // A lead subsystem will have dependency groups with resource names in the
- // properties file.
- // For non-lead subsystems, the dependency_group property will be absent.
- private static String[] depGroups = null;
-
- @Getter
- @Setter
- private static boolean unitTesting = false;
-
- // can turn on health checking of dependents via jmx test() call by setting
- // this property to true
- private static boolean testViaJmx = false;
-
- private static String jmxFqdn = null;
-
- // this is the max interval allowed without any forward progress
- // counter updates
- private static long maxFpcUpdateIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_MAX_FPC_UPDATE_INTERVAL);
-
- // Node types
- private enum NodeType {
- PDP_XACML, PDP_DROOLS, PAP, PAP_ADMIN, LOGPARSER, BRMS_GATEWAY, ASTRA_GATEWAY, ELK_SERVER, PYPDP
-
- }
-
- private static String siteName;
- private static String nodeType;
- private Date refreshStateAuditLastRunDate;
- private static long refreshStateAuditIntervalMs = 600000; // run it once per 10 minutes
-
- // lock objects
- private final Object evaluateSanityLock = new Object();
- private final Object fpMonitorCycleLock = new Object();
- private final Object dependencyCheckLock = new Object();
- private final Object testTransactionLock = new Object();
- private final Object startTransactionLock = new Object();
- private final Object endTransactionLock = new Object();
- private final Object checkTestTransactionLock = new Object();
- private final Object checkWriteFpcLock = new Object();
- private static final Object getInstanceLock = new Object();
- private final Object refreshStateAuditLock = new Object();
- private final Object imFlushLock = new Object();
-
- @Getter
- private Map<String, String> allSeemsWellMap;
- @Getter
- private Map<String, String> allNotWellMap;
-
- /**
- * IntegrityMonitor constructor. It is invoked from the getInstance() method in this class or from the constructor
- * of a child or subclass. A class can extend the IntegrityMonitor class if there is a need to override any of the
- * base methods (ex. subsystemTest()). Only one instance is allowed to be created per resource name.
- *
- * @param resourceName The resource name of the resource
- * @param properties a set of properties passed in from the resource
- * @throws IntegrityMonitorException if any errors are encountered in the constructor
- */
- protected IntegrityMonitor(String resourceName, Properties properties) throws IntegrityMonitorException {
-
- // singleton check since this constructor can be called from a child or
- // subclass
- if (instance != null) {
- var msg = "IM object exists and only one instance allowed";
- logger.error("{}", msg);
- throw new IntegrityMonitorException("IntegrityMonitor constructor exception: " + msg);
- }
-
- setInstance(this, resourceName);
-
- /*
- * Validate that the properties file contains all the needed properties. Throws an
- * IntegrityMonitorPropertiesException
- */
- validateProperties(properties);
-
- // construct jmx url
- String jmxUrl = getJmxUrlFromProps();
-
- //
- // Create the entity manager factory
- //
- emf = Persistence.createEntityManagerFactory(getPersistenceUnit(), properties);
-
- // add entry to forward progress and resource registration tables in DB
-
- // Start a transaction
- em = emf.createEntityManager();
- EntityTransaction et = em.getTransaction();
-
- et.begin();
-
- try {
- // if ForwardProgress entry exists for resourceName, update it. If
- // not found, create a new entry
- createOrUpdateForwardProgress(resourceName);
-
- // if ResourceRegistration entry exists for resourceName, update it.
- // If not found, create a new entry
- createOrUpdateResourceReg(resourceName, jmxUrl, et);
-
- } catch (Exception e) {
- logger.error("IntegrityMonitor constructor DB table update threw an exception");
- try {
- if (et.isActive()) {
- synchronized (imFlushLock) {
- et.rollback();
- }
- }
- } catch (Exception e1) {
- logger.error("IntegrityMonitor constructor threw exception: ", e1);
- }
- throw e;
- }
-
- makeStateManager(resourceName);
-
- // create management bean
- makeManagementBean(resourceName);
-
- // set now as the last time the refreshStateAudit ran
- IntegrityMonitor.this.refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate();
-
- fpManager.set(new Thread(this::runFpManager));
- fpManager.get().start();
-
- }
-
- protected void createOrUpdateForwardProgress(String resourceName) {
- TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
- fquery.setParameter("rn", resourceName);
-
- List<ForwardProgressEntity> fpList =
- fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ForwardProgressEntity fpx;
- if (!fpList.isEmpty()) {
- // ignores multiple results
- fpx = fpList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(fpx);
- if (logger.isDebugEnabled()) {
- logger.debug("Resource {} exists and will be updated - old fpc= {}, lastUpdated= {}", resourceName,
- fpx.getFpcCount(), fpx.getLastUpdated());
- }
- fpx.setFpcCount(fpCounter);
- } else {
- // Create a forward progress object
- logger.debug("Adding resource {} to ForwardProgress table", resourceName);
- fpx = new ForwardProgressEntity();
- }
- // update/set columns in entry
- fpx.setResourceName(resourceName);
- em.persist(fpx);
- // flush to the DB
- synchronized (imFlushLock) {
- em.flush();
- }
- }
-
- protected void createOrUpdateResourceReg(String resourceName, String jmxUrl, EntityTransaction et) {
- TypedQuery<ResourceRegistrationEntity> rquery =
- em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn",
- ResourceRegistrationEntity.class);
- rquery.setParameter("rn", resourceName);
-
- List<ResourceRegistrationEntity> rrList =
- rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ResourceRegistrationEntity rrx;
- if (!rrList.isEmpty()) {
- // ignores multiple results
- rrx = rrList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(rrx);
- if (logger.isDebugEnabled()) {
- logger.debug("Resource {} exists and will be updated - old url= {}, createdDate={}", resourceName,
- rrx.getResourceUrl(), rrx.getCreatedDate());
- }
- rrx.setLastUpdated(MonitorTime.getInstance().getDate());
- } else {
- // register resource by adding entry to table in DB
- logger.debug("Adding resource {} to ResourceRegistration table", resourceName);
- rrx = new ResourceRegistrationEntity();
- }
- // update/set columns in entry
- rrx.setResourceName(resourceName);
- rrx.setResourceUrl(jmxUrl);
- rrx.setNodeType(nodeType);
- rrx.setSite(siteName);
- em.persist(rrx);
- // flush to the DB
- synchronized (imFlushLock) {
- et.commit();
- }
- }
-
- protected void makeStateManager(String resourceName) throws IntegrityMonitorException {
- try {
- // create instance of StateManagement class and pass emf to it
- stateManager = new StateManagement(emf, resourceName);
-
- /*
- * Initialize the state and status attributes. This will maintain any Administrative state value but will
- * set the operational state = enabled, availability status = null, standby status = null. The integrity
- * monitor will set the operational state via the FPManager and the owning application must set the standby
- * status by calling promote/demote on the StateManager.
- */
- stateManager.initializeState();
-
- } catch (StateManagementException e) {
- throw new IntegrityMonitorException(e);
- }
- }
-
- protected void makeManagementBean(String resourceName) {
- try {
- new ComponentAdmin(resourceName, this, stateManager);
- } catch (Exception e) {
- logger.error("ComponentAdmin constructor exception: {}", e, e);
- }
- }
-
- private static void setInstance(IntegrityMonitor newInstance, String newResourceName) {
- instance = newInstance;
- resourceName = newResourceName;
- }
-
- /**
- * Get an instance of IntegrityMonitor for a given resource name. It creates one if it does not exist. Only one
- * instance is allowed to be created per resource name.
- *
- * @param resourceName The resource name of the resource
- * @param properties a set of properties passed in from the resource
- * @return The new instance of IntegrityMonitor
- * @throws IntegrityMonitorException if unable to create jmx url or the constructor returns an exception
- */
- public static IntegrityMonitor getInstance(String resourceName, Properties properties)
- throws IntegrityMonitorException {
-
- synchronized (getInstanceLock) {
- logger.debug("getInstance() called - resourceName= {}", resourceName);
- if (resourceName == null || resourceName.isEmpty() || properties == null) {
- logger.error("Error: getIntegrityMonitorInstance() called with invalid input");
- return null;
- }
-
- if (instance == null) {
- logger.debug("Creating new instance of IntegrityMonitor");
- // note: new() will populate "instance"
- new IntegrityMonitor(resourceName, properties);
- }
- return instance;
- }
- }
-
- /**
- * Get the single instance.
- *
- * @return the instance
- * @throws IntegrityMonitorException if no instance exists
- */
- public static IntegrityMonitor getInstance() throws IntegrityMonitorException {
- logger.debug("getInstance() called");
- if (instance == null) {
- String msg = "No IntegrityMonitor instance exists."
- + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)";
- throw new IntegrityMonitorPropertiesException(msg);
- } else {
- return instance;
- }
- }
-
- /**
- * This is a facility used by JUnit testing to destroy the IntegrityMonitor instance before creating a new one. It
- * waits a bit to allow the FPManager to fully exit.
- */
- public static void deleteInstance() throws IntegrityMonitorException {
- logger.debug("deleteInstance() called");
- synchronized (getInstanceLock) {
- if (isUnitTesting() && instance != null && instance.fpManager != null) {
- // Stop the FPManager thread
- Thread fpm = instance.fpManager.get();
- instance.fpManager = null;
- fpm.interrupt();
-
- try {
- // Make sure it has exited
- fpm.join(2000L);
- } catch (InterruptedException e) {
- logger.error("deleteInstance: Interrupted while waiting for FPManager to fully exit", e);
- Thread.currentThread().interrupt();
- }
-
- if (fpm.isAlive()) {
- logger.error("IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
- throw new IntegrityMonitorException(
- "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
- }
-
- instance = null;
- }
- }
- logger.debug("deleteInstance() exit");
- }
-
- private static String getJmxUrlFromProps() throws IntegrityMonitorException {
-
- // get the jmx remote port and construct the JMX URL
- var systemProps = System.getProperties();
- String jmxPort = systemProps.getProperty("com.sun.management.jmxremote.port");
- String jmxErrMsg;
- if (jmxPort == null) {
- jmxErrMsg = "System property com.sun.management.jmxremote.port for JMX remote port is not set";
- logger.error("{}", jmxErrMsg);
- throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
- }
-
- var port = 0;
- try {
- port = Integer.parseInt(jmxPort);
- } catch (NumberFormatException e) {
- jmxErrMsg = "JMX remote port is not a valid integer value - " + jmxPort;
- logger.error("{}", jmxErrMsg);
- throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
- }
-
- try {
- if (jmxFqdn == null) {
- // get FQDN of this host
- jmxFqdn = InetAddress.getLocalHost().getCanonicalHostName();
- }
- } catch (Exception e) {
- var msg = "getJmxUrl could not get hostname";
- logger.error("{}", msg, e);
- throw new IntegrityMonitorException("getJmxUrl Exception: " + msg);
- }
- if (jmxFqdn == null) {
- var msg = "getJmxUrl encountered null hostname";
- logger.error("{}", msg);
- throw new IntegrityMonitorException("getJmxUrl error: " + msg);
- }
-
- // assemble the jmx url
- String jmxUrl = "service:jmx:rmi:///jndi/rmi://" + jmxFqdn + ":" + port + "/jmxrmi";
-
- logger.debug("IntegrityMonitor - jmx url={}", jmxUrl);
-
- return jmxUrl;
- }
-
- /**
- * evaluateSanity() is designed to be called by an external entity to evaluate the sanity of the node. It checks the
- * operational and administrative states and the standby status. If the operational state is disabled, it will
- * include the dependencyCheckErrorMsg which includes information about any dependency (node) which has failed.
- */
- public void evaluateSanity() throws IntegrityMonitorException {
- logger.debug("evaluateSanity called ....");
- synchronized (evaluateSanityLock) {
-
- String errorMsg = dependencyCheckErrorMsg;
- logger.debug("evaluateSanity dependencyCheckErrorMsg = {}", errorMsg);
- // check op state and throw exception if disabled
- if ((stateManager.getOpState() != null) && stateManager.getOpState().equals(StateManagement.DISABLED)) {
- String msg = RESOURCE_STRING + resourceName + " operation state is disabled. " + errorMsg;
- logger.debug("{}", msg);
- throw new IntegrityMonitorException(msg);
- }
-
- // check admin state and throw exception if locked
- if ((stateManager.getAdminState() != null) && stateManager.getAdminState().equals(StateManagement.LOCKED)) {
- String msg = RESOURCE_STRING + resourceName + " is administratively locked";
- logger.debug("{}", msg);
- throw new AdministrativeStateException("IntegrityMonitor Admin State Exception: " + msg);
- }
- // check standby state and throw exception if cold standby
- if ((stateManager.getStandbyStatus() != null)
- && stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
- String msg = RESOURCE_STRING + resourceName + " is cold standby";
- logger.debug("{}", msg);
- throw new StandbyStatusException("IntegrityMonitor Standby Status Exception: " + msg);
- }
-
- }
-
- }
-
- /**
- * This method checks the forward progress counter and the state of a dependency. If the dependency is unavailable
- * or failed, an error message is created which is checked when evaluateSanity interface is called. If the error
- * message is set then the evaluateSanity will return an error.
- *
- * @param dep the dependency
- * @return {@code null} if success, an error message otherwise
- */
- public String stateCheck(String dep) {
- logger.debug("checking state of dependent resource: {}", dep);
- AtomicReference<ForwardProgressEntity> forwardProgressEntity = new AtomicReference<>();
- AtomicReference<StateManagementEntity> stateManagementEntity = new AtomicReference<>();
-
- String errorMsg =
- withinTransaction(dep + ": ForwardProgressEntity DB operation failed with exception: ", () -> {
- TypedQuery<ForwardProgressEntity> query = em.createQuery(
- "Select p from ForwardProgressEntity p where p.resourceName=:resource",
- ForwardProgressEntity.class);
- query.setParameter(LC_RESOURCE_STRING, dep);
-
- List<ForwardProgressEntity> fpList = query.setLockMode(LockModeType.NONE)
- .setFlushMode(FlushModeType.COMMIT).getResultList();
-
- if (!fpList.isEmpty()) {
- // exists
- forwardProgressEntity.set(fpList.get(0));
- // refresh the object from DB in case cached data was
- // returned
- em.refresh(forwardProgressEntity.get());
- logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}",
- dep);
- return null;
-
- } else {
- return dep + ": resource not found in ForwardProgressEntity database table";
- }
- });
-
- if (StringUtils.isEmpty(errorMsg)) {
- errorMsg = withinTransaction(dep + ": StateManagementEntity DB read failed with exception: ", () -> {
-
- // query if StateManagement entry exists for dependent resource
- TypedQuery<StateManagementEntity> query =
- em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
- StateManagementEntity.class);
- query.setParameter(LC_RESOURCE_STRING, dep);
-
- List<StateManagementEntity> smList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!smList.isEmpty()) {
- // exist
- stateManagementEntity.set(smList.get(0));
- // refresh the object from DB in case cached data was
- // returned
- em.refresh(stateManagementEntity.get());
- logger.debug("Found entry in StateManagementEntity table for dependent Resource={}", dep);
- return null;
- } else {
- return dep + ": resource not found in state management entity database table";
- }
- });
- }
-
- // verify that the ForwardProgress is current (check last_updated)
- if (StringUtils.isEmpty(errorMsg)) {
- checkForwardProgress(dep, forwardProgressEntity.get(), stateManagementEntity.get());
- }
-
- // check operation, admin and standby states of dependent resource
- if (StringUtils.isEmpty(errorMsg)) {
- errorMsg = checkDependentStates(dep, stateManagementEntity.get());
- }
-
- String returnMsg = "IntegrityMonitor.stateCheck(): returned error_msg: " + errorMsg;
- logger.debug("{}", returnMsg);
- return errorMsg;
- }
-
- /**
- * Runs an action within a transaction.
- *
- * @param exMsg message to log and return if an exception occurs
- * @param action action to apply; returns non-null if an error occurs
- * @return {@code null} if success, or an error message otherwise
- */
- private String withinTransaction(String exMsg, Supplier<String> action) {
- // Start a transaction
- EntityTransaction et = em.getTransaction();
- et.begin();
-
- try {
- var errorMsg = action.get();
- logger.error("{}", errorMsg);
- synchronized (imFlushLock) {
- et.commit();
- }
- return errorMsg;
- } catch (RuntimeException ex) {
- // log an error
- logger.error("{}", exMsg, ex);
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
- }
- return exMsg;
- }
- }
-
- private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity,
- StateManagementEntity stateManagementEntity) {
- if (forwardProgressEntity != null && stateManagementEntity != null) {
- var date = MonitorTime.getInstance().getDate();
- long diffMs = date.getTime() - forwardProgressEntity.getLastUpdated().getTime();
- logger.debug("IntegrityMonitor.stateCheck(): diffMs = {}", diffMs);
-
- // Threshold for a stale entry
- long staleMs = maxFpcUpdateIntervalMs;
- logger.debug("IntegrityMonitor.stateCheck(): staleMs = {}", staleMs);
-
- if (diffMs > staleMs) {
- // ForwardProgress is stale. Disable it
- disableEntity(dep, stateManagementEntity);
- }
- } else {
-
- String msg;
- if (forwardProgressEntity == null) {
- msg = STATE_CHECK_STRING + dep + "; " + " forwardProgressEntity == null.";
- } else {
- msg = STATE_CHECK_STRING + dep + "; " + " stateManagementEntity == null.";
- }
- logger.error("{}", msg);
- }
- }
-
- private String checkDependentStates(String dep, StateManagementEntity stateManagementEntity) {
- String errorMsg = null;
-
- if (stateManagementEntity != null) {
- if ((stateManager.getAdminState() != null)
- && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) {
- errorMsg = dep + ": resource is administratively locked";
- logger.error("{}", errorMsg);
- } else if ((stateManager.getOpState() != null)
- && stateManagementEntity.getOpState().equals(StateManagement.DISABLED)) {
- errorMsg = dep + ": resource is operationally disabled";
- logger.error("{}", errorMsg);
- } else if ((stateManager.getStandbyStatus() != null)
- && stateManagementEntity.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
- errorMsg = dep + ": resource is cold standby";
- logger.error("{}", errorMsg);
- }
- } else {
- errorMsg = dep + ": could not check standy state of resource. stateManagementEntity == null.";
- logger.error("{}", errorMsg);
- }
-
- return errorMsg;
- }
-
- private String fpCheck(String dep) {
- logger.debug("checking forward progress count of dependent resource: {}", dep);
-
- return withinTransaction(dep + ": ForwardProgressEntity DB read failed with exception: ", () -> fpCheck2(dep));
- }
-
- private String fpCheck2(String dep) {
- TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
- fquery.setParameter("rn", dep);
-
- List<ForwardProgressEntity> fpList =
- fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ForwardProgressEntity fpx;
- if (!fpList.isEmpty()) {
- // ignores multiple results
- fpx = fpList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(fpx);
- if (logger.isDebugEnabled()) {
- logger.debug("Dependent resource {} - fpc= {}, lastUpdated={}", dep, fpx.getFpcCount(),
- fpx.getLastUpdated());
- }
- long currTime = MonitorTime.getInstance().getMillis();
- // if dependent resource FPC has not been updated, consider it
- // an error
- if ((currTime - fpx.getLastUpdated().getTime()) > maxFpcUpdateIntervalMs) {
- disableEntity(dep);
- return dep + ": FP count has not been updated in the last " + maxFpcUpdateIntervalMs + "ms";
- }
-
- return null;
-
- } else {
- // resource entry not found in FPC table
- return dep + ": resource not found in ForwardProgressEntity table in the DB";
- }
- }
-
- /**
- * Get all forward progress entities.
- *
- * @return list of all forward progress entities
- */
- @SuppressWarnings("unchecked")
- public List<ForwardProgressEntity> getAllForwardProgressEntity() {
- logger.debug("getAllForwardProgressEntity: entry");
-
- ArrayList<ForwardProgressEntity> fpList = new ArrayList<>();
-
- withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> {
- var fquery = em.createQuery("Select e from ForwardProgressEntity e");
- fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList()
- .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
- return null;
- });
-
- if (!logger.isDebugEnabled()) {
- return fpList;
- }
-
- logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size());
- var index = 0;
- for (ForwardProgressEntity fpe : fpList) {
- logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++,
- fpe.getResourceName());
- }
-
- return fpList;
- }
-
- private String jmxCheck(String dep) {
- logger.debug("checking health of dependent by calling test() via JMX on resource: {}", dep);
-
- // get the JMX URL from the database
- AtomicReference<String> jmxUrl = new AtomicReference<>();
-
- String errorMsg = withinTransaction(dep + ": ResourceRegistrationEntity DB read failed with exception: ",
- () -> getJmxUrlFromDb(dep, jmxUrl));
-
- if (jmxUrl.get() != null) {
- errorMsg = jmxCheck2(dep, jmxUrl.get(), errorMsg);
- }
-
- return errorMsg;
- }
-
- private String getJmxUrlFromDb(String dep, AtomicReference<String> jmxUrl) {
- // query if ResourceRegistration entry exists for resourceName
- TypedQuery<ResourceRegistrationEntity> rquery =
- em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn",
- ResourceRegistrationEntity.class);
- rquery.setParameter("rn", dep);
-
- List<ResourceRegistrationEntity> rrList =
- rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ResourceRegistrationEntity rrx;
-
- if (!rrList.isEmpty()) {
- // ignores multiple results
- rrx = rrList.get(0);
- // refresh the object from DB in case cached data was
- // returned
- em.refresh(rrx);
- jmxUrl.set(rrx.getResourceUrl());
- if (logger.isDebugEnabled()) {
- logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(), rrx.getCreatedDate());
- }
-
- return null;
-
- } else {
- return dep + ": resource not found in ResourceRegistrationEntity table in the DB";
- }
- }
-
- private String jmxCheck2(String dep, String jmxUrl, String errorMsg) {
- JmxAgentConnection jmxAgentConnection = null;
- try {
- jmxAgentConnection = new JmxAgentConnection(jmxUrl);
- MBeanServerConnection mbeanServer = jmxAgentConnection.getMBeanConnection();
- ComponentAdminMBean admin =
- JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
-
- // invoke the test method via the jmx proxy
- admin.test();
- logger.debug("Dependent resource {} sanity test passed", dep);
- } catch (Exception e) {
- String errorMsg2 = dep + ": resource sanity test failed with exception: ";
- logger.error("{}", errorMsg2, e);
- return errorMsg2;
- } finally {
- // close the JMX connector
- if (jmxAgentConnection != null) {
- jmxAgentConnection.disconnect();
- }
- }
- return errorMsg;
- }
-
- /**
- * Perform a dependency check.
- *
- * @return an error message detailing any issues found
- */
- public String dependencyCheck() {
- logger.debug("dependencyCheck: entry");
- synchronized (dependencyCheckLock) {
-
- // Start with the error message empty
- var errorMsg = new StringBuilder();
-
- /*
- * Before we check dependency groups we need to check subsystemTest.
- */
- boolean dependencyOk = checkSubsystems(errorMsg);
-
- // Check the sanity of dependents for lead subcomponents
- if (depGroups != null && depGroups.length > 0) {
- dependencyOk = checkDependencies(errorMsg) && dependencyOk;
-
- /*
- * We have checked all the dependency groups. If all are ok and subsystemTest passed, dependencyFailure
- * == false
- */
- if (dependencyOk) {
- dependenciesGood(errorMsg);
- }
- } else if (dependencyOk) {
- /*
- * This is put here to clean up when no dependency group should exist, but one was erroneously added
- * which caused the state to be disabled/dependency/coldstandby and later removed. We saw this happen in
- * the lab, but is not very likely in a production environment...but you never know.
- */
- noDependencyGroups(errorMsg);
- }
-
- dependencyCheckErrorMsg = errorMsg.toString();
- lastDependencyCheckTime = MonitorTime.getInstance().getMillis();
-
- if (!dependencyCheckErrorMsg.isEmpty()) {
- logger.error("Sanity failure detected in a dependent resource: {}", errorMsg);
-
- }
-
- logger.debug("dependencyCheck: exit");
- return dependencyCheckErrorMsg;
- }
- }
-
- /**
- * Checks the subsystems.
- *
- * @param errorMsg error messages are appended to this
- * @return {@code true} if the test succeeds, {@code false} otherwise
- */
- private boolean checkSubsystems(StringBuilder errorMsg) {
- try {
- // Test any subsystems that are not covered under the dependency
- // relationship
- subsystemTest();
- return true;
-
- } catch (Exception e) {
- logger.error("IntegrityMonitor threw exception", e);
- // This indicates a subsystemTest failure
- try {
- if (logger.isDebugEnabled()) {
- logger.debug("{}: There has been a subsystemTest failure with error:{} Updating this resource's "
- + "state to disableDependency", resourceName, e.getMessage());
- }
- // Capture the subsystemTest failure info
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": ");
- errorMsg.append(e.getMessage());
- this.stateManager.disableDependency();
- } catch (Exception ex) {
- logger.error(EXCEPTION_STRING, ex);
- appendSeparator(errorMsg);
- errorMsg.append('\n');
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to disable dependency after subsystemTest failure due to: ");
- errorMsg.append(ex.getMessage());
- }
-
- return false;
- }
- }
-
- /**
- * Checks the dependencies.
- *
- * @param errorMsg error messages are appended to this
- * @return {@code true} if the dependencies are OK, {@code false} otherwise
- */
- private boolean checkDependencies(StringBuilder errorMsg) {
- var dependencyOk = true;
-
- // check state of resources in dependency groups
- for (String group : depGroups) {
- if (checkDependencyGroupHasError(group, errorMsg)) {
- dependencyOk = false;
- if (!disableDependency(errorMsg, group)) {
- break; // break out on failure and skip checking other groups
- }
- }
- // check the next group
-
- }
-
- return dependencyOk;
- }
-
- /**
- * Checks if a dependency group has an error.
- *
- * @param group group to be checked
- * @param errorMsg error messages are appended here
- * @return {@code true} if the group has an error, {@code false} otherwise
- */
- private boolean checkDependencyGroupHasError(String group, StringBuilder errorMsg) {
- group = group.trim();
- if (group.isEmpty()) {
- // ignore empty group
- return false;
- }
- String[] dependencies = COMMA_PAT.split(group);
- if (logger.isDebugEnabled()) {
- logger.debug("group dependencies = {}", Arrays.toString(dependencies));
- }
- var realDepCount = 0;
- var failDepCount = 0;
- for (String dep : dependencies) {
- dep = dep.trim();
- if (dep.isEmpty()) {
- // ignore empty dependency
- continue;
- }
- realDepCount++; // this is a valid dependency whose state is tracked
- // if a resource is down, its FP count will not be incremented
- String failMsg = doDependencyChecks(dep);
- if (failMsg != null) {
- failDepCount++;
- appendSeparator(errorMsg);
- errorMsg.append(failMsg);
- }
- }
-
- // if all dependencies in a group are failed, set this
- // resource's state to disable dependency
- return (realDepCount > 0) && (failDepCount == realDepCount);
- }
-
- /**
- * Checks a single dependency.
- *
- * @param dep dependency to be checked
- * @return the failure message, or {@code null} if all checks passed
- */
- private String doDependencyChecks(String dep) {
- String failMsg = fpCheck(dep);
-
- if (failMsg == null) {
- if (testViaJmx) {
- failMsg = jmxCheck(dep);
- } else {
- failMsg = stateCheck(dep);
- }
- }
-
- return failMsg;
- }
-
- /**
- * Disables the dependency group.
- *
- * @param errorMsg error messages are appended to this
- * @param group group of interest
- * @return {@code true} if it was successfully disabled, {@code false} otherwise
- */
- private boolean disableDependency(StringBuilder errorMsg, String group) {
- try {
- logger.debug("All dependents in group {} have failed their health check. Updating this "
- + "resource's state to disableDependency", group);
- if (stateManager.getAvailStatus() == null
- || !((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
- || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
- // Note: redundant calls are made by
- // refreshStateAudit
- this.stateManager.disableDependency();
- }
-
- return true;
-
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to disable dependency");
- return false;
- }
- }
-
- private void dependenciesGood(StringBuilder errorMsg) {
- try {
- logger.debug("All dependency groups have at least one viable member. Updating this resource's state"
- + " to enableNoDependency");
- if (stateManager.getAvailStatus() != null
- && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
- || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
- // Note: redundant calls are made by
- // refreshStateAudit
- this.stateManager.enableNoDependency();
- }
- // The refreshStateAudit will catch the case where it is disabled but
- // availStatus != failed
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to enable no dependency");
- }
- }
-
- private void noDependencyGroups(StringBuilder errorMsg) {
- try {
- logger.debug("There are no dependents. Updating this resource's state to enableNoDependency");
- if (stateManager.getAvailStatus() != null
- && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
- || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
- // Note: redundant calls are made by refreshStateAudit
- this.stateManager.enableNoDependency();
- }
- // The refreshStateAudit will catch the case where it is disabled but
- // availStatus != failed
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to enable no dependency");
- }
- }
-
- private void appendSeparator(StringBuilder errorMsg) {
- if (!errorMsg.isEmpty()) {
- errorMsg.append(',');
- }
- }
-
- /**
- * Execute a test transaction. It is called when the test transaction timer fires. It could be overridden to provide
- * additional test functionality. If overridden, the overriding method must invoke startTransaction() and
- * endTransaction() and check if the allNotWellMap is empty.
- */
- public void testTransaction() {
- synchronized (testTransactionLock) {
- logger.debug("testTransaction: entry");
- //
- // startTransaction() not required for testTransaction
- //
-
- // end transaction - increments local FP counter
- endTransaction();
- }
- }
-
- /**
- * Additional testing for subsystems that do not have a /test interface (for ex. 3rd party processes like elk). This
- * method would be overridden by the subsystem.
- *
- */
- public void subsystemTest() {
- // Testing provided by subsystem
- logger.debug("IntegrityMonitor subsystemTest() OK");
- }
-
- /**
- * Checks admin state and resets transaction timer. Called by application at the start of a transaction.
- *
- * @throws IntegrityMonitorException if resource is locked or in standby
- */
- public void startTransaction() throws IntegrityMonitorException {
-
- synchronized (startTransactionLock) {
- // check admin state and throw exception if locked
- if ((stateManager.getAdminState() != null) && stateManager.getAdminState().equals(StateManagement.LOCKED)) {
- String msg = RESOURCE_STRING + resourceName + " is administratively locked";
-
- throw new AdministrativeStateException("IntegrityMonitor Admin State Exception: " + msg);
- }
- // check standby state and throw exception if locked
-
- if ((stateManager.getStandbyStatus() != null)
- && (stateManager.getStandbyStatus().equals(StateManagement.HOT_STANDBY)
- || stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY))) {
- String msg = RESOURCE_STRING + resourceName + " is standby";
-
- throw new StandbyStatusException("IntegrityMonitor Standby Status Exception: " + msg);
- }
-
- // reset transactionTimer so it will not fire
- elapsedTestTransTime = 0;
- }
- }
-
- /**
- * Increment the local forward progress counter. Called by application at the end of each transaction (successful or
- * not).
- */
- public void endTransaction() {
- synchronized (endTransactionLock) {
- if (getAllNotWellMap() != null) {
- if (!(getAllNotWellMap().isEmpty())) {
- /*
- * An entity has reported that it is not well. We must not allow the forward progress counter to
- * advance.
- */
- var msg = new StringBuilder("allNotWellMap:");
- buildMapString(msg, allNotWellMap);
- logger.error(
- """
- endTransaction: allNotWellMap is NOT EMPTY. Not advancing forward progress counter.
- {}
- """, msg);
- return;
- }
-
- if (logger.isDebugEnabled() && getAllSeemsWellMap() != null && !(getAllSeemsWellMap().isEmpty())) {
- var msg = new StringBuilder("allSeemsWellMap:");
- buildMapString(msg, allSeemsWellMap);
- logger.debug(
- """
- endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY.
- Advancing forward progress counter.
- {}
- """, msg);
- }
- }
- // increment local FPC
- fpCounter++;
- }
- }
-
- private void buildMapString(StringBuilder msg, Map<String, String> map) {
- for (Entry<String, String> entry : map.entrySet()) {
- msg.append("\nkey = ");
- msg.append(entry.getKey());
- msg.append(" msg = ");
- msg.append(entry.getValue());
- }
- }
-
- // update FP count in DB with local FP count
- private void writeFpc() throws IntegrityMonitorException {
-
- // Start a transaction
- EntityTransaction et = em.getTransaction();
-
- if (!et.isActive()) {
- et.begin();
- }
-
- try {
- // query if ForwardProgress entry exists for resourceName
- TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
- fquery.setParameter("rn", resourceName);
-
- List<ForwardProgressEntity> fpList =
- fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ForwardProgressEntity fpx;
- if (!fpList.isEmpty()) {
- // ignores multiple results
- fpx = fpList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(fpx);
- if (logger.isDebugEnabled()) {
- logger.debug("Updating FP entry: Resource={}, fpcCount={}, lastUpdated={}, new fpcCount={}",
- resourceName, fpx.getFpcCount(), fpx.getLastUpdated(), fpCounter);
- }
- fpx.setFpcCount(fpCounter);
- em.persist(fpx);
- // flush to the DB and commit
- synchronized (imFlushLock) {
- et.commit();
- }
- } else {
- // Error - FP entry does not exist
- String msg = "FP entry not found in database for resource " + resourceName;
- throw new IntegrityMonitorException(msg);
- }
- } catch (Exception e) {
- try {
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
- }
- } catch (Exception e1) {
- logger.error(EXCEPTION_STRING, e1);
- }
- logger.error("writeFpc DB table commit failed with exception");
- throw e;
- }
- }
-
- /**
- * Read and validate properties.
- *
- * @throws IntegrityMonitorPropertiesException if a property is invalid
- */
- private static void validateProperties(Properties prop) throws IntegrityMonitorPropertiesException {
-
- checkNonNull(prop, IntegrityMonitorProperties.DB_DRIVER);
- checkNonNull(prop, IntegrityMonitorProperties.DB_URL);
- checkNonNull(prop, IntegrityMonitorProperties.DB_USER);
- checkNonNull(prop, IntegrityMonitorProperties.DB_PWD);
-
- setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL, value -> monitorIntervalMs = toMillis(value));
-
- setInt(prop, value -> failedCounterThreshold = value);
-
- setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL, value -> testTransIntervalMs = toMillis(value));
-
- setLong(prop, IntegrityMonitorProperties.WRITE_FPC_INTERVAL, value -> writeFpcIntervalMs = toMillis(value));
-
- setLong(prop, IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL,
- value -> checkDependencyIntervalMs = toMillis(value));
-
- // dependency_groups are a semicolon separated list of groups
- // each group is a comma separated list of resource names
- // For ex. dependency_groups = site_1.pap_1,site_1.pap_2 ; site_1.pdp_1,
- // site_1.pdp_2
- String depGroupsValue = prop.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS);
- if (!StringUtils.isBlank(depGroupsValue)) {
- depGroups = SEMICOLON_PAT.split(depGroupsValue);
- if (logger.isDebugEnabled()) {
- logger.debug("dependency groups property = {}", Arrays.toString(depGroups));
- }
- }
-
- siteName = checkNonNull(prop, IntegrityMonitorProperties.SITE_NAME);
-
- nodeType = checkNonNull(prop, IntegrityMonitorProperties.NODE_TYPE);
- if (!isNodeTypeEnum(nodeType)) {
- String msg = IntegrityMonitorProperties.NODE_TYPE + " property " + nodeType + " is invalid";
- logger.error("{}", msg);
- throw new IntegrityMonitorPropertiesException(PROPERTY_EXCEPTION_STRING + msg);
- }
-
- setBoolean(prop, IntegrityMonitorProperties.TEST_VIA_JMX, value -> testViaJmx = value);
-
- String jmxFqdnValue = prop.getProperty(IntegrityMonitorProperties.JMX_FQDN);
- jmxFqdn = StringUtils.isBlank(jmxFqdnValue) ? null : jmxFqdnValue.trim();
-
- setLong(prop, IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL,
- value -> maxFpcUpdateIntervalMs = toMillis(value));
-
- setLong(prop, IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, value -> stateAuditIntervalMs = value);
-
- setLong(prop, IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS,
- value -> refreshStateAuditIntervalMs = value);
-
- logger.debug("IntegrityMonitor.validateProperties(): Property values \nmaxFpcUpdateIntervalMs = {}\n",
- maxFpcUpdateIntervalMs);
- }
-
- private static void setBoolean(Properties props, String propName, Consumer<Boolean> setter) {
- String propValue = props.getProperty(propName);
- if (propValue != null) {
- setter.accept(Boolean.parseBoolean(propValue.trim()));
- }
- }
-
- private static String checkNonNull(Properties props, String propName) throws IntegrityMonitorPropertiesException {
-
- String propValue = props.getProperty(propName);
- if (propValue == null) {
- String msg = propName + NULL_PROPERTY_STRING;
- logger.error("{}", msg);
- throw new IntegrityMonitorPropertiesException(PROPERTY_EXCEPTION_STRING + msg);
- }
-
- return propValue.trim();
- }
-
- private static void setInt(Properties props, IntConsumer setter) {
- String propValue = props.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD);
- if (StringUtils.isBlank(propValue)) {
- return;
- }
-
- try {
- setter.accept(Integer.parseInt(propValue.trim()));
- } catch (NumberFormatException e) {
- logger.warn(IGNORE_INVALID_PROPERTY_STRING, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, e);
- }
- }
-
- private static void setLong(Properties props, String propName, LongConsumer setter) {
- String propValue = props.getProperty(propName);
- if (StringUtils.isBlank(propValue)) {
- return;
- }
-
- try {
- setter.accept(Long.parseLong(propValue.trim()));
- } catch (NumberFormatException e) {
- logger.warn(IGNORE_INVALID_PROPERTY_STRING, propName, e);
- }
- }
-
- /**
- * Update properties.
- *
- * @param newprop the new properties
- */
- public static void updateProperties(Properties newprop) {
- if (isUnitTesting()) {
- try {
- validateProperties(newprop);
- } catch (IntegrityMonitorPropertiesException e) {
- logger.error(EXCEPTION_STRING, e);
- }
- } else {
- logger.debug("Update integrity monitor properties not allowed");
- }
- }
-
- private static boolean isNodeTypeEnum(String nodeType) {
- String upper = nodeType.toUpperCase();
- for (NodeType n : NodeType.values()) {
- if (n.toString().equals(upper)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Look for "Forward Progress" -- if the 'FPMonitor' is stalled for too long, the operational state is changed to
- * 'Disabled', and an alarm is set. The state is restored when forward progress continues.
- */
- private void fpMonitorCycle() {
- logger.debug("fpMonitorCycle(): entry");
- synchronized (fpMonitorCycleLock) {
- // monitoring interval checks
- if (monitorIntervalMs <= 0) {
- logger.debug("fpMonitorCycle(): disabled");
- elapsedTime = 0;
- return; // monitoring is disabled
- }
-
- elapsedTime = elapsedTime + CYCLE_INTERVAL_MILLIS;
- if (elapsedTime < monitorIntervalMs) {
- return; // monitoring interval not reached
- }
-
- elapsedTime = 0; // reset elapsed time
-
- try {
- if (fpCounter == lastFpCounter) {
- // no forward progress
- noForwardProgress();
- } else {
- // forward progress has occurred
- forwardProgress();
- }
- } catch (Exception e) {
- // log error
- logger.error("FP Monitor encountered error. ", e);
- }
- }
- logger.debug("fpMonitorCycle(): exit");
- }
-
- private void noForwardProgress() throws StateManagementException {
- missedCycles += 1;
- if (missedCycles >= failedCounterThreshold && !alarmExists) {
- logger.debug("Forward progress not detected for resource {}. Setting state to disable failed.",
- resourceName);
- if (!(stateManager.getOpState()).equals(StateManagement.DISABLED)) {
- // Note: The refreshStateAudit will make redundant
- // calls
- stateManager.disableFailed();
- }
- // The refreshStateAudit will catch the case where opStat = disabled and
- // availState ! failed/dependency.failed
- alarmExists = true;
- }
- }
-
- private void forwardProgress() throws StateManagementException {
- lastFpCounter = fpCounter;
- missedCycles = 0;
- // set op state to enabled
- logger.debug("Forward progress detected for resource {}. Setting state to enable not failed.", resourceName);
- if (!(stateManager.getOpState()).equals(StateManagement.ENABLED)) {
- // Note: The refreshStateAudit will make redundant calls
- stateManager.enableNotFailed();
- }
- // The refreshStateAudit will catch the case where opState=enabled and
- // availStatus != null
- alarmExists = false;
- }
-
- /**
- * Look for "Forward Progress" on other nodes. If they are not making forward progress, check their operational
- * state. If it is not disabled, then disable them.
- */
- private void stateAudit() {
- logger.debug("IntegrityMonitor.stateAudit(): entry");
- if (stateAuditIntervalMs <= 0) {
- logger.debug("IntegrityMonitor.stateAudit(): disabled");
- return; // stateAudit is disabled
- }
-
- // Only run from nodes that are operational
- if (stateManager.getOpState().equals(StateManagement.DISABLED)) {
- logger.debug("IntegrityMonitor.stateAudit(): DISABLED. returning");
- return;
- }
- if (stateManager.getAdminState().equals(StateManagement.LOCKED)) {
- logger.debug("IntegrityMonitor.stateAudit(): LOCKED. returning");
- return;
- }
- if (!stateManager.getStandbyStatus().equals(StateManagement.NULL_VALUE)
- && stateManager.getStandbyStatus() != null
- && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) {
- logger.debug("IntegrityMonitor.stateAudit(): NOT PROVIDING_SERVICE. returning");
- return;
- }
-
- var date = MonitorTime.getInstance().getDate();
- long timeSinceLastStateAudit = date.getTime() - lastStateAuditTime.getTime();
- if (timeSinceLastStateAudit < stateAuditIntervalMs) {
- logger.debug("IntegrityMonitor.stateAudit(): Not time to run. returning");
- return;
- }
-
- executeStateAudit();
-
- lastStateAuditTime = date;
-
- logger.debug("IntegrityMonitor.stateAudit(): exit");
- }
-
- /**
- * Execute state audit.
- */
- public void executeStateAudit() {
- logger.debug("IntegrityMonitor.executeStateAudit(): entry");
- var date = MonitorTime.getInstance().getDate();
-
- // Get all entries in the forwardprogressentity table
- List<ForwardProgressEntity> fpList = getAllForwardProgressEntity();
-
- // Check if each forwardprogressentity entry is current
- for (ForwardProgressEntity fpe : fpList) {
- // If this is my ForwardProgressEntity, continue
- if (fpe.getResourceName().equals(IntegrityMonitor.resourceName)) {
- continue;
- }
- // Make sure you are not getting a cached version
- em.refresh(fpe);
- long diffMs = date.getTime() - fpe.getLastUpdated().getTime();
- if (logger.isDebugEnabled()) {
- logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, diffMs = {}", fpe.getResourceName(),
- diffMs);
- }
-
- // Threshold for a stale entry
- long staleMs = maxFpcUpdateIntervalMs;
- if (logger.isDebugEnabled()) {
- logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, staleMs = {}", fpe.getResourceName(),
- staleMs);
- }
-
- if (diffMs > staleMs) {
- // ForwardProgress is stale. Disable it
- // Start a transaction
- logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, FPC is stale. Disabling it",
- fpe.getResourceName());
- EntityTransaction et = em.getTransaction();
- et.begin();
- StateManagementEntity sme = disableEntity(et, fpe);
-
- if (sme != null && !sme.getOpState().equals(StateManagement.DISABLED)) {
- disableFailed(sme);
- }
- }
- }
- logger.debug("IntegrityMonitor.executeStateAudit(): exit");
- }
-
- /**
- * Disables the entity.
- *
- * @param entrans entity transaction
- * @param fpe entity of interest
- * @return the corresponding state management entity
- */
- private StateManagementEntity disableEntity(EntityTransaction entrans, ForwardProgressEntity fpe) {
- StateManagementEntity sme = null;
-
- try {
- // query if StateManagement entry exists for fpe resource
- TypedQuery<StateManagementEntity> query =
- em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
- StateManagementEntity.class);
- query.setParameter(LC_RESOURCE_STRING, fpe.getResourceName());
-
- List<StateManagementEntity> smList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!smList.isEmpty()) {
- // exists
- sme = smList.get(0);
- // refresh the object from DB in case cached data was
- // returned
- em.refresh(sme);
- if (logger.isDebugEnabled()) {
- logger.debug("IntegrityMonitor.executeStateAudit(): Found entry in StateManagementEntity table "
- + "for Resource={}", sme.getResourceName());
- }
- } else {
- String msg = "IntegrityMonitor.executeStateAudit(): " + fpe.getResourceName()
- + ": resource not found in state management entity database table";
- logger.error("{}", msg);
- }
- synchronized (imFlushLock) {
- entrans.commit();
- }
- } catch (Exception e) {
- // log an error
- logger.error("IntegrityMonitor.executeStateAudit(): {}: StateManagementEntity DB read failed with "
- + "exception: ", fpe.getResourceName(), e);
- synchronized (imFlushLock) {
- if (entrans.isActive()) {
- entrans.rollback();
- }
- }
- }
-
- return sme;
- }
-
- private void disableEntity(String dep, StateManagementEntity sme) {
- try {
- if (!sme.getOpState().equals(StateManagement.DISABLED)) {
- logger.debug("IntegrityMonitor.stateCheck(): Changing OpStat = disabled for {}", dep);
- stateManager.disableFailed(dep);
- }
- } catch (Exception e) {
- String msg = STATE_CHECK_STRING + dep + "; " + e.getMessage();
- logger.error("{}", msg, e);
- }
- }
-
- private void disableEntity(String dep) {
- try {
- // create instance of StateManagement class for dependent
- var depStateManager = new StateManagement(emf, dep);
- if (!depStateManager.getOpState().equals(StateManagement.DISABLED)) {
- logger.debug("Forward progress not detected for dependent resource {}. Setting dependent's "
- + "state to disable failed.", dep);
- depStateManager.disableFailed();
- }
- } catch (Exception e) {
- // ignore errors
- logger.error("Update dependent state failed with exception: ", e);
- }
- }
-
- /**
- * Indicates a failure to disable an entity.
- *
- * @param sme entity of interest
- */
- private void disableFailed(StateManagementEntity sme) {
- if (logger.isDebugEnabled()) {
- logger.debug("IntegrityMonitor.executeStateAudit(): Changing OpStat = disabled for {}",
- sme.getResourceName());
- }
- try {
- stateManager.disableFailed(sme.getResourceName());
- } catch (Exception e) {
- String msg = "IntegrityMonitor.executeStateAudit(): Failed to disable " + sme.getResourceName();
- logger.error("{}", msg, e);
- }
- }
-
- /**
- * Execute a test transaction when test transaction interval has elapsed.
- */
- private void checkTestTransaction() {
- logger.debug("checkTestTransaction(): entry");
- synchronized (checkTestTransactionLock) {
-
- // test transaction timer checks
- if (testTransIntervalMs <= 0) {
- logger.debug("checkTestTransaction(): disabled");
- elapsedTestTransTime = 0;
- return; // test transaction is disabled
- }
-
- elapsedTestTransTime = elapsedTestTransTime + CYCLE_INTERVAL_MILLIS;
- if (elapsedTestTransTime < testTransIntervalMs) {
- return; // test transaction interval not reached
- }
-
- elapsedTestTransTime = 0; // reset elapsed time
-
- // execute test transaction
- testTransaction();
- }
- logger.debug("checkTestTransaction(): exit");
- }
-
- /**
- * Updates Fpc counter in database when write Fpc interval has elapsed.
- */
- private void checkWriteFpc() {
- logger.debug("checkWriteFpc(): entry");
- synchronized (checkWriteFpcLock) {
-
- // test transaction timer checks
- if (writeFpcIntervalMs <= 0) {
- logger.debug("checkWriteFpc(): disabled");
- elapsedWriteFpcTime = 0;
- return; // write Fpc is disabled
- }
-
- elapsedWriteFpcTime = elapsedWriteFpcTime + CYCLE_INTERVAL_MILLIS;
- if (elapsedWriteFpcTime < writeFpcIntervalMs) {
- return; // write Fpc interval not reached
- }
-
- elapsedWriteFpcTime = 0; // reset elapsed time
-
- // write Fpc to database
- try {
- writeFpc();
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- }
- }
- logger.debug("checkWriteFpc(): exit");
- }
-
- /**
- * Execute a dependency health check periodically which also updates this resource's state.
- */
- private void checkDependentHealth() {
- logger.debug("checkDependentHealth: entry");
- if (checkDependencyIntervalMs <= 0) {
- logger.debug("checkDependentHealth: disabled");
- return; // dependency monitoring is disabled
- }
-
- long currTime = MonitorTime.getInstance().getMillis();
- logger.debug("checkDependentHealth currTime - lastDependencyCheckTime = {}",
- currTime - lastDependencyCheckTime);
- if ((currTime - lastDependencyCheckTime) > checkDependencyIntervalMs) {
- // execute dependency check and update this resource's state
-
- dependencyCheck();
- }
- logger.debug("checkDependentHealth: exit");
- }
-
- /*
- * This is a simple refresh audit which is periodically run to assure that the states and status attributes are
- * aligned and notifications are sent to any listeners. It is possible for state/status to get out of sync and
- * notified systems to be out of sync due to database corruption (manual or otherwise) or because a node became
- * isolated.
- *
- * When the operation (lock/unlock) is called, it will cause a re-evaluation of the state and send a notification to
- * all registered observers.
- */
- private void refreshStateAudit() {
- logger.debug("refreshStateAudit(): entry");
- if (refreshStateAuditIntervalMs <= 0) {
- // The audit is disabled
- logger.debug("refreshStateAudit(): disabled");
- return;
- }
- executeRefreshStateAudit();
- logger.debug("refreshStateAudit(): exit");
- }
-
- /**
- * Execute refresh state audit.
- */
- public void executeRefreshStateAudit() {
- logger.debug("executeRefreshStateAudit(): entry");
- synchronized (refreshStateAuditLock) {
- logger.debug("refreshStateAudit: entry");
- var now = MonitorTime.getInstance().getDate();
- long nowMs = now.getTime();
- long lastTimeMs = refreshStateAuditLastRunDate.getTime();
- logger.debug("refreshStateAudit: ms since last run = {}", nowMs - lastTimeMs);
-
- if ((nowMs - lastTimeMs) > refreshStateAuditIntervalMs) {
- String adminState = stateManager.getAdminState();
- logger.debug("refreshStateAudit: adminState = {}", adminState);
- if (adminState.equals(StateManagement.LOCKED)) {
- try {
- logger.debug("refreshStateAudit: calling lock()");
- stateManager.lock();
- } catch (Exception e) {
- logger.error("refreshStateAudit: caught unexpected exception from stateManager.lock(): ", e);
- }
- } else { // unlocked
- try {
- logger.debug("refreshStateAudit: calling unlock()");
- stateManager.unlock();
- } catch (Exception e) {
- logger.error("refreshStateAudit: caught unexpected exception from stateManager.unlock(): ", e);
- }
- }
- refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate();
- logger.debug("refreshStateAudit: exit");
- }
- }
- logger.debug("executeRefreshStateAudit(): exit");
- }
-
- private void runFpManager() {
- logger.debug("FPManager thread running");
-
- try {
- runStarted();
-
- while (fpManager != null) {
- MonitorTime.getInstance().sleep(CYCLE_INTERVAL_MILLIS);
-
- runOnce();
- monitorCompleted();
- }
-
- } catch (InterruptedException e) {
- logger.debug(EXCEPTION_STRING, e);
- Thread.currentThread().interrupt();
- }
- }
-
- private void runOnce() {
- try {
- logger.debug("FPManager calling fpMonitorCycle()");
- // check forward progress timer
- fpMonitorCycle();
-
- logger.debug("FPManager calling checkTestTransaction()");
- // check test transaction timer
- checkTestTransaction();
-
- logger.debug("FPManager calling checkWriteFpc()");
- // check write Fpc timer
- checkWriteFpc();
-
- logger.debug("FPManager calling checkDependentHealth()");
- // check dependency health
- checkDependentHealth();
-
- logger.debug("FPManager calling refreshStateAudit()");
- // check if it is time to run the refreshStateAudit
- refreshStateAudit();
-
- logger.debug("FPManager calling stateAudit()");
- // check if it is time to run the stateAudit
- stateAudit();
-
- } catch (Exception e) {
- logger.error("Ignore FPManager thread processing timer(s) exception: ", e);
- }
- }
-
- /**
- * Set all seems well or not well for the specified key.
- *
- * @param key the key
- * @param asw <code>true</code> if all seems well for the key, <code>false</code> if all seems not well for the key
- * @param msg message to add for the key
- */
- public void allSeemsWell(String key, Boolean asw, String msg) {
-
- logger.debug("allSeemsWell entry: key = {}, asw = {}, msg = {}", key, asw, msg);
- if (StringUtils.isEmpty(key)) {
- logger.error("allSeemsWell: 'key' has no visible content");
- throw new IllegalArgumentException("allSeemsWell: 'key' has no visible content");
- }
- if (asw == null) {
- logger.error("allSeemsWell: 'asw' is null");
- throw new IllegalArgumentException("allSeemsWell: 'asw' is null");
- }
- if (StringUtils.isEmpty(msg)) {
- logger.error("allSeemsWell: 'msg' has no visible content");
- throw new IllegalArgumentException("allSeemsWell: 'msg' has no visible content");
- }
-
- if (allSeemsWellMap == null) {
- allSeemsWellMap = new HashMap<>();
- }
-
- if (allNotWellMap == null) {
- allNotWellMap = new HashMap<>();
- }
-
- if (Boolean.TRUE.equals(asw)) {
- logger.info("allSeemsWell: ALL SEEMS WELL: key = {}, msg = {}", key, msg);
- allSeemsWellMap.put(key, msg);
- allNotWellMap.remove(key);
-
- } else {
- logger.error("allSeemsWell: ALL NOT WELL: key = {}, msg = {}", key, msg);
- allSeemsWellMap.remove(key);
- allNotWellMap.put(key, msg);
- }
-
- if (logger.isDebugEnabled()) {
- for (Entry<String, String> entry : allSeemsWellMap.entrySet()) {
- logger.debug("allSeemsWellMap: key = {} msg = {}", entry.getKey(), entry.getValue());
- }
- for (Entry<String, String> entry : allNotWellMap.entrySet()) {
- logger.debug("allNotWellMap: key = {} msg = {}", entry.getKey(), entry.getValue());
- }
- logger.debug("allSeemsWell exit");
- }
- }
-
- /**
- * Converts the given value to milliseconds using the current propertyUnits.
- *
- * @param value value to be converted, or -1
- * @return the value, in milliseconds, or -1
- */
- private static long toMillis(long value) {
- return (value < 0 ? -1 : value * 1000L);
- }
-
- // these methods may be overridden by junit tests
-
- /**
- * Indicates that the {FpManager#run()} method has started. This method simply returns.
- *
- * @throws InterruptedException can be interrupted
- */
- protected void runStarted() throws InterruptedException {
- // does nothing
- }
-
- /**
- * Indicates that a monitor activity has completed. This method simply returns.
- *
- * @throws InterruptedException can be interrupted
- */
- protected void monitorCompleted() throws InterruptedException {
- // does nothing
- }
-
- /**
- * Get persistence unit.
- *
- * @return the persistence unit to be used
- */
- protected String getPersistenceUnit() {
- return PERSISTENCE_UNIT;
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java
deleted file mode 100644
index 6e1d0c00..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class IntegrityMonitorException extends Exception {
- private static final long serialVersionUID = 1L;
-
- public IntegrityMonitorException() {
- super();
- }
-
- public IntegrityMonitorException(String message) {
- super(message);
- }
-
- public IntegrityMonitorException(Throwable cause) {
- super(cause);
- }
-
- public IntegrityMonitorException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public IntegrityMonitorException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java
deleted file mode 100644
index 6af7a557..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class IntegrityMonitorProperties {
-
- public static final String DB_DRIVER = "jakarta.persistence.jdbc.driver";
- public static final String DB_URL = "jakarta.persistence.jdbc.url";
- public static final String DB_USER = "jakarta.persistence.jdbc.user";
- public static final String DB_PWD = "jakarta.persistence.jdbc.password"; //NOSONAR
-
- // intervals specified are in seconds
- public static final int DEFAULT_MONITOR_INTERVAL = 30;
- public static final int DEFAULT_FAILED_COUNTER_THRESHOLD = 3;
- public static final int DEFAULT_TEST_INTERVAL = 10;
- public static final int DEFAULT_WRITE_FPC_INTERVAL = 5;
- public static final int DEFAULT_MAX_FPC_UPDATE_INTERVAL = 120;
- public static final int DEFAULT_CHECK_DEPENDENCY_INTERVAL = 10;
-
- public static final String FP_MONITOR_INTERVAL = "fp_monitor_interval";
- public static final String FAILED_COUNTER_THRESHOLD = "failed_counter_threshold";
- public static final String TEST_TRANS_INTERVAL = "test_trans_interval";
- public static final String WRITE_FPC_INTERVAL = "write_fpc_interval";
- public static final String CHECK_DEPENDENCY_INTERVAL = "check_dependency_interval";
-
- public static final String DEPENDENCY_GROUPS = "dependency_groups";
- public static final String SITE_NAME = "site_name";
- public static final String NODE_TYPE = "node_type";
-
- public static final String TEST_VIA_JMX = "test_via_jmx";
- public static final String JMX_FQDN = "jmx_fqdn";
- public static final String MAX_FPC_UPDATE_INTERVAL = "max_fpc_update_interval";
- public static final String STATE_AUDIT_INTERVAL_MS = "state_audit_interval_ms";
- public static final String REFRESH_STATE_AUDIT_INTERVAL_MS = "refresh_state_audit_interval_ms";
-
- // AllSeemsWell types
- public static final Boolean ALLNOTWELL = Boolean.FALSE;
- public static final Boolean ALLSEEMSWELL = Boolean.TRUE;
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java
deleted file mode 100644
index d3533f10..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class IntegrityMonitorPropertiesException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public IntegrityMonitorPropertiesException() {
- super();
- }
-
- public IntegrityMonitorPropertiesException(String message) {
- super(message);
- }
-
- public IntegrityMonitorPropertiesException(Throwable cause) {
- super(cause);
- }
-
- public IntegrityMonitorPropertiesException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java
deleted file mode 100644
index 61afb682..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import org.onap.policy.common.utils.time.CurrentTime;
-
-/**
- * "Current" time used by IntegrityMonitor classes.
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class MonitorTime {
-
- /**
- * Instance to be used. This is overridden by junit tests.
- */
- @Getter
- private static CurrentTime instance = new CurrentTime();
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java
deleted file mode 100644
index 352df386..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class StandbyStatusException extends IntegrityMonitorException {
-
- private static final long serialVersionUID = -5262512285108747134L;
-
- public StandbyStatusException() {
- super();
- }
-
- public StandbyStatusException(String message) {
- super(message);
- }
-
- public StandbyStatusException(Throwable cause) {
- super(cause);
- }
-
- public StandbyStatusException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public StandbyStatusException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java
deleted file mode 100644
index 5fc111e0..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import lombok.Getter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-/*
- * This is implementing the Observer interface to make it specific for
- * state management.
- *
- * It saves the StateManagement object and a String message that is
- * passed in when notifyObservers is called by the Observable
- * host class.
- *
- * It provides an abstract method for handling the state change
- * so this class must be overwritten and made concrete for the
- * Observer who is monitoring the state changes.
- */
-
-
-
-/**
- * StateChangeNotifier class implements the Observer pattern and is used to distribute state change
- * notifications to any entity that registers a derived class with an instance of the
- * StateManagement class.
- *
- */
-@Getter
-public class StateChangeNotifier {
- private static final Logger logger = LoggerFactory.getLogger(StateChangeNotifier.class);
- // The observable class
- StateManagement stateManagement;
-
- // A string argument passed by the observable class when
- // StateManagement:notifyObservers(String changed) is called
- String message;
-
- /**
- * Invoked to indicate that something observed by this notifier has changed.
- * @param observable item that has changed
- * @param changed message indicating what change was made
- */
- public void update(StateManagement observable, String changed) {
- this.stateManagement = observable;
- this.message = changed;
- handleStateChange();
- }
-
- /**
- * Handle state change.
- */
- public void handleStateChange() {
- if (logger.isDebugEnabled()) {
- logger.debug("handleStateChange, message: {}", this.message);
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java
deleted file mode 100644
index d1bc9cc1..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Getter
-@Setter
-@NoArgsConstructor
-public class StateElement {
- private static final Logger logger = LoggerFactory.getLogger(StateElement.class);
-
- String adminState = null;
- String opState = null;
- String availStatus = null;
- String standbyStatus = null;
- String actionName = null;
- String endingAdminState = null;
- String endingOpState = null;
- String endingAvailStatus = null;
- String endingStandbyStatus = null;
- String exception = null;
-
- /**
- * Display the state element.
- */
- public void displayStateElement() {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "adminState=[{}], opState=[{}], availStatus=[{}], standbyStatus=[{}], "
- + "actionName=[{}], endingAdminState=[{}], endingOpState=[{}], "
- + "endingAvailStatus=[{}], endingStandbyStatus=[{}], exception=[{}]",
- getAdminState(), getOpState(), getAvailStatus(), getStandbyStatus(), getActionName(),
- getEndingAdminState(), getEndingOpState(), getEndingAvailStatus(), getEndingStandbyStatus(),
- getException());
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java
deleted file mode 100644
index eace6037..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java
+++ /dev/null
@@ -1,551 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.FlushModeType;
-import jakarta.persistence.LockModeType;
-import jakarta.persistence.TypedQuery;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Consumer;
-import org.onap.policy.common.im.exceptions.EntityRetrievalException;
-import org.onap.policy.common.im.jpa.StateManagementEntity;
-import org.onap.policy.common.utils.jpa.EntityMgrCloser;
-import org.onap.policy.common.utils.jpa.EntityTransCloser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * StateManagement class handles all state changes per the Telecom standard X.731. It extends the
- * Observable class and, thus, has an interface to register instances of the
- * StateChangeNotifier/Observer class. When any state change occurs, the registered observers are
- * notified.
- *
- */
-public class StateManagement {
- private static final String RESOURCE_NAME = "resource";
- private static final String GET_STATE_MANAGEMENT_ENTITY_QUERY =
- "Select p from StateManagementEntity p where p.resourceName=:" + RESOURCE_NAME;
- private static final String FIND_MESSAGE = "findStateManagementEntity for {}";
- private static final Logger logger = LoggerFactory.getLogger(StateManagement.class);
- public static final String LOCKED = "locked";
- public static final String UNLOCKED = "unlocked";
- public static final String ENABLED = "enabled";
- public static final String DISABLED = "disabled";
- public static final String ENABLE_NOT_FAILED_ACTION = "enableNotFailed";
- public static final String DISABLE_FAILED_ACTION = "disableFailed";
- public static final String FAILED = "failed";
- public static final String DEPENDENCY = "dependency";
- public static final String DEPENDENCY_FAILED = "dependency,failed";
- public static final String DISABLE_DEPENDENCY_ACTION = "disableDependency";
- public static final String ENABLE_NO_DEPENDENCY_ACTION = "enableNoDependency";
- public static final String NULL_VALUE = "null";
-
- public static final String LOCK_ACTION = "lock";
- public static final String UNLOCK_ACTION = "unlock";
- public static final String PROMOTE_ACTION = "promote";
- public static final String DEMOTE_ACTION = "demote";
- public static final String HOT_STANDBY = "hotstandby";
- public static final String COLD_STANDBY = "coldstandby";
- public static final String PROVIDING_SERVICE = "providingservice";
-
- public static final String ADMIN_STATE = "adminState";
- public static final String OPERATION_STATE = "opState";
- public static final String AVAILABLE_STATUS = "availStatus";
- public static final String STANDBY_STATUS = "standbyStatus";
-
- private String resourceName = null;
- private String adminState = null;
- private String opState = null;
- private String availStatus = null;
- private String standbyStatus = null;
- private final EntityManagerFactory emf;
- private StateTransition st = null;
-
- /*
- * Guarantees single-threadedness of all actions. Only one action can execute at a time. That
- * avoids race conditions between actions being called from different places.
- *
- * Some actions can take significant time to complete and, if another conflicting action is
- * called during its execution, it could put the system in an inconsistent state. This very
- * thing happened when demote was called and the active/standby algorithm, seeing the state
- * attempted to promote the PDP-D.
- *
- */
- private static final Object SYNCLOCK = new Object();
- private static final Object FLUSHLOCK = new Object();
-
- /**
- * Observers to be notified when this object changes state.
- */
- private final Collection<StateChangeNotifier> observers = new ConcurrentLinkedQueue<>();
-
- /**
- * StateManagement constructor.
- *
- * @param entityManagerFactory the entity manager factory
- * @param resourceName the resource name
- * @throws StateManagementException if an error occurs
- */
- public StateManagement(final EntityManagerFactory entityManagerFactory, final String resourceName)
- throws StateManagementException {
- emf = entityManagerFactory;
- logger.debug("StateManagement: constructor, resourceName: {}", resourceName);
-
- this.resourceName = resourceName;
-
- setState("StateManagement", this.resourceName, sm -> null);
-
- // Load the StateTransition hash table
- st = new StateTransition();
- }
-
- /**
- * initializeState() is called when it is necessary to set the StateManagement to a known
- * initial state. It preserves the Administrative State since it must persist across node
- * reboots. Starting from this state, the IntegrityMonitory will determine the Operational State
- * and the owning application will set the StandbyStatus.
- */
- public void initializeState() throws StateManagementException {
- setState("initializeState", this.resourceName, sm -> {
- sm.setAdminState(sm.getAdminState()); // preserve the Admin state
- sm.setOpState(StateManagement.ENABLED);
- sm.setAvailStatus(StateManagement.NULL_VALUE);
- sm.setStandbyStatus(StateManagement.NULL_VALUE);
- return ADMIN_STATE;
- });
- }
-
- /**
- * Sets the management entity state.
- *
- * @param methodName name of the method that invoked this
- * @param resourceName resource name of the desired entity
- * @param updateState function to update the state; returns a string indicating which item
- * was updated, {@code null} if no change was made
- * @throws StateManagementException if an error occurs
- */
- private void setState(String methodName, String resourceName, ExFunction<StateManagementEntity, String> updateState)
- throws StateManagementException {
-
- synchronized (SYNCLOCK) {
- logger.debug("\nStateManagement: SYNCLOCK {}() operation for resourceName = {}\n", methodName,
- resourceName);
- logger.debug("StateManagement: {}() operation started, resourceName = {}", methodName, resourceName);
-
- final var em = emf.createEntityManager();
-
- try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- logger.debug(FIND_MESSAGE, resourceName);
-
- final var sm = findStateManagementEntity(em, resourceName);
- String changed = updateState.update(sm);
-
- em.persist(sm);
- et.commit();
-
- if (changed != null) {
- notifyObservers(changed);
- }
-
- logger.debug("StateManagement: {}() operation completed, resourceName = {}",
- methodName, resourceName);
- } catch (final Exception ex) {
- throw new StateManagementException("StateManagement." + methodName + "() Exception: " + ex);
- }
- }
- }
-
- /**
- * Adds an observer to list of those to be notified when this changes.
- * @param observer observer to be added
- */
- public void addObserver(StateChangeNotifier observer) {
- observers.add(observer);
- }
-
- private void notifyObservers(String changed) {
- for (StateChangeNotifier obs : observers) {
- obs.update(this, changed);
- }
- }
-
- private void setStateUsingTable(String actionName, String resourceName, String changeName)
- throws StateManagementException {
-
- setState(actionName, resourceName, sm -> {
- final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), actionName);
-
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- return changeName;
- });
- }
-
- /**
- * lock() changes the administrative state to locked.
- *
- * @throws StateManagementException if an error occurs
- */
- public void lock() throws StateManagementException {
- setStateUsingTable(LOCK_ACTION, this.resourceName, ADMIN_STATE);
- }
-
- /**
- * unlock() changes the administrative state to unlocked.
- *
- * @throws StateManagementException if an error occurs
- */
- public void unlock() throws StateManagementException {
- setStateUsingTable(UNLOCK_ACTION, this.resourceName, ADMIN_STATE);
- }
-
- /**
- * enableNotFailed() removes the "failed" availability status and changes the operational state
- * to enabled if no dependency is also failed.
- *
- * @throws StateManagementException if an error occurs
- */
- public void enableNotFailed() throws StateManagementException {
- setStateUsingTable(ENABLE_NOT_FAILED_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * disableFailed() changes the operational state to disabled and adds availability status of
- * "failed".
- *
- * @throws StateManagementException if an error occurs
- */
- public void disableFailed() throws StateManagementException {
- setStateUsingTable(DISABLE_FAILED_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * This version of disableFailed is to be used to manipulate the state of a remote resource in
- * the event that remote resource has failed but its state is still showing that it is viable.
- *
- * @throws StateManagementException if an error occurs
- */
- public void disableFailed(final String otherResourceName) throws StateManagementException {
- if (otherResourceName == null) {
- logger.error(
- "\nStateManagement: SYNCLOCK disableFailed(otherResourceName) operation: resourceName is NULL.\n");
- return;
- }
-
- setStateUsingTable(DISABLE_FAILED_ACTION, otherResourceName, OPERATION_STATE);
- }
-
- /**
- * disableDependency() changes operational state to disabled and adds availability status of
- * "dependency".
- *
- * @throws StateManagementException if an error occurs
- */
- public void disableDependency() throws StateManagementException {
- setStateUsingTable(DISABLE_DEPENDENCY_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * enableNoDependency() removes the availability status of "dependency " and will change the
- * operational state to enabled if not otherwise failed.
- *
- * @throws StateManagementException if an error occurs
- */
- public void enableNoDependency() throws StateManagementException {
- setStateUsingTable(ENABLE_NO_DEPENDENCY_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * promote() changes the standby status to providingservice if not otherwise failed.
- *
- * @throws IntegrityMonitorException if the status fails to change
- */
- public void promote() throws IntegrityMonitorException {
- AtomicReference<String> newStatus = new AtomicReference<>();
-
- setState(PROMOTE_ACTION, resourceName, sm -> {
- final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE_ACTION);
-
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- newStatus.set(sm.getStandbyStatus());
-
- return STANDBY_STATUS;
- });
-
- if (StateManagement.COLD_STANDBY.equals(newStatus.get())) {
- final String msg =
- "Failure to promote " + this.resourceName + " StandbyStatus = " + StateManagement.COLD_STANDBY;
- throw new StandbyStatusException(msg);
- }
- }
-
- /**
- * demote() changes standbystatus to hotstandby or, if failed, coldstandby.
- *
- * @throws StateManagementException if an error occurs
- */
- public void demote() throws StateManagementException {
- setStateUsingTable(DEMOTE_ACTION, this.resourceName, STANDBY_STATUS);
- }
-
- /**
- * Only used for a remote resource. It will not notify observers. It is used only in cases where
- * the remote resource has failed is such a way that it cannot update its own states. In
- * particular this is observed by PDP-D DroolsPdpsElectionHandler when it is trying to determine
- * which PDP-D should be designated as the lead.
- *
- * @param otherResourceName the resouce name
- * @throws StateManagementException if an error occurs
- */
- public void demote(final String otherResourceName) throws StateManagementException {
- if (otherResourceName == null) {
- logger.error(
- "\nStateManagement: SYNCLOCK demote(otherResourceName) operation: resourceName is NULL.\n");
- return;
- }
-
- setStateUsingTable(DEMOTE_ACTION, otherResourceName, null);
- }
-
- /**
- * Get the administration state.
- *
- * @return the administration state
- */
- public String getAdminState() {
- getEntityState("getAdminState", this.resourceName,
- sm -> this.adminState = sm.getAdminState(),
- () -> this.adminState = null);
- return this.adminState;
- }
-
- private void getEntityState(String methodName, String resourceName, Consumer<StateManagementEntity> function,
- Runnable notFound) {
-
- logger.debug("StateManagement(6/1/16): {} for resourceName {}", methodName, resourceName);
-
- final var em = emf.createEntityManager();
- try (final var emc = new EntityMgrCloser(em)) {
- final TypedQuery<StateManagementEntity> query =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
-
- query.setParameter(RESOURCE_NAME, this.resourceName);
-
- // Just test that we are retrieving the right object
- final List<StateManagementEntity> resourceList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!resourceList.isEmpty()) {
- // exist
- final var stateManagementEntity = resourceList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- function.accept(stateManagementEntity);
- } else {
- notFound.run();
- }
- } catch (final Exception ex) {
- logger.error("StateManagement: {} exception: {}", methodName, ex.getMessage(), ex);
- }
-
- }
-
- /**
- * Get the operational state.
- *
- * @return the operational state
- */
- public String getOpState() {
- getEntityState("getOpState", this.resourceName,
- sm -> this.opState = sm.getOpState(),
- () -> this.opState = null);
- return this.opState;
- }
-
- /**
- * Get the availability status.
- *
- * @return the availability status
- */
- public String getAvailStatus() {
- getEntityState("getAvailStatus", this.resourceName,
- sm -> this.availStatus = sm.getAvailStatus(),
- () -> this.availStatus = null);
- return this.availStatus;
- }
-
- /**
- * Get the standy status.
- *
- * @return the standby status
- */
- public String getStandbyStatus() {
- getEntityState("getStandbyStatus", this.resourceName,
- sm -> this.standbyStatus = sm.getStandbyStatus(),
- () -> this.standbyStatus = null);
- return this.standbyStatus;
- }
-
- /**
- * Get the standbystatus of a particular resource.
- *
- * @param otherResourceName the resource
- * @return the standby status
- */
- public String getStandbyStatus(final String otherResourceName) {
- AtomicReference<String> tempStandbyStatus = new AtomicReference<>();
-
- getEntityState("getStandbyStatus", otherResourceName,
- sm -> tempStandbyStatus.set(sm.getStandbyStatus()),
- () -> logger.error("getStandbyStatus: resourceName ={} not found in statemanagemententity table",
- otherResourceName));
-
- logger.debug("getStandbyStatus: Returning standbyStatus={}", tempStandbyStatus.get());
-
- return tempStandbyStatus.get();
- }
-
- /**
- * Find a StateManagementEntity.
- *
- * @param em the entity manager
- * @param otherResourceName the resource name
- * @return the StateManagementEntity
- */
- private static StateManagementEntity findStateManagementEntity(final EntityManager em,
- final String otherResourceName) {
- logger.debug("StateManagementEntity: findStateManagementEntity: Entry");
- try {
- final TypedQuery<StateManagementEntity> query =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
-
- query.setParameter(RESOURCE_NAME, otherResourceName);
-
- // Just test that we are retrieving the right object
- final List<StateManagementEntity> resourceList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!resourceList.isEmpty()) {
- // exist
- final var stateManagementEntity = resourceList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- stateManagementEntity.setModifiedDate(MonitorTime.getInstance().getDate());
- return stateManagementEntity;
- } else {
- // not exist - create one
- final var stateManagementEntity = new StateManagementEntity();
- stateManagementEntity.setResourceName(otherResourceName);
- stateManagementEntity.setAdminState(UNLOCKED);
- stateManagementEntity.setOpState(ENABLED);
- stateManagementEntity.setAvailStatus(NULL_VALUE);
- stateManagementEntity.setStandbyStatus(NULL_VALUE); // default
- return stateManagementEntity;
- }
- } catch (final Exception ex) {
- throw new EntityRetrievalException("findStateManagementEntity exception", ex);
- }
- }
-
- /**
- * Clean up all the StateManagementEntities.
- */
- public void deleteAllStateManagementEntities() {
-
- logger.debug("StateManagement: deleteAllStateManagementEntities: Entering");
-
- /*
- * Start transaction
- */
- final var em = emf.createEntityManager();
-
- try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
- final TypedQuery<StateManagementEntity> stateManagementEntityListQuery =
- em.createQuery("SELECT p FROM StateManagementEntity p", StateManagementEntity.class);
- final List<StateManagementEntity> stateManagementEntityList = stateManagementEntityListQuery
- .setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- logger.debug("deleteAllStateManagementEntities: Deleting {} StateManagementEntity records",
- stateManagementEntityList.size());
- for (final StateManagementEntity stateManagementEntity : stateManagementEntityList) {
- logger.debug("deleteAllStateManagementEntities: Deleting statemanagemententity with resourceName={} and"
- + " standbyStatus={}", stateManagementEntity.getResourceName(),
- stateManagementEntity.getStandbyStatus());
- em.remove(stateManagementEntity);
- }
-
- et.commit();
- } catch (final Exception ex) {
- logger.error("StateManagement.deleteAllStateManagementEntities() caught Exception: ", ex);
- }
- logger.debug("deleteAllStateManagementEntities: Exiting");
- }
-
- @FunctionalInterface
- private static interface ExFunction<T, R> {
- public R update(T object) throws IntegrityMonitorException;
- }
-
- private static class MyTransaction extends EntityTransCloser {
-
- /**
- * Create an instance.
- *
- * @param em the entity manager
- */
- public MyTransaction(final EntityManager em) {
- super(em.getTransaction());
- }
-
- @Override
- public void commit() {
- synchronized (FLUSHLOCK) {
- if (getTransaction().isActive()) {
- super.commit();
- }
- }
- }
-
- @Override
- public void rollback() {
- synchronized (FLUSHLOCK) {
- if (getTransaction().isActive()) {
- super.rollback();
- }
- }
- }
-
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java
deleted file mode 100644
index 05597a2a..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class StateManagementException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public StateManagementException() {
- super();
- }
-
- public StateManagementException(final String message) {
- super(message);
- }
-
- public StateManagementException(final Throwable cause) {
- super(cause);
- }
-
- public StateManagementException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java
deleted file mode 100644
index 2ebef874..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import com.google.re2j.Pattern;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import org.apache.commons.lang3.tuple.Pair;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The StateTransition class coordinates all state transitions.
- */
-public class StateTransition {
- private static final Pattern COMMA_PAT = Pattern.compile(",");
-
- private static final String DEPENDENCY_FAILED = "dependency.failed";
-
- private static final String ANY_DISABLED_ANY_COLDSTANDBY = "${1},disabled,${3},coldstandby,";
- private static final String ANY_DISABLED_ANY_COLDSTANDBY_STANDBY_STATUS_EXCEPTION =
- "${1},disabled,${3},coldstandby,StandbyStatusException";
- private static final String LOCKED_ENABLED_NULL_COLDSTANDBY_STANDBY_STATUS_EXCEPTION =
- "locked,enabled,null,coldstandby,StandbyStatusException";
- private static final String UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE = "unlocked,enabled,null,providingservice,";
- private static final String UNLOCKED_DISABLED_DEPENDENCY_HOTSTANDBY = "unlocked,disabled,dependency,hotstandby,";
- private static final String ANY_DISABLED_DEPENDENCY_NULL = "${1},disabled,dependency,null,";
- private static final String ANY_DISABLED_DEPENDENCY_COLDSTANDBY = "${1},disabled,dependency,coldstandby,";
- private static final String ANY_DISABLED_DEPENDENCY_FAILED_NULL = "${1},disabled,dependency.failed,null,";
- private static final String ANY_DISABLED_DEPENDENCY_FAILED_COLDSTANDBY =
- "${1},disabled,dependency.failed,coldstandby,";
- private static final String ANY_DISABLED_FAILED_NULL = "${1},disabled,failed,null,";
- private static final String ANY_DISABLED_FAILED_COLDSTANDBY = "${1},disabled,failed,coldstandby,";
- private static final String UNLOCKED_DISABLED_ANY_NULL = "unlocked,disabled,${3},null,";
- private static final String UNLOCKED_DISABLED_ANY_COLDSTANDBY = "unlocked,disabled,${3},coldstandby,";
- private static final String UNLOCKED_ENABLED_NULL_NULL = "unlocked,enabled,null,null,";
- private static final String LOCKED_DISABLED_ANY_NULL = "locked,disabled,${3},null,";
- private static final String LOCKED_DISABLED_ANY_COLDSTANDBY = "locked,disabled,${3},coldstandby,";
- private static final String UNLOCKED_ENABLED_NULL_HOTSTANDBY = "unlocked,enabled,null,hotstandby,";
- private static final String UNLOCKED_ENABLED_NULL_ANY = "unlocked,enabled,null,${4},";
- private static final String LOCKED_ENABLED_NULL_NULL = "locked,enabled,null,null,";
- private static final String LOCKED_ENABLED_NULL_COLDSTANDBY = "locked,enabled,null,coldstandby,";
- private static final Logger logger = LoggerFactory.getLogger(StateTransition.class);
-
- public static final String ADMIN_STATE = "adminState";
- public static final String OPERATION_STATE = "opState";
- public static final String AVAILABLE_STATUS = "availStatus";
- public static final String STANDBY_STATUS = "standbyStatus";
- public static final String ACTOIN_NAME = "actionName";
-
- /*
- * Common strings.
- */
- private static final String EXCEPTION_STRING = "Exception:StateTransition unable to process state: adminState=[";
- private static final String OPSTATE_STRING = "], opState=[";
- private static final String AVAILSTATUS_STRING = "], availStatus=[";
- private static final String STANDBY_STRING = "], standbyStatus=[";
- private static final String ACTION_STRING = "], actionName=[";
-
- /*
- * Valid values for each type.
- */
- private static final Set<String> VALID_ADMIN_STATE = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.LOCKED,
- StateManagement.UNLOCKED)));
-
- private static final Set<String> VALID_OP_STATE = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.ENABLED,
- StateManagement.DISABLED)));
-
- private static final Set<String> VALID_STANDBY_STATUS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.NULL_VALUE,
- StateManagement.COLD_STANDBY,
- StateManagement.HOT_STANDBY,
- StateManagement.PROVIDING_SERVICE)));
-
- private static final Set<String> VALID_AVAIL_STATUS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.NULL_VALUE,
- StateManagement.DEPENDENCY,
- StateManagement.DEPENDENCY_FAILED,
- StateManagement.FAILED)));
-
- private static final Set<String> VALID_ACTION_NAME = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.DEMOTE_ACTION,
- StateManagement.DISABLE_DEPENDENCY_ACTION,
- StateManagement.DISABLE_FAILED_ACTION,
- StateManagement.ENABLE_NO_DEPENDENCY_ACTION,
- StateManagement.ENABLE_NOT_FAILED_ACTION,
- StateManagement.LOCK_ACTION,
- StateManagement.PROMOTE_ACTION,
- StateManagement.UNLOCK_ACTION)));
-
- /**
- * This is only used while populating {@link #STATE_TABLE}.
- */
- private static final List<Pair<String, String[]>> TRANSITION_ITEMS = new ArrayList<>(10);
-
- /**
- * State-transition table.
- */
- private static final Map<String, String> STATE_TABLE = new HashMap<>();
-
- static {
- populateStateTable();
- }
-
-
- /**
- * Calculates the state transition and returns the end state.
- *
- * @param adminState the administration state
- * @param opState the operational state
- * @param availStatus the availability status
- * @param standbyStatus the standby status
- * @param actionName the action name
- * @return the StateEement
- * @throws StateTransitionException if an error occurs
- */
- public StateElement getEndingState(String adminState, String opState, String availStatus, String standbyStatus,
- String actionName) throws StateTransitionException {
- logger.debug("getEndingState");
- logger.debug("adminState=[{}], opState=[{}], availStatus=[{}], standbyStatus=[{}], actionName[{}]",
- adminState, opState, availStatus, standbyStatus, actionName);
-
- if (availStatus == null) {
- availStatus = StateManagement.NULL_VALUE;
- }
- if (standbyStatus == null) {
- standbyStatus = StateManagement.NULL_VALUE;
- }
-
- if (!VALID_ADMIN_STATE.contains(adminState) || !VALID_OP_STATE.contains(opState)
- || !VALID_STANDBY_STATUS.contains(standbyStatus)) {
- throw new StateTransitionException(
- EXCEPTION_STRING + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus
- + STANDBY_STRING + standbyStatus + ACTION_STRING + actionName + "]");
- }
-
- if (!VALID_AVAIL_STATUS.contains(availStatus) || !VALID_ACTION_NAME.contains(actionName)) {
- throw new StateTransitionException(
- EXCEPTION_STRING + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus
- + STANDBY_STRING + standbyStatus + ACTION_STRING + actionName + "]");
- }
-
-
- var stateElement = new StateElement();
-
- // dependency,failed is stored as dependency.failed in StateTable
- String availStatus2 = availStatus;
- if (availStatus2 != null) {
- availStatus2 = availStatus.replace(",", ".");
- }
- String key = adminState + "," + opState + "," + availStatus2 + "," + standbyStatus + "," + actionName;
- logger.debug("Ending State search key: {}", key);
- String value = STATE_TABLE.get(key);
-
- if (value != null) {
- String[] parts = COMMA_PAT.split(value, 5);
- stateElement.setEndingAdminState(parts[0].trim());
- stateElement.setEndingOpState(parts[1].trim());
- stateElement.setEndingAvailStatus(parts[2].trim().replace(".", ","));
- stateElement.setEndingStandbyStatus(parts[3].trim());
- stateElement.setException(parts[4].trim());
- stateElement.setAdminState(adminState);
- stateElement.setOpState(opState);
- stateElement.setAvailStatus(availStatus);
- stateElement.setStandbyStatus(standbyStatus);
- stateElement.setActionName(actionName);
-
- stateElement.displayStateElement();
-
- } else {
- String msg = "Ending state not found, adminState=[" + adminState + OPSTATE_STRING + opState
- + AVAILSTATUS_STRING + availStatus + STANDBY_STRING + standbyStatus + ACTION_STRING
- + actionName + "]";
- logger.error("{}", msg);
- throw new StateTransitionException(msg);
- }
-
- return stateElement;
- }
-
- /**
- * Adding State Transition info into HashMap. It includes all state/status and action
- * combinations key : adminState,opState,availStatus,standbyStatus,actionName value:
- * endingAdminState,endingOpState,endingAvailStatus,endingStandbyStatus,exception Note : Use
- * period instead of comma as seperator when store multi-value endingStandbyStatus (convert to
- * comma during retrieval)
- *
- * <p>Note on illegal state/status combinations: This table has many state/status combinations
- * that should never occur. However, they *may* occur due to corruption or manual manipulation
- * of the DB. So, in each case of an illegal combination, the state/status is first corrected
- * before applying the action. It is assumed that the administrative and operational states are
- * always correct. Second, if the availability status is in "agreement" with the operational
- * state, it is assumed correct. If it is null and the operational state is disabled, the
- * availability status is left null until a disabledfailed or disableddependency action is
- * received. Or, if a enableNotFailed or enableNoDependency is received while the availability
- * status is null, it will remain null, but the Operational state will change to enabled.
- *
- * <p>If the standby status is not in agreement with the administrative and/or operational
- * states, it is brought into agreement. For example, if the administrative state is locked and
- * the standby status is providingservice, the standby status is changed to coldstandby.
- *
- * <p>After bringing the states/status attributes into agreement, *then* the action is applied
- * to them. For example, if the administrative state is locked, the operational state is
- * enabled, the availability status is null, the standby status is providingservice and the
- * action is unlock, the standby status is changed to coldstandby and then the unlock action is
- * applied. This will change the final state/status to administrative state = unlocked,
- * operational state = disabled, availability status = null and standby status = hotstandby.
- *
- * <p>Note on standby status: If the starting state of standby status is null and either a
- * promote or demote action is made, the assumption is that standbystatus is supported and
- * therefore, the standby status will be changed to providingservice, hotstandby or coldstandby
- * - depending on the value of the administrative and operational states. If an attempt to
- * promote is made when the administrative state is locked or operational state is disabled, a
- * StandbyStatusException will be thrown since promotion (state transition) is not possible. If
- * the standby status is coldstandby and a transition occurs on the administrative or
- * operational state such that they are unlocked and enabled, the standby status is
- * automatically transitioned to hotstandby since it is only those two states that can hold the
- * standby status in the coldstandby value.
- */
-
- private static void populateStateTable() {
- /*
- * These are the items we'll be using while populating the state transition table.
- */
- TRANSITION_ITEMS.clear();
- TRANSITION_ITEMS.add(Pair.of("${1}", new String[] {"unlocked", "locked"}));
- TRANSITION_ITEMS.add(Pair.of("${2}", new String[] {"enabled", "disabled"}));
- TRANSITION_ITEMS.add(Pair.of("${3}", new String[] {"null", "failed", "dependency", DEPENDENCY_FAILED}));
- TRANSITION_ITEMS.add(Pair.of("${3:fail}", new String[] {"failed", DEPENDENCY_FAILED}));
- TRANSITION_ITEMS.add(Pair.of("${3:dep}", new String[] {"dependency", DEPENDENCY_FAILED}));
- TRANSITION_ITEMS.add(Pair.of("${4}", new String[] {"null", "coldstandby", "hotstandby", "providingservice"}));
-
- STATE_TABLE.clear();
-
- // lock
- populate("${1},enabled,${3},${4},lock", LOCKED_ENABLED_NULL_COLDSTANDBY);
- populate("${1},enabled,${3},null,lock", LOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3},${4},lock", LOCKED_DISABLED_ANY_COLDSTANDBY);
- populate("${1},disabled,${3},null,lock", LOCKED_DISABLED_ANY_NULL);
-
-
- // unlock
- populate("unlocked,enabled,${3},${4},unlock", UNLOCKED_ENABLED_NULL_ANY);
- populate("unlocked,enabled,${3},coldstandby,unlock", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("locked,enabled,${3},${4},unlock", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
- populate("locked,enabled,${3},null,unlock", UNLOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3},${4},unlock", UNLOCKED_DISABLED_ANY_COLDSTANDBY);
- populate("${1},disabled,${3},null,unlock", UNLOCKED_DISABLED_ANY_NULL);
-
-
- // disableFailed
- populate("${1},${2},${3},${4},disableFailed", ANY_DISABLED_FAILED_COLDSTANDBY);
- populate("${1},${2},${3},null,disableFailed", ANY_DISABLED_FAILED_NULL);
-
- populate("${1},disabled,${3:dep},${4},disableFailed", ANY_DISABLED_DEPENDENCY_FAILED_COLDSTANDBY);
- populate("${1},disabled,${3:dep},null,disableFailed", ANY_DISABLED_DEPENDENCY_FAILED_NULL);
-
-
- // enableNotFailed
- populate("unlocked,${2},${3},${4},enableNotFailed", UNLOCKED_ENABLED_NULL_ANY);
- populate("unlocked,${2},${3},coldstandby,enableNotFailed", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("unlocked,disabled,${3},${4},enableNotFailed", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
- populate("unlocked,disabled,${3},null,enableNotFailed", UNLOCKED_ENABLED_NULL_NULL);
-
- populate("locked,${2},${3},${4},enableNotFailed", LOCKED_ENABLED_NULL_COLDSTANDBY);
- populate("locked,${2},${3},null,enableNotFailed", LOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3:dep},${4},enableNotFailed", ANY_DISABLED_DEPENDENCY_COLDSTANDBY);
- populate("${1},disabled,${3:dep},null,enableNotFailed", ANY_DISABLED_DEPENDENCY_NULL);
-
-
- // disableDependency
- populate("${1},${2},${3},${4},disableDependency", ANY_DISABLED_DEPENDENCY_COLDSTANDBY);
- populate("${1},${2},${3},null,disableDependency", ANY_DISABLED_DEPENDENCY_NULL);
-
- populate("${1},disabled,${3:fail},${4},disableDependency", ANY_DISABLED_DEPENDENCY_FAILED_COLDSTANDBY);
- populate("${1},disabled,${3:fail},null,disableDependency", ANY_DISABLED_DEPENDENCY_FAILED_NULL);
-
- populate("unlocked,enabled,dependency,hotstandby,disableDependency", UNLOCKED_DISABLED_DEPENDENCY_HOTSTANDBY);
-
-
- // enableNoDependency
- populate("unlocked,enabled,${3},${4},enableNoDependency", UNLOCKED_ENABLED_NULL_ANY);
- populate("unlocked,enabled,${3},coldstandby,enableNoDependency", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("unlocked,disabled,${3},${4},enableNoDependency", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
- populate("unlocked,disabled,${3},null,enableNoDependency", UNLOCKED_ENABLED_NULL_NULL);
-
- populate("locked,${2},${3},${4},enableNoDependency", LOCKED_ENABLED_NULL_COLDSTANDBY);
- populate("locked,${2},${3},null,enableNoDependency", LOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3:fail},${4},enableNoDependency", ANY_DISABLED_FAILED_COLDSTANDBY);
- populate("${1},disabled,${3:fail},null,enableNoDependency", ANY_DISABLED_FAILED_NULL);
-
-
- // promote
- populate("unlocked,enabled,${3},${4},promote", UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE);
-
- populate("locked,enabled,${3},${4},promote", LOCKED_ENABLED_NULL_COLDSTANDBY_STANDBY_STATUS_EXCEPTION);
-
- populate("${1},disabled,${3},${4},promote", ANY_DISABLED_ANY_COLDSTANDBY_STANDBY_STATUS_EXCEPTION);
-
-
- // demote
- populate("unlocked,enabled,${3},${4},demote", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("locked,enabled,${3},${4},demote", LOCKED_ENABLED_NULL_COLDSTANDBY);
-
- populate("${1},disabled,${3},${4},demote", ANY_DISABLED_ANY_COLDSTANDBY);
- }
-
- /**
- * Populates {@link #STATE_TABLE} with the incoming and outgoing strings, trying all
- * substitutions of the item place-holders that appear within the strings.
- * @param incoming incoming string, with optional item place-holders
- * @param outgoing outgoing string, with optional item place-holders
- */
- private static void populate(String incoming, String outgoing) {
- populate(incoming, outgoing, 0);
- }
-
- /**
- * Makes appropriate substitutions within the incoming and outgoing strings, looping
- * through all possible items at the given position. Once the position has reached the
- * end of the item table, the incoming/outgoing result is added to
- * {@link #STATE_TABLE}.
- *
- * @param incoming incoming string, with optional item place-holders
- * @param outgoing outgoing string, with optional item place-holders
- * @param pos current position within the transition items
- */
- private static void populate(String incoming, String outgoing, int pos) {
-
- if (pos >= TRANSITION_ITEMS.size()) {
- // used up all possible replacements - add result to the table
- STATE_TABLE.put(incoming, outgoing);
- return;
- }
-
- Pair<String, String[]> pair = TRANSITION_ITEMS.get(pos);
- String key = pair.getKey();
-
- if (!incoming.contains(key) && !outgoing.contains(key)) {
- // strings do not contain a place-holder for this position - try the next
- populate(incoming, outgoing, pos + 1);
- return;
- }
-
- // process all items associated with this place-holder
- for (String item : pair.getValue()) {
- String incoming2 = incoming.replace(key, item);
- String outgoing2 = outgoing.replace(key, item);
- populate(incoming2, outgoing2, pos + 1);
- }
- }
-
- /**
- * Display the state table.
- */
- public void displayStateTable() {
- if (!logger.isDebugEnabled()) {
- return;
- }
-
- for (Entry<String, String> me : STATE_TABLE.entrySet()) {
- String key = me.getKey() + me.getValue().replace(".", ",");
- logger.debug("{}", key);
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java
deleted file mode 100644
index 0f4ea2fd..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-public class StateTransitionException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public StateTransitionException() {
- super();
- }
-
- public StateTransitionException(String message) {
- super(message);
- }
-
- public StateTransitionException(Throwable cause) {
- super(cause);
- }
-
- public StateTransitionException(String message, Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java
deleted file mode 100644
index 9387805c..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2018 Ericsson. 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.exceptions;
-
-public class EntityRetrievalException extends RuntimeException {
-
- private static final long serialVersionUID = 8761143697306009072L;
-
- public EntityRetrievalException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java
deleted file mode 100644
index 8cbdaa7d..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jmx;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import org.onap.policy.common.im.IntegrityMonitor;
-import org.onap.policy.common.im.IntegrityMonitorException;
-import org.onap.policy.common.im.StateManagement;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Base class for component MBeans.
- */
-public class ComponentAdmin implements ComponentAdminMBean {
- private static final String STATE_MANAGER = "stateManager";
-
- private static final Logger logger = LoggerFactory.getLogger(ComponentAdmin.class.getName());
-
- private final String name;
- private MBeanServer registeredMBeanServer;
- private ObjectName registeredObjectName;
- private IntegrityMonitor integrityMonitor = null;
- private StateManagement stateManager = null;
-
- /**
- * Constructor.
- *
- * @param name the MBean name
- * @param integrityMonitor the integrity monitor
- * @param stateManager the state manager
- * @throws ComponentAdminException if an error occurs
- */
- public ComponentAdmin(String name, IntegrityMonitor integrityMonitor, StateManagement stateManager)
- throws ComponentAdminException {
- if ((name == null) || (integrityMonitor == null) || (stateManager == null)) {
- logger.error("Error: ComponentAdmin constructor called with invalid input");
- throw new ComponentAdminException("null input");
- }
-
- this.name = "ONAP_POLICY_COMP:name=" + name;
- this.integrityMonitor = integrityMonitor;
- this.stateManager = stateManager;
-
- try {
- register();
- } catch (ComponentAdminException e) {
- logger.debug("Failed to register ComponentAdmin MBean");
- throw e;
- }
- }
-
- /**
- * Registers with the MBean server.
- *
- * @throws ComponentAdminException a JMX exception
- */
- public synchronized void register() throws ComponentAdminException {
-
- try {
- logger.debug("Registering {} MBean", name);
-
- var mbeanServer = findMBeanServer();
-
- if (mbeanServer == null) {
- return;
- }
-
- var objectName = new ObjectName(name);
-
- if (mbeanServer.isRegistered(objectName)) {
- logger.debug("Unregistering a previously registered {} MBean", name);
- mbeanServer.unregisterMBean(objectName);
- }
-
- mbeanServer.registerMBean(this, objectName);
- registeredMBeanServer = mbeanServer;
- registeredObjectName = objectName;
-
- } catch (MalformedObjectNameException | MBeanRegistrationException | InstanceNotFoundException
- | InstanceAlreadyExistsException | NotCompliantMBeanException e) {
- throw new ComponentAdminException(e);
- }
- }
-
- /**
- * Checks if this MBean is registered with the MBeanServer.
- *
- * @return true if this MBean is registered with the MBeanServer.
- */
- public boolean isRegistered() {
- return registeredObjectName != null;
- }
-
- /**
- * Unregisters with the MBean server.
- *
- * @throws ComponentAdminException a JMX exception
- */
- public synchronized void unregister() throws ComponentAdminException {
-
- if (registeredObjectName == null) {
- return;
- }
-
-
- try {
- registeredMBeanServer.unregisterMBean(registeredObjectName);
-
- } catch (MBeanRegistrationException | InstanceNotFoundException e) {
- throw new ComponentAdminException(e);
- }
-
- registeredMBeanServer = null;
- registeredObjectName = null;
- }
-
- @Override
- public String toString() {
- return ComponentAdmin.class.getSimpleName() + "[" + name + "]";
- }
-
- /**
- * Finds the MBeanServer.
- *
- * @return the MBeanServer, or null if it is not found
- */
- public static MBeanServer findMBeanServer() {
- ArrayList<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer(null);
-
- Iterator<MBeanServer> iter = mbeanServers.iterator();
- MBeanServer mbeanServer;
-
- while (iter.hasNext()) {
- mbeanServer = iter.next();
- if ("DefaultDomain".equals(mbeanServer.getDefaultDomain())) {
- return mbeanServer;
- }
- }
-
- return null;
- }
-
- /**
- * Creates the MBeanServer (intended for unit testing only).
- *
- * @return the MBeanServer
- */
- public static MBeanServer createMBeanServer() {
- return MBeanServerFactory.createMBeanServer("DefaultDomain");
- }
-
- /**
- * Get the MBean object name for the specified feature name.
- *
- * @param componentName component name
- * @return the object name
- * @throws MalformedObjectNameException a JMX exception
- */
- public static ObjectName getObjectName(String componentName) throws MalformedObjectNameException {
- return new ObjectName("ONAP_POLICY_COMP:name=" + componentName);
- }
-
- @Override
- public void test() throws IntegrityMonitorException {
- // Call evaluateSanity on IntegrityMonitor to run the test
- logger.debug("test() called...");
- if (integrityMonitor != null) {
- integrityMonitor.evaluateSanity();
- } else {
- logger.error("Unable to invoke test() - state manager instance is null");
- throw new ComponentAdminException(STATE_MANAGER);
- }
-
- }
-
- @Override
- public void lock() throws IntegrityMonitorException {
- logger.debug("lock() called...");
- if (stateManager != null) {
- stateManager.lock();
- } else {
- logger.error("Unable to invoke lock() - state manager instance is null");
- throw new ComponentAdminException(STATE_MANAGER);
- }
- }
-
- @Override
- public void unlock() throws IntegrityMonitorException {
- logger.debug("unlock() called...");
- if (stateManager != null) {
- stateManager.unlock();
- } else {
- logger.error("Unable to invoke unlock() - state manager instance is null");
- throw new ComponentAdminException(STATE_MANAGER);
- }
-
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java
deleted file mode 100644
index dcc4da0a..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jmx;
-
-import org.onap.policy.common.im.IntegrityMonitorException;
-
-public class ComponentAdminException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public ComponentAdminException() {
- super();
- }
-
- public ComponentAdminException(String message) {
- super(message);
- }
-
- public ComponentAdminException(Throwable cause) {
- super(cause);
- }
-
- public ComponentAdminException(String message, Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java
deleted file mode 100644
index 3276cf63..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jmx;
-
-import org.onap.policy.common.im.IntegrityMonitorException;
-
-/**
- * Provides operations to test health, lock and unlock components.
- */
-public interface ComponentAdminMBean {
- /**
- * Test health of component.
- *
- * @throws IntegrityMonitorException if the component fails the health check
- */
- void test() throws IntegrityMonitorException;
-
- /**
- * Administratively lock component.
- *
- * @throws IntegrityMonitorException if the component lock fails
- */
- void lock() throws IntegrityMonitorException;
-
- /**
- * Administratively unlock component.
- *
- * @throws IntegrityMonitorException if the component unlock fails
- */
- void unlock() throws IntegrityMonitorException;
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java
deleted file mode 100644
index a2d8c091..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jmx;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import javax.management.MBeanServerConnection;
-import javax.management.remote.JMXConnectionNotification;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import org.onap.policy.common.im.IntegrityMonitorException;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-/**
- * Class to create a JMX RMI connection to the JmxAgent.
- */
-public final class JmxAgentConnection {
-
- private static final Logger logger = FlexLogger.getLogger(JmxAgentConnection.class);
-
-
- private static final String DEFAULT_HOST = "localhost";
- private static final String DEFAULT_PORT = "9996";
-
- private String host;
- private String port;
- private JMXConnector connector;
- private String jmxUrl = null;
-
- /**
- * Set up the host/port from the properties. Use defaults if missing from the properties.
- */
- public JmxAgentConnection() {
- host = DEFAULT_HOST;
- port = DEFAULT_PORT;
- }
-
- public JmxAgentConnection(String url) {
- jmxUrl = url;
- }
-
- /**
- * Generate jmxAgent url. service:jmx:rmi:///jndi/rmi://host.domain:9999/jmxAgent
- *
- * @param host host.domain
- * @param port 9999
- * @return jmxAgent url.
- */
- private static String jmxAgentUrl(String host, String port) {
-
- return "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
- }
-
- /**
- * Get a connection to the jmxAgent MBeanServer.
- *
- * @return the connection
- * @throws IntegrityMonitorException on error
- */
- public MBeanServerConnection getMBeanConnection() throws IntegrityMonitorException {
-
- try {
- JMXServiceURL url;
- if (jmxUrl == null) {
- url = new JMXServiceURL(jmxAgentUrl(host, port));
- } else {
- url = new JMXServiceURL(jmxUrl);
- }
- Map<String, Object> env = new HashMap<>();
-
- connector = JMXConnectorFactory.newJMXConnector(url, env);
- connector.connect();
- connector.addConnectionNotificationListener((notification, handback) -> {
- if (notification.getType().equals(JMXConnectionNotification.FAILED)) {
- // handle disconnect
- disconnect();
- }
- }, null, null);
-
- return connector.getMBeanServerConnection();
-
- } catch (IOException e) {
- throw new IntegrityMonitorException(e);
- }
- }
-
- /**
- * Disconnect.
- */
- public void disconnect() {
- if (connector != null) {
- try {
- connector.close();
- } catch (IOException e) {
- logger.debug(e);
- }
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java
deleted file mode 100644
index 5213baef..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.MappedSuperclass;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.Serial;
-import java.io.Serializable;
-import java.util.Date;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.common.im.MonitorTime;
-
-/*
- * Superclass of Entities having create and update timestamps.
- */
-@MappedSuperclass
-@Getter
-@Setter
-@NoArgsConstructor
-public class DateEntity implements Serializable {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_date", updatable = false)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "last_updated")
- private Date lastUpdated;
-
- /**
- * PrePersist callback method.
- */
- @PrePersist
- public void prePersist() {
- var date = MonitorTime.getInstance().getDate();
- this.createdDate = date;
- this.lastUpdated = date;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.lastUpdated = MonitorTime.getInstance().getDate();
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java
deleted file mode 100644
index 7c9698b3..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.Table;
-import java.io.Serial;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Entity
-@Table(name = "ForwardProgressEntity")
-@NamedQuery(name = " ForwardProgressEntity.findAll", query = "SELECT e FROM ForwardProgressEntity e ")
-@NamedQuery(name = "ForwardProgressEntity.deleteAll", query = "DELETE FROM ForwardProgressEntity WHERE 1=1")
-@Getter
-@Setter
-@NoArgsConstructor
-public class ForwardProgressEntity extends DateEntity {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "forwardProgressId")
- @Setter(AccessLevel.NONE)
- private long forwardProgressId;
-
- @Column(name = "resourceName", nullable = false, length = 100, unique = true)
- private String resourceName;
-
- @Column(name = "fpc_count", nullable = false)
- private long fpcCount;
-
- /**
- * PrePersist callback method.
- */
- @PrePersist
- @Override
- public void prePersist() {
- this.fpcCount = 0;
- super.prePersist();
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java
deleted file mode 100644
index e70a000b..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Table;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.Serial;
-import java.io.Serializable;
-import java.util.Date;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.common.im.MonitorTime;
-
-@Entity
-@Table(name = "ImTestEntity")
-@NamedQuery(name = " ImTestEntity.findAll", query = "SELECT e FROM ImTestEntity e ")
-@NamedQuery(name = "ImTestEntity.deleteAll", query = "DELETE FROM ImTestEntity WHERE 1=1")
-@Getter
-@Setter
-@NoArgsConstructor
-public class ImTestEntity implements Serializable {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "ImTestId")
- @Setter(AccessLevel.NONE)
- private long imTestId;
-
- @Column(name = "created_by", nullable = false, length = 255)
- private String createdBy = "guest";
-
- @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;
-
- /**
- * PrePersist callback method.
- */
- @PrePersist
- public void prePersist() {
- var date = MonitorTime.getInstance().getDate();
- this.createdDate = date;
- this.modifiedDate = date;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.modifiedDate = MonitorTime.getInstance().getDate();
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java
deleted file mode 100644
index 3ee607f2..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.Table;
-import java.io.Serial;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-/*
- * The Entity class to persist a policy object ResourceRegistration
- */
-
-@Entity
-@Table(name = "ResourceRegistrationEntity")
-@NamedQuery(name = " ResourceRegistrationEntity.findAll", query = "SELECT e FROM ResourceRegistrationEntity e ")
-@NamedQuery(name = "ResourceRegistrationEntity.deleteAll", query = "DELETE FROM ResourceRegistrationEntity WHERE 1=1")
-@Getter
-@Setter
-@NoArgsConstructor
-public class ResourceRegistrationEntity extends DateEntity {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "ResourceRegistrationId")
- @Setter(AccessLevel.NONE)
- private long resourceRegistrationId;
-
- @Column(name = "resourceName", nullable = false, length = 100, unique = true)
- private String resourceName;
-
- @Column(name = "resourceUrl", nullable = false, length = 255, unique = true)
- private String resourceUrl;
-
- @Column(name = "site", nullable = true, length = 50)
- private String site;
-
- @Column(name = "nodeType", nullable = true, length = 50)
- private String nodeType;
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java
deleted file mode 100644
index b03ec71b..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Table;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.Serial;
-import java.io.Serializable;
-import java.util.Date;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.common.im.MonitorTime;
-
-@Entity
-@Table(name = "StateManagementEntity")
-@NamedQuery(name = "StateManagementEntity.findAll", query = "SELECT e FROM StateManagementEntity e")
-@Getter
-@Setter
-@NoArgsConstructor
-public class StateManagementEntity implements Serializable {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "id")
- @Getter(AccessLevel.NONE)
- @Setter(AccessLevel.NONE)
- private long id;
-
- @Column(name = "resourceName", nullable = false, length = 100, unique = true)
- private String resourceName;
-
- @Column(name = "adminState", nullable = false, length = 20)
- private String adminState;
-
- @Column(name = "opState", nullable = false, length = 20)
- private String opState;
-
- @Column(name = "availStatus", nullable = false, length = 20)
- private String availStatus;
-
- @Column(name = "standbyStatus", nullable = false, length = 20)
- private String standbyStatus;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_Date", updatable = false)
- @Setter(AccessLevel.NONE)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "modifiedDate", nullable = false)
- private Date modifiedDate;
-
- @PrePersist
- public void prePersist() {
- this.createdDate = MonitorTime.getInstance().getDate();
- this.modifiedDate = MonitorTime.getInstance().getDate();
- }
-
- @PreUpdate
- public void preUpdate() {
- this.modifiedDate = MonitorTime.getInstance().getDate();
- }
-
- /**
- * Clone a StateManagementEntity.
- *
- * @param sm the StateManagementEntity to clone
- * @return a new StateManagementEntity
- */
- public static StateManagementEntity clone(StateManagementEntity sm) {
- var newStateManagementEntity = new StateManagementEntity();
- newStateManagementEntity.setResourceName(sm.getResourceName());
- newStateManagementEntity.setAdminState(sm.getResourceName());
- newStateManagementEntity.setOpState(sm.getOpState());
- newStateManagementEntity.setAdminState(sm.getAdminState());
- newStateManagementEntity.setAvailStatus(sm.getAvailStatus());
- newStateManagementEntity.setStandbyStatus(sm.getStandbyStatus());
-
- return newStateManagementEntity;
- }
-}
diff --git a/integrity-monitor/src/main/resources/META-INF/persistence.xml b/integrity-monitor/src/main/resources/META-INF/persistence.xml
deleted file mode 100644
index 6a46c2a2..00000000
--- a/integrity-monitor/src/main/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ============LICENSE_START=======================================================
- Integrity Monitor
- ================================================================================
- Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023-2024 Nordix Foundation.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-<persistence version="3.1" xmlns="https://jakarta.ee/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd">
- <persistence-unit name="schemaPU" transaction-type="RESOURCE_LOCAL">
- <!-- Limited use for generating the DB and schema files for imtest DB - uses hibernate -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
- <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
- <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
- <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
- </properties>
- </persistence-unit>
-
- <persistence-unit name="operationalPU" transaction-type="RESOURCE_LOCAL">
- <!-- For operational use -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
- <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
- <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
- <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <!-- none -->
- </properties>
- </persistence-unit>
-</persistence>
diff --git a/integrity-monitor/src/main/resources/log4j.properties b/integrity-monitor/src/main/resources/log4j.properties
deleted file mode 100644
index fde133de..00000000
--- a/integrity-monitor/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,48 +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=========================================================
-###
-
-#
-# Use this properties for debugging and development.
-#
-#
-# Set root logger level to DEBUG and its only appender to A1.
-log4j.rootLogger=INFO, FILE
-
-# A1 is set to be a DailyRollingFileAppender.
-log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
-
-# Set the name of the file
-log4j.appender.FILE.File=IntegrityMonitor.log
-
-# Set the immediate flush to true (default)
-log4j.appender.FILE.ImmediateFlush=true
-
-# Set the threshold to debug mode
-log4j.appender.FILE.Threshold=debug
-
-# Set the append to false, should not overwrite
-log4j.appender.FILE.Append=true
-
-# Set the DatePattern
-log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
-
-# A1 uses PatternLayout.
-log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
-log4j.appender.FILE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/AllSeemsWellTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/AllSeemsWellTest.java
deleted file mode 100644
index c5b2e193..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/AllSeemsWellTest.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-import java.util.concurrent.Semaphore;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.util.ReflectionTestUtils;
-
-class AllSeemsWellTest extends IntegrityMonitorTestBase {
- private static final String ALL_SEEMS_WELL_MSG = "'AllSeemsWellTest - ALLSEEMSWELL'";
-
- private static Logger logger = LoggerFactory.getLogger(AllSeemsWellTest.class);
-
- private static String resourceName;
-
- private Properties myProp;
- private Semaphore monitorSem;
- private Semaphore junitSem;
-
- /**
- * Set up for test class.
- */
- @BeforeAll
- public static void setUpClass() throws Exception {
- IntegrityMonitorTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + AllSeemsWellTest.class.getSimpleName());
-
- resourceName = IntegrityMonitorTestBase.SITE_NAME + "." + IntegrityMonitorTestBase.NODE_TYPE;
- }
-
- @AfterAll
- public static void tearDownClass() {
- IntegrityMonitorTestBase.tearDownAfterClass();
- }
-
- /**
- * Set up for test cases.
- * @throws Exception if an error occurs
- */
- @BeforeEach
- public void setUp() throws Exception {
- super.setUpTest();
-
- myProp = makeProperties();
-
- monitorSem = new Semaphore(0);
- junitSem = new Semaphore(0);
-
- IntegrityMonitor im = new IntegrityMonitor(resourceName, myProp) {
-
- @Override
- protected void runStarted() throws InterruptedException {
- monitorSem.acquire();
-
- junitSem.release();
- monitorSem.acquire();
- }
-
- @Override
- protected void monitorCompleted() throws InterruptedException {
- junitSem.release();
- monitorSem.acquire();
- }
- };
-
- ReflectionTestUtils.setField(IntegrityMonitor.class, IM_INSTANCE_FIELD, im);
- }
-
- @AfterEach
- public void tearDown() {
- super.tearDownTest();
- }
-
- @Test
- void testAllSeemsWell() throws Exception {
- logger.debug("\nIntegrityMonitorTest: Entering testAllSeemsWell\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, "-1");
- myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "-1");
- myProp.put(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, "1");
-
- IntegrityMonitor.updateProperties(myProp);
-
- IntegrityMonitor im = IntegrityMonitor.getInstance(resourceName, myProp);
-
- StateManagement sm = im.getStateManager();
-
- // Give it time to set the states in the DB
- waitStateChange();
-
- // Check the state
- logger.debug(
- "\n\ntestAllSeemsWell starting im state \nAdminState = {}\nOpState() = {}\nAvailStatus = {}\n"
- + "StandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.ENABLED, sm.getOpState());
-
- // Indicate a failure
- im.allSeemsWell(this.getClass().getName(), IntegrityMonitorProperties.ALLNOTWELL,
- "'AllSeemsWellTest - ALLNOTWELL'");
-
- // Wait for the state to change due to ALLNOTWELL
- waitStateChange();
- // Check the state
- logger.debug(
- "\n\ntestAllSeemsWell after ALLNOTWELL: im state \nAdminState = {}\nOpState() = {}\nAvailStatus = "
- + "{}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- Map<String, String> allNotWellMap = im.getAllNotWellMap();
- if (logger.isDebugEnabled()) {
- for (Entry<String, String> ent : allNotWellMap.entrySet()) {
- logger.debug("AllSeemsWellTest: allNotWellMap: key = {} msg = {}", ent.getKey(), ent.getValue());
- }
- }
- assertEquals(1, allNotWellMap.size());
-
- assertTrue(im.getAllSeemsWellMap().isEmpty());
-
- // Return to normal
- im.allSeemsWell(this.getClass().getName(), IntegrityMonitorProperties.ALLSEEMSWELL,
- ALL_SEEMS_WELL_MSG);
-
- // Wait for the state to change due to ALLNOTWELL
- waitStateChange();
- // Check the state
- logger.debug(
- "\n\ntestAllSeemsWell after ALLSEEMSWELL: im state \nAdminState = {}\nOpState() = {}\nAvailStatus = "
- + "{}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.ENABLED, sm.getOpState());
-
- allNotWellMap = im.getAllNotWellMap();
- assertTrue(allNotWellMap.isEmpty());
-
- Map<String, String> allSeemsWellMap = im.getAllSeemsWellMap();
- assertEquals(1, allSeemsWellMap.size());
- if (logger.isDebugEnabled()) {
- for (Entry<String, String> ent : allSeemsWellMap.entrySet()) {
- logger.debug("AllSeemsWellTest: allSeemsWellMap: key = {} msg = {}", ent.getKey(), ent.getValue());
- }
- }
-
- // Check for null parameters
- assertThatIllegalArgumentException().isThrownBy(
- () -> im.allSeemsWell(null, IntegrityMonitorProperties.ALLSEEMSWELL, ALL_SEEMS_WELL_MSG));
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> im.allSeemsWell("", IntegrityMonitorProperties.ALLSEEMSWELL, ALL_SEEMS_WELL_MSG));
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> im.allSeemsWell(this.getClass().getName(), null, ALL_SEEMS_WELL_MSG));
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> im.allSeemsWell(this.getClass().getName(), IntegrityMonitorProperties.ALLSEEMSWELL, null));
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> im.allSeemsWell(this.getClass().getName(), IntegrityMonitorProperties.ALLSEEMSWELL, ""));
-
- logger.debug("\n\ntestAllSeemsWell: Exit\n\n");
- }
-
- /**
- * Waits for the state to change.
- *
- * @throws InterruptedException if the thread is interrupted
- */
- private void waitStateChange() throws InterruptedException {
- monitorSem.release();
- waitSem(junitSem);
- }
-
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/ExceptionsTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/ExceptionsTest.java
deleted file mode 100644
index ca7ef27d..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/ExceptionsTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.im.jmx.ComponentAdminException;
-import org.onap.policy.common.utils.test.ExceptionsTester;
-
-/**
- * Tests various Exception subclasses.
- */
-class ExceptionsTest extends ExceptionsTester {
-
- @Test
- void testStateTransitionException() {
- assertEquals(4, test(StateTransitionException.class));
- }
-
- @Test
- void testStateManagementException() {
- assertEquals(4, test(StateManagementException.class));
- }
-
- @Test
- void testStandbyStatusException() {
- assertEquals(5, test(StandbyStatusException.class));
- }
-
- @Test
- void testIntegrityMonitorPropertiesException() {
- assertEquals(4, test(IntegrityMonitorPropertiesException.class));
- }
-
- @Test
- void testIntegrityMonitorException() {
- assertEquals(5, test(IntegrityMonitorException.class));
- }
-
- @Test
- void testForwardProgressException() {
- assertEquals(4, test(ForwardProgressException.class));
- }
-
- @Test
- void testAllSeemsWellException() {
- assertEquals(4, test(AllSeemsWellException.class));
- }
-
- @Test
- void testAdministrativeStateException() {
- assertEquals(4, test(AdministrativeStateException.class));
- }
-
- @Test
- void testComponentAdminException() {
- assertEquals(4, test(ComponentAdminException.class));
- }
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTest.java
deleted file mode 100644
index f866df47..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTest.java
+++ /dev/null
@@ -1,982 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modificaitons Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import jakarta.persistence.EntityTransaction;
-import jakarta.persistence.Query;
-import jakarta.persistence.TemporalType;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.im.jpa.ForwardProgressEntity;
-import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
-import org.onap.policy.common.im.jpa.StateManagementEntity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.util.ReflectionTestUtils;
-
-/*
- * All JUnits are designed to run in the local development environment
- * where they have write privileges and can execute time-sensitive
- * tasks.
- */
-class IntegrityMonitorTest extends IntegrityMonitorTestBase {
- private static final String STANDBY_STATUS = "StandbyStatus = {}\n";
- private static final String RESTARTING_MSG = "\ntestSanityJmx restarting the IntegrityMonitor";
- private static final String FALSE_STRING = "false";
- private static final String GROUP1_DEP1 = "group1_dep1";
- private static final String RESOURCE = "resource";
- private static final String SITE_A_PAP2 = "siteA_pap2";
- private static final String SITE_B_PAP1 = "siteB_pap1";
- private static final String SITE_B_PAP2 = "siteB_pap2";
-
- private static final String ENABLE_NO_DEPENDENCY_MSG =
- """
-
-
- sm.enableNoDependency()
- AdminState = {}
- OpState() = {}
- AvailStatus = {}
- StandbyStatus = {}
- """;
-
- private static final Logger logger = LoggerFactory.getLogger(IntegrityMonitorTest.class);
-
- /**
- * Number of monitor cycles it takes between dependency health checks.
- */
- private static final int DEPENDENCY_CHECK_CYCLES = 6;
-
- private static String resourceName;
-
- private Properties myProp;
- private EntityTransaction et;
- private Semaphore monitorSem;
- private Semaphore junitSem;
-
- /**
- * Set up for test class.
- */
- @BeforeAll
- public static void setUpClass() throws Exception {
- IntegrityMonitorTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + IntegrityMonitorTest.class.getSimpleName());
-
- resourceName = IntegrityMonitorTestBase.SITE_NAME + "." + IntegrityMonitorTestBase.NODE_TYPE;
- }
-
- /**
- * Tear down after test class.
- */
- @AfterAll
- public static void tearDownClass() {
- IntegrityMonitorTestBase.tearDownAfterClass();
- }
-
- /**
- * Set up for test cases.
- */
- @BeforeEach
- public void setUp() {
- super.setUpTest();
-
- myProp = makeProperties();
- et = null;
- }
-
- /**
- * Tear down after test cases.
- */
- @AfterEach
- public void tearDown() {
- if (et != null && et.isActive()) {
- try {
- et.rollback();
-
- } catch (RuntimeException e) {
- logger.error("cannot rollback transaction", e);
- }
- }
-
- super.tearDownTest();
- }
-
- /*
- * 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
- */
- @Test
- void testSanityJmx() throws Exception {
- logger.debug("\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");
- // Disable the integrity monitor so it will not interfere
- myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "-1");
- // Disable the refresh state audit
- myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the state audit
- myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the test transaction
- myProp.put(IntegrityMonitorProperties.TEST_TRANS_INTERVAL, "-1");
- // Disable the write FPC
- myProp.put(IntegrityMonitorProperties.WRITE_FPC_INTERVAL, "-1");
- // Speed up the check
- myProp.put(IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, "1");
- // Fail dependencies after three seconds
- myProp.put(IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL, "3");
-
- IntegrityMonitor im = makeMonitor(resourceName, myProp);
- logger.debug(
- "\n\ntestSanityJmx starting im state \nAdminState = {}\nOpState() = {}\nAvailStatus = {}\n"
- + STANDBY_STATUS,
- im.getStateManager().getAdminState(), im.getStateManager().getOpState(),
- im.getStateManager().getAvailStatus(), im.getStateManager().getStandbyStatus());
- // 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
- logger.debug("Adding resource {} to ResourceRegistration table", dependent);
- 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();
-
- /*
- * wait for FPManager to perform dependency health check. Once that's done, it
- * should now be stale and the sanity check should fail
- */
- waitCycles(DEPENDENCY_CHECK_CYCLES);
-
- final IntegrityMonitor im2 = im;
- assertThatThrownBy(im2::evaluateSanity).isInstanceOf(IntegrityMonitorException.class);
-
- // undo dependency groups and jmx test properties settings
- myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "");
- myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, FALSE_STRING);
- IntegrityMonitor.updateProperties(myProp);
-
- logger.debug("\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.
-
- logger.debug(
- "\n\ntestSanityJmx ending im state\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\n"
- + STANDBY_STATUS,
- im.getStateManager().getAdminState(), im.getStateManager().getOpState(),
- im.getStateManager().getAvailStatus(), im.getStateManager().getStandbyStatus());
-
- logger.debug(RESTARTING_MSG);
- // Create a new instance. It should recover from the disabled-dependency
- // condition
- im = makeMonitor(resourceName, myProp);
-
- logger.debug(
- """
-
-
- testSanityJmx state after creating new im
- AdminState = {}
- OpState() = {}
- AvailStatus = {}
- StandbyStatus = {}
- """,
- im.getStateManager().getAdminState(), im.getStateManager().getOpState(),
- im.getStateManager().getAvailStatus(), im.getStateManager().getStandbyStatus());
-
- // Verify the state
- assertEquals(StateManagement.UNLOCKED, im.getStateManager().getAdminState());
- assertEquals(StateManagement.ENABLED, im.getStateManager().getOpState());
- assertEquals(StateManagement.NULL_VALUE, im.getStateManager().getAvailStatus());
- assertEquals(StateManagement.NULL_VALUE, im.getStateManager().getStandbyStatus());
-
- // Test state manager via the IntegrityMonitor
- StateManagement sm = im.getStateManager();
-
- // Verify lock state
- sm.lock();
- logger.debug("\n\nsm.lock()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
- assertEquals(StateManagement.LOCKED, sm.getAdminState());
-
- // Verify lock persists across a restart
- logger.debug(RESTARTING_MSG);
- // Create a new instance. It should come up with the admin state locked
- im = makeMonitor(resourceName, myProp);
- sm = im.getStateManager();
- logger.debug(
- """
-
-
- testSanityJmx restart with AdminState=locked
- AdminState = {}
- OpState() = {}
- AvailStatus = {}
- StandbyStatus = {}
- """,
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
- assertEquals(StateManagement.LOCKED, sm.getAdminState());
-
- // Verify unlock
- sm.unlock();
- logger.debug(
- "\n\ntestSanityJmx sm.unlock\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
- assertEquals(StateManagement.UNLOCKED, sm.getAdminState());
-
- // Verify unlock restart
- logger.debug(RESTARTING_MSG);
- // Create a new instance. It should come up with the admin state locked
- im = makeMonitor(resourceName, myProp);
- sm = im.getStateManager();
- logger.debug(
- """
-
-
- testSanityJmx restart with AdminState=unlocked
- AdminState = {}
- OpState() = {}
- AvailStatus = {}
- StandbyStatus = {}
- """,
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.UNLOCKED, sm.getAdminState());
-
- logger.debug("\n\ntestSanityJmx: Exit\n\n");
- }
-
- @Test
- void testIm() throws Exception {
- logger.debug("\nIntegrityMonitorTest: Entering testIM\n\n");
-
- // Disable the integrity monitor so it will not interfere
- myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "-1");
- // Disable dependency checking
- myProp.put(IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, "-1");
- // Disable the refresh state audit
- myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the state audit
- myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the test transaction
- myProp.put(IntegrityMonitorProperties.TEST_TRANS_INTERVAL, "-1");
- // Disable writing the FPC
- myProp.put(IntegrityMonitorProperties.WRITE_FPC_INTERVAL, "-1");
-
- IntegrityMonitor im = makeMonitor(resourceName, myProp);
-
- logger.debug("\n\nim initial state: \nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- im.getStateManager().getAdminState(), im.getStateManager().getOpState(),
- im.getStateManager().getAvailStatus(), im.getStateManager().getStandbyStatus());
-
- waitCycles(1);
-
- // test evaluate sanity
- im.evaluateSanity();
-
- // Test startTransaction - should work since it is unlocked
- im.startTransaction();
-
- // Test state manager via the IntegrityMonitor
- StateManagement sm = im.getStateManager();
-
- sm.lock();
-
- logger.debug("\n\nsm.lock()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.LOCKED, sm.getAdminState());
-
- // test startTransaction. It should fail since it is locked
- assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
-
- sm.unlock();
- logger.debug("\n\nsm.unlock()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
- assertEquals(StateManagement.UNLOCKED, sm.getAdminState());
-
- // test startTransaction. It should succeed
- im.startTransaction();
-
- sm.disableDependency();
- logger.debug(
- "\n\nsm.disableDependency()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.DISABLED, sm.getOpState());
- assertEquals(StateManagement.DEPENDENCY, sm.getAvailStatus());
-
- // test startTransaction. It should succeed since standby status is null
- // and unlocked
- im.startTransaction();
-
- sm.enableNoDependency();
-
- logger.debug(
- ENABLE_NO_DEPENDENCY_MSG,
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
- assertEquals(StateManagement.ENABLED, sm.getOpState());
- // test startTransaction. It should succeed since standby status is null
- // and unlocked
- im.startTransaction();
-
- sm.disableFailed();
- logger.debug("\n\nsm.disableFailed()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.DISABLED, sm.getOpState());
- assertEquals(StateManagement.FAILED, sm.getAvailStatus());
- // test startTransaction. It should succeed since standby status is null
- // and unlocked
- im.startTransaction();
-
- sm.enableNotFailed();
-
- logger.debug(
- "\n\nsm.enabledNotFailed()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.ENABLED, sm.getOpState());
- // test startTransaction. It should succeed since standby status is null
- // and unlocked
- im.startTransaction();
-
- sm.demote();
-
- logger.debug("\n\nsm.demote()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.HOT_STANDBY, sm.getStandbyStatus());
-
- // test startTransaction. It should fail since it is standby
- assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
-
- sm.promote();
-
- logger.debug("\n\nsm.promote()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\nStandbyStatus = {}\n",
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.PROVIDING_SERVICE, sm.getStandbyStatus());
-
- // test startTransaction. It should succeed since it is providing
- // service
- im.startTransaction();
-
- // Test the multi-valued availability status
- sm.disableDependency();
- sm.disableFailed();
-
- logger.debug(
- "\n\nsm.disableDependency(), sm.disableFailed\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\n"
- + STANDBY_STATUS,
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.DEPENDENCY_FAILED, sm.getAvailStatus());
-
- // Test startTransaction. Should fail since standby status is cold
- // standby
- assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
-
- sm.enableNoDependency();
-
- logger.debug(
- ENABLE_NO_DEPENDENCY_MSG,
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
- assertEquals(StateManagement.FAILED, sm.getAvailStatus());
- // Test startTransaction. Should fail since standby status is cold
- // standby
- assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
-
- sm.disableDependency();
- sm.enableNotFailed();
-
- logger.debug(
- "\n\nsm.disableDependency(),sm.enableNotFailed()\nAdminState = {}\nOpState() = {}\nAvailStatus = {}\n"
- + STANDBY_STATUS,
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
-
- assertEquals(StateManagement.DEPENDENCY, sm.getAvailStatus());
- // Test startTransaction. Should fail since standby status is cold
- // standby
- assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
-
- sm.enableNoDependency();
- logger.debug(
- ENABLE_NO_DEPENDENCY_MSG,
- sm.getAdminState(), sm.getOpState(), sm.getAvailStatus(), sm.getStandbyStatus());
- assertEquals(StateManagement.ENABLED, sm.getOpState());
- // test startTransaction. It should fail since standby status is hot
- // standby
- assertThatThrownBy(im::startTransaction).isInstanceOf(IntegrityMonitorException.class);
-
- logger.debug("\n\ntestIM: Exit\n\n");
- }
-
- @Test
- void testSanityState() throws Exception {
- logger.debug("\nIntegrityMonitorTest: Entering testSanityState\n\n");
-
- // parameters are passed via a properties file
- myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "group1_dep1,group1_dep2; group2_dep1");
- // Disable the integrity monitor so it will not interfere
- myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "-1");
- // Disable the refresh state audit
- myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable dependency checking so it does not interfere
- myProp.put(IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, "-1");
- // Disable the state audit
- myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the test transaction
- myProp.put(IntegrityMonitorProperties.TEST_TRANS_INTERVAL, "-1");
- // Disable writing the FPC
- myProp.put(IntegrityMonitorProperties.WRITE_FPC_INTERVAL, "-1");
- // Max interval for use in deciding if a FPC entry is stale in seconds
- myProp.put(IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL, "120");
-
- final IntegrityMonitor im = makeMonitor(resourceName, myProp);
-
- waitCycles(1);
-
- // 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");
-
- // Call the dependency check directly instead of waiting for FPManager
- // to do it.
- logger.debug("\n\nIntegrityMonitor.testSanityState: calling im.dependencyCheck()\n\n");
- im.dependencyCheck();
- assertThatThrownBy(im::evaluateSanity).isInstanceOf(IntegrityMonitorException.class);
-
- logger.debug("\n\ntestSanityState: Exit\n\n");
- }
-
- @Test
- 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_STRING);
- // Disable the integrity monitor so it will not interfere
- myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "-1");
- // Disable the refresh state audit
- myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable dependency checking so it does not interfere
- myProp.put(IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, "-1");
- // Disable the state audit
- myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the test transaction
- myProp.put(IntegrityMonitorProperties.TEST_TRANS_INTERVAL, "-1");
- // Disable writing the FPC
- myProp.put(IntegrityMonitorProperties.WRITE_FPC_INTERVAL, "-1");
-
- final IntegrityMonitor im = makeMonitor(resourceName, myProp);
-
- waitCycles(1);
-
- // 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()) {
- logger.debug("Record not found, resourceName: {}", resourceName);
- fail("missing record");
- }
-
- // exist
- sme = (StateManagementEntity) resourceList.get(0);
- em.refresh(sme);
-
- logger.debug(
- """
- ??? -- Retrieve StateManagementEntity from database --
- sme.getResourceName() = {}
- sme.getAdminState() = {}
- sme.getOpState() = {}
- sme.getAvailStatus() = {}
- sme.getStandbyStatus() = {}""",
- sme.getResourceName(), sme.getAdminState(), sme.getOpState(), sme.getAvailStatus(),
- sme.getStandbyStatus());
-
- assertEquals(StateManagement.UNLOCKED, sme.getAdminState());
- assertEquals(StateManagement.ENABLED, sme.getOpState());
- assertEquals(StateManagement.NULL_VALUE, sme.getAvailStatus());
- assertEquals(StateManagement.NULL_VALUE, sme.getStandbyStatus());
- logger.debug("--");
-
- et = em.getTransaction();
- et.begin();
-
- sme.setStandbyStatus(StateManagement.COLD_STANDBY);
- em.persist(sme);
- em.flush();
- et.commit();
-
- // Run the refreshStateAudit
- im.executeRefreshStateAudit();
-
- // 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);
-
- @SuppressWarnings("rawtypes")
- List resourceList1 = query1.getResultList();
- if (!resourceList1.isEmpty()) {
- // exist
- sme1 = (StateManagementEntity) resourceList1.get(0);
- em.refresh(sme1);
- logger.debug(
- """
- ??? -- Retrieve StateManagementEntity from database --
- sme1.getResourceName() = {}
- sme1.getAdminState() = {}
- sme1.getOpState() = {}
- sme1.getAvailStatus() = {}
- sme1.getStandbyStatus() = {}""",
- sme1.getResourceName(), sme1.getAdminState(), sme1.getOpState(), sme1.getAvailStatus(),
- sme1.getStandbyStatus());
-
- assertEquals(StateManagement.UNLOCKED, sme1.getAdminState());
- assertEquals(StateManagement.ENABLED, sme1.getOpState());
- assertEquals(StateManagement.NULL_VALUE, sme1.getAvailStatus());
- assertEquals(StateManagement.HOT_STANDBY, sme1.getStandbyStatus());
- logger.debug("--");
- } else {
- logger.debug("Record not found, resourceName: {}", resourceName);
- fail("record not found");
- }
-
- logger.debug("\nIntegrityMonitorTest: testRefreshStateAudit Exit\n\n");
- }
-
- @Test
- void testStateCheck() throws Exception {
- logger.debug("\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_STRING);
- myProp.put(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, "1");
- /*
- * The monitorInterval is set to 10 and the failedCounterThreshold is 1 because stateCheck()
- * uses the faileCounterThreshold * monitorInterval to determine if an entry is stale, it
- * will be stale after 10 seconds.
- */
- myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "5");
- /*
- * We accelerate the test transaction and write FPC intervals because we don't want there to
- * be any chance of a FPC failure because of the short monitor interval
- */
- myProp.put(IntegrityMonitorProperties.TEST_TRANS_INTERVAL, "1");
- myProp.put(IntegrityMonitorProperties.WRITE_FPC_INTERVAL, "2");
- // Disable the refresh state audit
- myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "-1");
- // The maximum time in seconds to determine that a FPC entry is stale
- myProp.put(IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL, "5");
- myProp.put(IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, "5");
-
- // Note: do ***NOT*** do waitStep() here
-
- // 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);
-
- IntegrityMonitor im = makeMonitor(resourceName, myProp);
-
- im.evaluateSanity();
-
- /*
- * wait for FPManager to perform dependency health check. Once that's done, it
- * should now be stale and the sanity check should fail
- */
- waitCycles(DEPENDENCY_CHECK_CYCLES);
-
- assertThatThrownBy(im::evaluateSanity).isInstanceOf(IntegrityMonitorException.class);
-
- logger.debug("\n\ntestStateCheck: Exit\n\n");
- }
-
- @Test
- void testGetAllForwardProgressEntity() throws Exception {
- logger.debug("\nIntegrityMonitorTest: Entering testGetAllForwardProgressEntity\n\n");
- // parameters are passed via a properties file
- myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "");
- myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, FALSE_STRING);
- // Disable the integrity monitor so it will not interfere
- myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "-1");
- // Disable the refresh state audit
- myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable dependency checking so it does not interfere
- myProp.put(IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, "-1");
- // Disable the state audit
- myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the test transaction
- myProp.put(IntegrityMonitorProperties.TEST_TRANS_INTERVAL, "-1");
- // Disable writing the FPC
- myProp.put(IntegrityMonitorProperties.WRITE_FPC_INTERVAL, "-1");
-
- final IntegrityMonitor im = makeMonitor(resourceName, myProp);
- waitCycles(1);
-
- logger.debug("\nIntegrityMonitorTest: Creating ForwardProgressEntity entries\n\n");
- // Add resource entries in the forward progress table
- final ForwardProgressEntity fpe = new ForwardProgressEntity();
- final ForwardProgressEntity fpe2 = new ForwardProgressEntity();
- final ForwardProgressEntity fpe3 = new ForwardProgressEntity();
- fpe.setFpcCount(0);
- fpe.setResourceName(SITE_A_PAP2);
- fpe2.setFpcCount(0);
- fpe2.setResourceName(SITE_B_PAP1);
- fpe3.setFpcCount(0);
- fpe3.setResourceName(SITE_B_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");
- List<ForwardProgressEntity> fpeList = im.getAllForwardProgressEntity();
-
- assertEquals(4, fpeList.size());
-
- logger.debug("\nIntegrityMonitorTest: Exit testGetAllForwardProgressEntity\n\n");
- }
-
- @Test
- void testStateAudit() throws Exception {
- logger.debug("\nIntegrityMonitorTest: Entering testStateAudit\n\n");
-
- // parameters are passed via a properties file
-
- // No Dependency Groups
- myProp.put(IntegrityMonitorProperties.DEPENDENCY_GROUPS, "");
- // Don't use JMX
- myProp.put(IntegrityMonitorProperties.TEST_VIA_JMX, FALSE_STRING);
- // Disable the internal sanity monitoring.
- myProp.put(IntegrityMonitorProperties.FP_MONITOR_INTERVAL, "-1");
- // Disable the dependency monitoring.
- myProp.put(IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL, "-1");
- // Disable the refresh state audit
- myProp.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS, "-1");
- // Disable the test transaction
- myProp.put(IntegrityMonitorProperties.TEST_TRANS_INTERVAL, "-1");
- // Disable the write FPC
- myProp.put(IntegrityMonitorProperties.WRITE_FPC_INTERVAL, "-1");
- // Disable the State Audit we will call it directly
- myProp.put(IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, "-1");
- // Max interval for use in deciding if a FPC entry is stale in seconds
- myProp.put(IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL, "120");
-
- final IntegrityMonitor im = makeMonitor(resourceName, myProp);
- waitCycles(1);
-
- logger.debug("\nIntegrityMonitorTest: Creating ForwardProgressEntity entries\n\n");
- // Add resources to put an entry in the forward progress table
- final Date staleDate = new Date(0);
- final ForwardProgressEntity fpe1 = new ForwardProgressEntity();
- final ForwardProgressEntity fpe2 = new ForwardProgressEntity();
- final ForwardProgressEntity fpe3 = new ForwardProgressEntity();
- fpe1.setFpcCount(0);
- fpe1.setResourceName(SITE_A_PAP2);
- fpe2.setFpcCount(0);
- fpe2.setResourceName(SITE_B_PAP1);
- fpe3.setFpcCount(0);
- fpe3.setResourceName(SITE_B_PAP2);
- logger.debug("\nIntegrityMonitorTest: Creating StateManagementEntity entries\n\n");
- final StateManagementEntity sme1 = new StateManagementEntity();
- final StateManagementEntity sme2 = new StateManagementEntity();
- final StateManagementEntity sme3 = new StateManagementEntity();
- sme1.setResourceName(SITE_A_PAP2);
- sme1.setAdminState(StateManagement.UNLOCKED);
- sme1.setOpState(StateManagement.ENABLED);
- sme1.setAvailStatus(StateManagement.NULL_VALUE);
- sme1.setStandbyStatus(StateManagement.NULL_VALUE);
- sme2.setResourceName(SITE_B_PAP1);
- sme2.setAdminState(StateManagement.UNLOCKED);
- sme2.setOpState(StateManagement.ENABLED);
- sme2.setAvailStatus(StateManagement.NULL_VALUE);
- sme2.setStandbyStatus(StateManagement.NULL_VALUE);
- sme3.setResourceName(SITE_B_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");
- List<ForwardProgressEntity> fpeList = im.getAllForwardProgressEntity();
-
- logger.debug("\n\n");
- logger.debug("IntegrityMonitorTest:testStateAudit:ForwardProgressEntity entries");
- for (ForwardProgressEntity myFpe : fpeList) {
- logger.debug("\n ResourceName: {}\n LastUpdated: {}", myFpe.getResourceName(),
- 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(
- """
-
- ResourceName: {}
- AdminState: {}
- OpState: {}
- AvailStatus: {}
- StandbyStatus: {}\
- """,
- tmpSme.getResourceName(), tmpSme.getAdminState(), tmpSme.getOpState(), tmpSme.getAvailStatus(),
- tmpSme.getStandbyStatus());
- }
- logger.debug("\n\n");
-
- em.refresh(sme1);
- assertEquals(StateManagement.ENABLED, sme1.getOpState());
-
- logger.debug("IntegrityMonitorTest:testStateAudit: calling stateAudit()");
- im.executeStateAudit();
- logger.debug("IntegrityMonitorTest:testStateAudit: call to stateAudit() complete");
-
- 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(
- """
-
- ResourceName: {}
- AdminState: {}
- OpState: {}
- AvailStatus: {}
- StandbyStatus: {}\
- """,
- tmpSme.getResourceName(), tmpSme.getAdminState(), tmpSme.getOpState(), tmpSme.getAvailStatus(),
- tmpSme.getStandbyStatus());
- }
- logger.debug("\n\n");
-
- em.refresh(sme1);
- assertEquals(StateManagement.DISABLED, sme1.getOpState());
-
- // 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();
-
- // Give it a chance to write the DB and run the audit
- logger.debug("IntegrityMonitorTest:testStateAudit: (restart4) Running State Audit");
- waitCycles(1);
- im.executeStateAudit();
- waitCycles(1);
- logger.debug("IntegrityMonitorTest:testStateAudit: (restart4) State Audit complete");
-
- // 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(
- """
-
- (restart4) ResourceName: {}
- AdminState: {}
- OpState: {}
- AvailStatus: {}
- StandbyStatus: {}\
- """,
- tmpSme.getResourceName(), tmpSme.getAdminState(), tmpSme.getOpState(), tmpSme.getAvailStatus(),
- tmpSme.getStandbyStatus());
- }
- logger.debug("\n\n");
-
- em.refresh(sme1);
- assertEquals(StateManagement.DISABLED, sme1.getOpState());
-
- em.refresh(sme2);
- assertEquals(StateManagement.DISABLED, sme2.getOpState());
-
- logger.info("\n\ntestStateAudit: Exit\n\n");
- }
-
- private IntegrityMonitor makeMonitor(String resourceName, Properties myProp) throws Exception {
- IntegrityMonitor.deleteInstance();
-
- monitorSem = new Semaphore(0);
- junitSem = new Semaphore(0);
-
- IntegrityMonitor im = new IntegrityMonitor(resourceName, myProp) {
-
- @Override
- protected void runStarted() throws InterruptedException {
- monitorSem.acquire();
-
- junitSem.release();
- monitorSem.acquire();
- }
-
- @Override
- protected void monitorCompleted() throws InterruptedException {
- junitSem.release();
- monitorSem.acquire();
- }
- };
-
- ReflectionTestUtils.setField(IntegrityMonitor.class, IM_INSTANCE_FIELD, im);
-
- // wait for the monitor thread to start
- waitCycles(1);
-
- return im;
- }
-
- /**
- * Waits for several monitor cycles to complete.
- * @param ncycles number of cycles to wait
- *
- * @throws InterruptedException if the thread is interrupted
- */
- private void waitCycles(int ncycles) throws InterruptedException {
- monitorSem.release(ncycles);
- junitSem.tryAcquire(ncycles, WAIT_MS, TimeUnit.MILLISECONDS);
- }
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTestBase.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTestBase.java
deleted file mode 100644
index eeb34be5..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTestBase.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
- * Modificaitons Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.Persistence;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Properties;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import org.onap.policy.common.utils.jpa.EntityTransCloser;
-import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
-import org.onap.policy.common.utils.time.CurrentTime;
-import org.onap.policy.common.utils.time.TestTime;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.util.ReflectionTestUtils;
-
-/**
- * All JUnits are designed to run in the local development environment where they have write
- * privileges and can execute time-sensitive tasks. <p/> Many of the test verification steps are
- * performed by scanning for items written to the log file. Rather than actually scan the log file,
- * an {@link ExtractAppender} is used to monitor events that are logged and extract relevant items.
- * In order to attach the appender to the debug log, it assumes that the debug log is a
- * <i>logback</i> Logger configured per EELF. <p/> These tests use a temporary, in-memory DB, which
- * is dropped once the tests complete.
- */
-public class IntegrityMonitorTestBase {
- private static Logger logger = LoggerFactory.getLogger(IntegrityMonitorTestBase.class);
-
- /**
- * Name of the instance field within the IntegrityMonitor class.
- */
- public static final String IM_INSTANCE_FIELD = "instance";
-
- /**
- * Name of the instance field within the MonitorTime class.
- */
- public static final String TIME_INSTANCE_FIELD = "instance";
-
- /**
- * Directory containing the slf4j log files.
- */
- private static final String SLF4J_LOG_DIR = "logs";
-
- private static final String JMX_PORT_PROP = "com.sun.management.jmxremote.port";
-
- /**
- * Max time, in milliseconds, to wait for a latch to be triggered.
- */
- protected static final long WAIT_MS = 5000L;
-
- /**
- * Milliseconds between state refreshes.
- */
- protected static final long REFRESH_INTERVAL_MS = 3L * IntegrityMonitor.CYCLE_INTERVAL_MILLIS;
-
- public static final String DEFAULT_DB_URL_PREFIX = "jdbc:h2:mem:";
-
- protected static final String DB_DRIVER = "org.h2.Driver";
- protected static final String DB_USER = "testu";
- protected static final String DB_PASS = "testp";
- protected static final String SITE_NAME = "SiteA";
- protected static final String NODE_TYPE = "pap";
-
- // will be defined by the test *Classes*
- protected static String dbUrl;
-
- /**
- * Persistence unit.
- */
- protected static final String PERSISTENCE_UNIT = "schemaPU";
-
- /**
- * Properties to be used in all tests.
- */
- protected static Properties properties;
-
- /**
- * Entity manager factory pointing to the in-memory DB for A_SEQ_PU.
- */
- protected static EntityManagerFactory emf;
-
- /**
- * Entity manager factory pointing to the in-memory DB associated with emf.
- */
- protected static EntityManager em;
-
- /**
- * Test time used by tests in lieu of CurrentTime.
- */
- private static TestTime testTime;
-
- /**
- * Saved JMX port from system properties, to be restored once all tests complete.
- */
- private static Object savedJmxPort;
-
- /**
- * Saved time accessor, to be restored once all tests complete.
- */
- private static CurrentTime savedTime;
-
-
- /**
- * Saves current configuration information and then sets new values.
- *
- * @param dbUrl the URL to the DB
- * @throws IOException if an IO error occurs
- */
- protected static void setUpBeforeClass(String dbUrl) throws IOException {
- logger.info("setup");
-
- final Properties systemProps = System.getProperties();
-
- // truncate the logs
- new FileOutputStream(SLF4J_LOG_DIR + "/audit.log").close();
- new FileOutputStream(SLF4J_LOG_DIR + "/debug.log").close();
- new FileOutputStream(SLF4J_LOG_DIR + "/error.log").close();
- new FileOutputStream(SLF4J_LOG_DIR + "/metrics.log").close();
-
- IntegrityMonitorTestBase.dbUrl = dbUrl;
-
- // save data that we have to restore at the end of the test
- savedJmxPort = systemProps.get(JMX_PORT_PROP);
- savedTime = MonitorTime.getInstance();
-
- systemProps.put(JMX_PORT_PROP, "9797");
-
- IntegrityMonitor.setUnitTesting(true);
-
- testTime = new TestTime();
- ReflectionTestUtils.setField(MonitorTime.class, TIME_INSTANCE_FIELD, testTime);
-
- properties = new Properties();
- properties.put(IntegrityMonitorProperties.DB_DRIVER, DB_DRIVER);
- properties.put(IntegrityMonitorProperties.DB_URL, dbUrl);
- properties.put(IntegrityMonitorProperties.DB_USER, DB_USER);
- properties.put(IntegrityMonitorProperties.DB_PWD, DB_PASS);
- properties.put(IntegrityMonitorProperties.SITE_NAME, SITE_NAME);
- properties.put(IntegrityMonitorProperties.NODE_TYPE, NODE_TYPE);
- properties.put(IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS,
- String.valueOf(REFRESH_INTERVAL_MS));
-
- emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, makeProperties());
-
- // keep this open so the in-memory DB stays around until all tests are
- // done
- em = emf.createEntityManager();
-
- stopMonitor();
- }
-
- /**
- * Restores the configuration to what it was before the test.
- */
- protected static void tearDownAfterClass() {
- Properties systemProps = System.getProperties();
- if (savedJmxPort == null) {
- systemProps.remove(JMX_PORT_PROP);
-
- } else {
- systemProps.put(JMX_PORT_PROP, savedJmxPort);
- }
-
- ReflectionTestUtils.setField(MonitorTime.class, TIME_INSTANCE_FIELD, savedTime);
-
- IntegrityMonitor.setUnitTesting(false);
-
- stopMonitor();
-
- // this should result in the in-memory DB being deleted
- em.close();
- emf.close();
- }
-
- /**
- * Sets up for a test, which includes deleting all records from the IntegrityAuditEntity table.
- */
- protected void setUpTest() {
-
- // Clean up the DB
- try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) {
-
- em.createQuery("Delete from StateManagementEntity").executeUpdate();
- em.createQuery("Delete from ForwardProgressEntity").executeUpdate();
- em.createQuery("Delete from ResourceRegistrationEntity").executeUpdate();
-
- // commit transaction
- et.commit();
- }
- }
-
- /**
- * Cleans up after a test, removing any ExtractAppenders from the logger and stopping any
- * AuditThreads.
- */
- protected void tearDownTest() {
- stopMonitor();
- }
-
- /**
- * Stops the IntegrityMonitor instance.
- */
- private static void stopMonitor() {
- try {
- IntegrityMonitor.deleteInstance();
-
- } catch (IntegrityMonitorException e) {
- // no need to log, as exception was already logged
- logger.debug("stopMonitor failed", e);
- }
- }
-
- /**
- * Get current test time.
- *
- * @return the "current" time, in milliseconds
- */
- protected static long getCurrentTestTime() {
- return testTime.getMillis();
- }
-
- /**
- * Makes a new Property set that's a clone of {@link #properties}.
- *
- * @return a new Property set containing all of a copy of all of the {@link #properties}
- */
- protected static Properties makeProperties() {
- Properties props = new Properties();
- props.putAll(properties);
- return props;
- }
-
- /**
- * Waits for a semaphore to be acquired.
- *
- * @param sem semaphore to wait on
- * @throws InterruptedException if the thread is interrupted
- * @throws AssertionError if the semaphore was not acquired within the allotted time
- */
- protected void waitSem(Semaphore sem) throws InterruptedException {
- assertTrue(sem.tryAcquire(WAIT_MS, TimeUnit.MILLISECONDS));
- }
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/MonitorTimeTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/MonitorTimeTest.java
deleted file mode 100644
index a8baae40..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/MonitorTimeTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.utils.time.CurrentTime;
-
-/**
- * Class that tests MonitorTime.
- */
-class MonitorTimeTest {
-
- @Test
- void testGetInstance() {
- CurrentTime inst = MonitorTime.getInstance();
- assertNotNull(inst);
-
- assertEquals(inst, MonitorTime.getInstance());
- }
-
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateChangeNotifierTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/StateChangeNotifierTest.java
deleted file mode 100644
index 8a71d45a..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateChangeNotifierTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertSame;
-import static org.mockito.Mockito.mock;
-
-import org.junit.jupiter.api.Test;
-
-class StateChangeNotifierTest {
- private static final String MESSAGE = "my message";
-
- private StateChangeNotifier scn;
- private StateManagement sm;
-
- @Test
- void test() {
- sm = mock(StateManagement.class);
- scn = new StateChangeNotifier();
-
- scn.update(sm, MESSAGE);
-
- scn.handleStateChange();
-
- assertSame(sm, scn.getStateManagement());
- assertEquals(MESSAGE, scn.getMessage());
- }
-
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementEntityTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementEntityTest.java
deleted file mode 100644
index 266b3221..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementEntityTest.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import jakarta.persistence.Query;
-import java.util.List;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.im.jpa.StateManagementEntity;
-import org.onap.policy.common.utils.jpa.EntityTransCloser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class StateManagementEntityTest extends IntegrityMonitorTestBase {
- private static final Logger logger = LoggerFactory.getLogger(StateManagementEntityTest.class);
-
- /**
- * Set up for the test class.
- */
- @BeforeAll
- public static void setUpClass() throws Exception {
- IntegrityMonitorTestBase
- .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + StateManagementEntityTest.class.getSimpleName());
-
- }
-
- /**
- * Tear down after the test class.
- */
- @AfterAll
- public static void tearDownClass() {
- IntegrityMonitorTestBase.tearDownAfterClass();
- }
-
- /**
- * Set up for the test cases.
- */
- @BeforeEach
- public void setUp() {
- super.setUpTest();
- }
-
- /**
- * Tear down after the test cases.
- */
- @AfterEach
- public void tearDown() {
- super.tearDownTest();
- }
-
- @Test
- void testJpa() {
- logger.debug("\n??? logger.infor StateManagementEntityTest: Entering\n\n");
-
- // Define the resourceName for the StateManagement constructor
- String resourceName = "test_resource1";
-
- //
- logger.debug("Create StateManagementEntity, resourceName: {}", resourceName);
- logger.debug("??? instantiate StateManagementEntity object");
- StateManagementEntity sme = new StateManagementEntity();
-
- logger.debug("??? setResourceName : {}", resourceName);
- sme.setResourceName(resourceName);
- logger.debug("??? getResourceName : {}", sme.getResourceName());
-
- sme.setAdminState(StateManagement.UNLOCKED);
- assertEquals(StateManagement.UNLOCKED, sme.getAdminState());
-
- sme.setOpState(StateManagement.ENABLED);
- assertEquals(StateManagement.ENABLED, sme.getOpState());
-
- sme.setAvailStatus(StateManagement.NULL_VALUE);
- assertEquals(StateManagement.NULL_VALUE, sme.getAvailStatus());
-
- sme.setStandbyStatus(StateManagement.COLD_STANDBY);
- assertEquals(StateManagement.COLD_STANDBY, sme.getStandbyStatus());
-
- try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) {
- logger.debug("??? before persist");
- em.persist(sme);
- logger.debug("??? after persist");
-
- em.flush();
- logger.debug("??? after flush");
-
- et.commit();
- logger.debug("??? after commit");
- }
-
- 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);
-
- assertEquals(sme.getResourceName(), sme2.getResourceName());
- assertEquals(sme.getAdminState(), sme2.getAdminState());
- assertEquals(sme.getOpState(), sme2.getOpState());
- assertEquals(sme.getAvailStatus(), sme2.getAvailStatus());
- assertEquals(sme.getStandbyStatus(), sme2.getStandbyStatus());
- logger.debug("--");
- } else {
- logger.debug("Record not found, resourceName: {}", resourceName);
- }
-
- logger.debug("\n\nJpaTest: Exit\n\n");
- }
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementTest.java
deleted file mode 100644
index 5dfd01f3..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementTest.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
- * Modifications Copyright (C) 2023-2024 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.EntityTransaction;
-import jakarta.persistence.PersistenceException;
-import jakarta.persistence.QueryTimeoutException;
-import jakarta.persistence.TypedQuery;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.mockito.Mockito;
-import org.onap.policy.common.im.jpa.StateManagementEntity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/*
- * All JUnits are designed to run in the local development environment where they have write
- * privileges and can execute time-sensitive tasks.
- */
-class StateManagementTest extends IntegrityMonitorTestBase {
- private static final String LOCKED_DISABLED_FAILED_COLDSTANDBY = "locked,disabled,failed,coldstandby";
- private static final String UNLOCKED_DISABLED_FAILED_COLDSTANDBY = "unlocked,disabled,failed,coldstandby";
- private static final String UNLOCKED_ENABLED_NULL_HOTSTANDBY = "unlocked,enabled,null,hotstandby";
- private static final String UNLOCKED_ENABLED_NULL_NULL = "unlocked,enabled,null,null";
- private static final String UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE = "unlocked,enabled,null,providingservice";
- private static final String TEST_RESOURCE_NAME = "test_resource1";
-
- private static final Logger logger = LoggerFactory.getLogger(StateManagementTest.class);
- //
-
- @BeforeAll
- public static void setUpClass() throws Exception {
- IntegrityMonitorTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + StateManagementTest.class.getSimpleName());
-
- }
-
- @AfterAll
- public static void tearDownClass() {
- IntegrityMonitorTestBase.tearDownAfterClass();
- }
-
- @BeforeEach
- public void setUp() {
- super.setUpTest();
- }
-
- @AfterEach
- public void tearDown() {
- super.tearDownTest();
- }
-
- @Test
- void test() throws Exception {
- logger.info("\n\nlogger.infor StateManagementTest: Entering\n\n");
-
- // These parameters are in a properties file
- try {
- final StateManagement sm = new StateManagement(emf, TEST_RESOURCE_NAME);
- test_1(sm);
- test_2(sm);
- } catch (final Exception ex) {
- logger.error("Exception: {}", ex.toString());
- throw ex;
- }
-
- logger.info("\n\nStateManagementTest: Exit\n\n");
- }
-
- private void test_1(final StateManagement sm) throws IntegrityMonitorException {
- logger.info("\n??? initial state");
- assertEquals(UNLOCKED_ENABLED_NULL_NULL, makeString(sm));
-
- logger.info("\n??? test lock()");
- sm.lock();
- assertEquals("locked,enabled,null,null", makeString(sm));
-
- logger.info("\n??? test unlock()");
- sm.unlock();
- assertEquals(UNLOCKED_ENABLED_NULL_NULL, makeString(sm));
-
- logger.info("\n??? test enableNotFailed()");
- sm.enableNotFailed();
- assertEquals(UNLOCKED_ENABLED_NULL_NULL, makeString(sm));
-
- logger.info("\n??? test disableFailed()");
- sm.disableFailed();
- assertEquals("unlocked,disabled,failed,null", makeString(sm));
-
- // 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");
- sm.disableFailed();
- sm.lock();
- assertThatThrownBy(sm::promote).isInstanceOf(IntegrityMonitorException.class);
-
- assertEquals(LOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(sm));
-
- // 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");
- assertThatThrownBy(sm::promote).isInstanceOf(IntegrityMonitorException.class);
- assertEquals(LOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(sm));
-
- // 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");
- final StateManagement sm2 = new StateManagement(emf, "test_resource2");
- sm2.enableNotFailed();
- sm2.unlock();
- assertEquals(UNLOCKED_ENABLED_NULL_NULL, makeString(sm2));
- sm2.promote();
- assertEquals(UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE, makeString(sm2));
-
- // P5 If promote() is called while standbyStatus is
- // providingservice, no action is taken
- logger.info("\n??? promote() test case P5");
- sm2.promote();
- assertEquals(UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE, makeString(sm2));
-
- // D1 If demote() is called while standbyStatus is providingservice,
- // the state shall transition to hotstandby
- logger.info("\n??? demote() test case D1");
- sm2.demote();
- assertEquals(UNLOCKED_ENABLED_NULL_HOTSTANDBY, makeString(sm2));
-
- // D4 If demote() is called while standbyStatus is hotstandby, no
- // action is taken
- logger.info("\n??? demote() test case D4");
- sm2.demote();
- assertEquals(UNLOCKED_ENABLED_NULL_HOTSTANDBY, makeString(sm2));
- }
-
- private void test_2(final StateManagement sm) throws IntegrityMonitorException {
- // 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");
- final StateManagement sm3 = new StateManagement(emf, "test_resource3");
- sm3.lock();
- sm3.disableFailed();
- sm3.demote();
- assertEquals(LOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(sm3));
-
- // D5 If demote() is called while standbyStatus is coldstandby, no
- // action is taken
- logger.info("\n??? demote() test case D5");
- sm3.demote();
- assertEquals(LOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(sm3));
-
- // 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");
- final StateManagement sm4 = new StateManagement(emf, "test_resource4");
- sm4.unlock();
- sm4.enableNotFailed();
- assertEquals(UNLOCKED_ENABLED_NULL_NULL, makeString(sm4));
- sm4.demote();
- assertEquals(UNLOCKED_ENABLED_NULL_HOTSTANDBY, makeString(sm4));
-
- // P1 If promote() is called while standbyStatus is hotstandby, the
- // state shall transition to providingservice.
- logger.info("\n??? promote() test case P1");
- sm4.promote();
- assertEquals(UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE, makeString(sm4));
-
- // State change notification
- logger.info("\n??? State change notification test case 1 - lock()");
- final StateChangeNotifier stateChangeNotifier = new StateChangeNotifier();
- sm.addObserver(stateChangeNotifier);
- sm.lock();
- assertEquals(LOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(stateChangeNotifier.getStateManagement()));
-
- logger.info("\n??? State change notification test case 2 - unlock()");
- sm.unlock();
- assertEquals(UNLOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(stateChangeNotifier.getStateManagement()));
-
- logger.info("\n??? State change notification test case 3 - enabled()");
- sm.enableNotFailed();
- assertEquals(UNLOCKED_ENABLED_NULL_HOTSTANDBY, makeString(stateChangeNotifier.getStateManagement()));
-
- logger.info("\n??? State change notification test case 4 - disableFailed()");
- sm.disableFailed();
- assertEquals(UNLOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(stateChangeNotifier.getStateManagement()));
-
- logger.info("\n??? State change notification test case 5 - demote()");
- sm.demote();
- assertEquals(UNLOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(stateChangeNotifier.getStateManagement()));
-
- logger.info("\n??? State change notification test case 6 - promote()");
- assertThatThrownBy(sm::promote).isInstanceOf(IntegrityMonitorException.class);
- assertEquals(UNLOCKED_DISABLED_FAILED_COLDSTANDBY, makeString(sm));
- }
-
- @Test
- @SuppressWarnings("unchecked")
- void test_StateManagementInitialization_ThrowException_ifEntityManagerCreateQuerythrowsAnyException() {
- assertThatThrownBy(() -> {
- final EntityManager mockedEm = getMockedEntityManager();
- final EntityManagerFactory mockedEmf = getMockedEntityManagerFactory(mockedEm);
-
- doThrow(PersistenceException.class).when(mockedEm).createQuery(anyString(),
- any(StateManagementEntity.class.getClass()));
-
- new StateManagement(mockedEmf, TEST_RESOURCE_NAME);
- }).isInstanceOf(StateManagementException.class);
- }
-
- @Test
- @SuppressWarnings("unchecked")
- void test_StateManagementInitialization_ThrowStateManagementException_ifEntityManagerThrowsAnyException() {
- assertThatThrownBy(() -> {
- final EntityManager mockedEm = getMockedEntityManager();
- final EntityManagerFactory mockedEmf = getMockedEntityManagerFactory(mockedEm);
- final TypedQuery<StateManagementEntity> mockedQuery = mock(TypedQuery.class);
-
- when(mockedQuery.setFlushMode(Mockito.any())).thenReturn(mockedQuery);
- when(mockedQuery.setLockMode(Mockito.any())).thenReturn(mockedQuery);
- when(mockedEm.createQuery(anyString(), any(StateManagementEntity.class.getClass())))
- .thenReturn(mockedQuery);
-
- doThrow(QueryTimeoutException.class).when(mockedQuery).getResultList();
-
- new StateManagement(mockedEmf, TEST_RESOURCE_NAME);
- }).isInstanceOf(StateManagementException.class);
- }
-
- private EntityManager getMockedEntityManager() {
- final EntityManager mockedEm = mock(EntityManager.class);
- final EntityTransaction mockedTransaction = mock(EntityTransaction.class);
-
- when(mockedEm.getTransaction()).thenReturn(mockedTransaction);
- return mockedEm;
- }
-
- private EntityManagerFactory getMockedEntityManagerFactory(final EntityManager entityManager) {
- final EntityManagerFactory mockedEmf = mock(EntityManagerFactory.class);
- when(mockedEmf.createEntityManager()).thenReturn(entityManager);
-
- return mockedEmf;
-
- }
-
- /**
- * Converts a state element to a comma-separated string.
- *
- * @param sm element to be converted
- * @return a string representing the element
- */
- private String makeString(final StateManagement sm) {
- if (sm == null) {
- return null;
- }
-
- return sm.getAdminState()
- + ',' + sm.getOpState()
- + ',' + sm.getAvailStatus()
- + ',' + sm.getStandbyStatus();
- }
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateTransitionTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/StateTransitionTest.java
deleted file mode 100644
index 8523c9e4..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/StateTransitionTest.java
+++ /dev/null
@@ -1,3566 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/*
- * All JUnits are designed to run in the local development environment
- * where they have write privileges and can execute time-sensitive
- * tasks.
- */
-class StateTransitionTest {
- private static final String HOTSTANDBY = "hotstandby";
- private static final String LOCKED = "locked";
- private static final String PROMOTE = "promote";
- private static final String PROVIDINGSERVICE = "providingservice";
- private static final String UNLOCK = "unlock";
- private static final String UNLOCKED = "unlocked";
- private static final String COLDSTANDBY = "coldstandby";
- private static final String DEMOTE = "demote";
- private static final String DEPENDENCY = "dependency";
- private static final String DEPENDENCY_FAILED = "dependency,failed";
- private static final String DISABLE_DEPENDENCY = "disableDependency";
- private static final String DISABLE_FAILED = "disableFailed";
- private static final String DISABLED = "disabled";
- private static final String ENABLE_NO_DEPENDENCY = "enableNoDependency";
- private static final String ENABLE_NOT_FAILED = "enableNotFailed";
- private static final String ENABLED = "enabled";
- private static final String FAILED = "failed";
-
- @Test
- void testBad() throws StateTransitionException {
- // bad test case
- assertEquals("coldstandby,locked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, "lock"));
-
- }
-
- @Test
- void test1() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", "lock"));
-
- }
-
- @Test
- void test2() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", UNLOCK));
-
- }
-
- @Test
- void test3() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, ENABLED, "null", "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test4() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test5() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, "null", "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test6() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test7() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", PROMOTE));
-
- }
-
- @Test
- void test8() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", "null", DEMOTE));
-
- }
-
- @Test
- void test9() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test10() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test11() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test12() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test13() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test14() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test15() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test16() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test17() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test18() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test19() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test20() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test21() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test22() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test23() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test24() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test25() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test26() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test27() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test28() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test29() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test30() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test31() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test32() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test33() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test34() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test35() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, ENABLED, FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test36() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test37() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test38() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test39() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test40() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test41() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test42() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test43() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test44() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test45() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test46() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test47() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test48() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test49() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test50() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test51() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test52() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test53() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test54() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test55() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test56() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test57() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test58() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test59() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test60() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test61() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test62() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test63() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test64() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test65() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test66() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", UNLOCK));
-
- }
-
- @Test
- void test67() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test68() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test69() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test70() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test71() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", PROMOTE));
-
- }
-
- @Test
- void test72() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test73() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test74() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test75() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test76() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test77() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test78() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test79() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test80() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test81() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test82() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test83() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test84() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test85() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test86() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test87() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test88() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test89() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test90() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test91() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test92() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test93() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test94() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test95() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test96() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test97() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test98() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test99() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test100() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test101() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test102() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test103() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test104() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test105() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test106() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test107() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test108() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test109() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test110() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test111() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test112() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test113() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test114() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test115() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test116() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test117() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test118() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test119() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test120() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test121() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test122() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test123() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test124() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test125() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test126() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test127() throws StateTransitionException {
- assertEquals("providingservice,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test128() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test129() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", DEMOTE));
-
- }
-
- @Test
- void test130() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", UNLOCK));
-
- }
-
- @Test
- void test131() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, "null", "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test132() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test133() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, "null", "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test134() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, "null", "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test135() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, "null", "null", PROMOTE));
-
- }
-
- @Test
- void test136() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", "null", DEMOTE));
-
- }
-
- @Test
- void test137() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test138() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test139() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test140() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test141() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test142() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test143() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test144() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,",
- makeString(UNLOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test145() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test146() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test147() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test148() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test149() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test150() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test151() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test152() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(UNLOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test153() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test154() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test155() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test156() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test157() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test158() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test159() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test160() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,",
- makeString(UNLOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test161() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test162() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test163() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test164() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(UNLOCKED, DISABLED, FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test165() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test166() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test167() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test168() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(UNLOCKED, DISABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test169() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test170() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test171() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test172() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test173() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test174() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test175() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test176() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test177() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test178() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test179() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test180() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test181() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test182() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test183() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test184() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test185() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test186() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test187() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test188() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test189() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test190() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test191() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test192() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test193() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test194() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,", makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", UNLOCK));
-
- }
-
- @Test
- void test195() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test196() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test197() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test198() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test199() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", PROMOTE));
-
- }
-
- @Test
- void test200() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test201() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test202() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test203() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test204() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test205() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test206() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test207() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test208() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test209() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test210() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test211() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test212() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test213() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test214() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test215() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test216() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test217() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test218() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test219() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test220() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test221() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test222() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test223() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test224() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test225() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test226() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test227() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test228() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test229() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test230() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test231() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test232() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test233() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test234() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test235() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test236() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test237() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test238() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test239() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test240() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test241() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test242() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test243() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test244() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test245() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test246() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test247() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test248() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test249() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test250() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test251() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test252() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test253() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test254() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test255() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,StandbyStatusException",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test256() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(UNLOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test257() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", DEMOTE));
-
- }
-
- @Test
- void test258() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", UNLOCK));
-
- }
-
- @Test
- void test259() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,", makeString(LOCKED, ENABLED, "null", "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test260() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test261() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, "null", "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test262() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test263() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, "null", "null", PROMOTE));
-
- }
-
- @Test
- void test264() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", "null", DEMOTE));
-
- }
-
- @Test
- void test265() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test266() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, "null", COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test267() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test268() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test269() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test270() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test271() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, "null", COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test272() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test273() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test274() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, "null", HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test275() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test276() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test277() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test278() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test279() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, "null", HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test280() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test281() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test282() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test283() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test284() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test285() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test286() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test287() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test288() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test289() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test290() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test291() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,", makeString(LOCKED, ENABLED, FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test292() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test293() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test294() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test295() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test296() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test297() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test298() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test299() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test300() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test301() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test302() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test303() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test304() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test305() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test306() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test307() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test308() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test309() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test310() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test311() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test312() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test313() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test314() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test315() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test316() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test317() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test318() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test319() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test320() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test321() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test322() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", UNLOCK));
-
- }
-
- @Test
- void test323() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test324() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test325() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test326() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test327() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY, "null", PROMOTE));
-
- }
-
- @Test
- void test328() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test329() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test330() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test331() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test332() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test333() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test334() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test335() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test336() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test337() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test338() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test339() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test340() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test341() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test342() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test343() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test344() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test345() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test346() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test347() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test348() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test349() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test350() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test351() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test352() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test353() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test354() throws StateTransitionException {
- assertEquals("null,unlocked,enabled,null,", makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test355() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test356() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test357() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test358() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test359() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test360() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test361() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test362() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test363() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test364() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test365() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test366() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test367() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test368() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test369() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test370() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test371() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test372() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test373() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test374() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test375() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test376() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test377() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test378() throws StateTransitionException {
- assertEquals("hotstandby,unlocked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test379() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test380() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test381() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test382() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test383() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,StandbyStatusException",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test384() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, ENABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test385() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", "null", DEMOTE));
-
- }
-
- @Test
- void test386() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,null,", makeString(LOCKED, DISABLED, "null", "null", UNLOCK));
-
- }
-
- @Test
- void test387() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,", makeString(LOCKED, DISABLED, "null", "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test388() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, DISABLED, "null", "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test389() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, "null", "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test390() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, DISABLED, "null", "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test391() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
- makeString(LOCKED, DISABLED, "null", "null", PROMOTE));
-
- }
-
- @Test
- void test392() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", "null", DEMOTE));
-
- }
-
- @Test
- void test393() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test394() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(LOCKED, DISABLED, "null", COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test395() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test396() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test397() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test398() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, "null", COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test399() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
- makeString(LOCKED, DISABLED, "null", COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test400() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test401() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test402() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,", makeString(LOCKED, DISABLED, "null", HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test403() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test404() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test405() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test406() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, "null", HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test407() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
- makeString(LOCKED, DISABLED, "null", HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test408() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,", makeString(LOCKED, DISABLED, "null", HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test409() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test410() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,null,",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test411() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test412() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test413() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test414() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test415() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,StandbyStatusException",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test416() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,null,",
- makeString(LOCKED, DISABLED, "null", PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test417() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test418() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test419() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test420() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,", makeString(LOCKED, DISABLED, FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test421() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test422() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test423() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test424() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test425() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test426() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test427() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test428() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test429() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test430() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test431() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test432() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test433() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test434() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test435() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test436() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test437() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test438() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test439() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test440() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,", makeString(LOCKED, DISABLED, FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test441() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test442() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test443() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test444() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test445() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test446() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test447() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test448() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test449() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test450() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,", makeString(LOCKED, DISABLED, DEPENDENCY, "null", UNLOCK));
-
- }
-
- @Test
- void test451() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test452() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test453() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test454() throws StateTransitionException {
- assertEquals("null,locked,enabled,null,",
- makeString(LOCKED, DISABLED, DEPENDENCY, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test455() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY, "null", PROMOTE));
-
- }
-
- @Test
- void test456() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, "null", DEMOTE));
-
- }
-
- @Test
- void test457() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test458() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test459() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test460() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test461() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test462() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test463() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test464() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test465() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test466() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test467() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test468() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test469() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test470() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test471() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test472() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test473() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test474() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test475() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test476() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test477() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test478() throws StateTransitionException {
- assertEquals("coldstandby,locked,enabled,null,",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test479() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test480() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test481() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test482() throws StateTransitionException {
- assertEquals("null,unlocked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", UNLOCK));
-
- }
-
- @Test
- void test483() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_FAILED));
-
- }
-
- @Test
- void test484() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test485() throws StateTransitionException {
- assertEquals("null,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test486() throws StateTransitionException {
- assertEquals("null,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test487() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", PROMOTE));
-
- }
-
- @Test
- void test488() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, "null", DEMOTE));
-
- }
-
- @Test
- void test489() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test490() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test491() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test492() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test493() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test494() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test495() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test496() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, COLDSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test497() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test498() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, UNLOCK));
-
- }
-
- @Test
- void test499() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_FAILED));
-
- }
-
- @Test
- void test500() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test501() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test502() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test503() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, PROMOTE));
-
- }
-
- @Test
- void test504() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, HOTSTANDBY, DEMOTE));
-
- }
-
- @Test
- void test505() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
-
- }
-
- @Test
- void test506() throws StateTransitionException {
- assertEquals("coldstandby,unlocked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, UNLOCK));
-
- }
-
- @Test
- void test507() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_FAILED));
-
- }
-
- @Test
- void test508() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NOT_FAILED));
-
- }
-
- @Test
- void test509() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DISABLE_DEPENDENCY));
-
- }
-
- @Test
- void test510() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, ENABLE_NO_DEPENDENCY));
-
- }
-
- @Test
- void test511() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,StandbyStatusException",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, PROMOTE));
-
- }
-
- @Test
- void test512() throws StateTransitionException {
- assertEquals("coldstandby,locked,disabled,dependency,failed,",
- makeString(LOCKED, DISABLED, DEPENDENCY_FAILED, PROVIDINGSERVICE, DEMOTE));
- }
-
- /**
- * Converts a transition to a string.
- */
- private String makeString(String adminState, String opState, String availStatus, String standbyStatus,
- String actionName) throws StateTransitionException {
- StateTransition st = new StateTransition();
- StateElement se = st.getEndingState(adminState, opState, availStatus, standbyStatus, actionName);
- if (se == null) {
- return null;
- }
-
- StringBuilder stringBuilder = new StringBuilder();
-
- String endingStandbyStatus = se.getEndingStandbyStatus();
- if (endingStandbyStatus != null) {
- stringBuilder.append(endingStandbyStatus.replace(".", ","));
- stringBuilder.append(',');
- }
-
- stringBuilder.append(se.getEndingAdminState());
- stringBuilder.append(',');
- stringBuilder.append(se.getEndingOpState());
- stringBuilder.append(',');
- stringBuilder.append(se.getEndingAvailStatus());
- stringBuilder.append(',');
- stringBuilder.append(se.getException());
-
- return stringBuilder.toString();
- }
-}
diff --git a/integrity-monitor/src/test/java/org/onap/policy/common/im/exceptions/EntityRetrievalExceptionTest.java b/integrity-monitor/src/test/java/org/onap/policy/common/im/exceptions/EntityRetrievalExceptionTest.java
deleted file mode 100644
index abf7d27c..00000000
--- a/integrity-monitor/src/test/java/org/onap/policy/common/im/exceptions/EntityRetrievalExceptionTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2024 Nordix Foundation
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.im.exceptions;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.utils.test.ExceptionsTester;
-
-class EntityRetrievalExceptionTest extends ExceptionsTester {
-
- @Test
- void testEntityRetrievalException() {
- assertEquals(1, test(EntityRetrievalException.class));
- }
-
-}
diff --git a/integrity-monitor/src/test/resources/logback-test.xml b/integrity-monitor/src/test/resources/logback-test.xml
deleted file mode 100644
index 70a71950..00000000
--- a/integrity-monitor/src/test/resources/logback-test.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- integrity-monitor
- ================================================================================
- Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ============LICENSE_END=========================================================
- -->
-
-<!-- Controls the output of logs for JUnit tests -->
-
-<configuration>
-
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
- <Pattern>
- %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
- </Pattern>
- </encoder>
- </appender>
- <appender name="FILE" class="ch.qos.logback.core.FileAppender">
- <file>logs/debug.log</file>
- <encoder>
- <Pattern>
- %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
- </Pattern>
- </encoder>
- </appender>
-
- <root level="debug">
- <appender-ref ref="STDOUT" />
- <appender-ref ref="FILE" />
- </root>
-
-</configuration>
diff --git a/pom.xml b/pom.xml
index ae6d1b03..e841eb43 100644
--- a/pom.xml
+++ b/pom.xml
@@ -52,10 +52,7 @@
<module>utils-test</module>
<module>utils</module>
<module>gson</module>
- <module>common-logging</module>
<module>common-parameters</module>
- <module>integrity-audit</module>
- <module>integrity-monitor</module>
<module>policy-endpoints</module>
<module>spring-utils</module>
</modules>
diff --git a/utils-test/pom.xml b/utils-test/pom.xml
index d5341812..6338cc08 100644
--- a/utils-test/pom.xml
+++ b/utils-test/pom.xml
@@ -42,7 +42,6 @@
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-fips</artifactId>
- <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
diff --git a/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java b/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java
index 1cc16263..9fa1067d 100644
--- a/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java
+++ b/utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java
@@ -75,7 +75,6 @@ public class SelfSignedKeyStore {
* Generates the keystore, if it does not exist or if it's more than a few hours old.
*
* @throws IOException if an I/O error occurs
- * @throws InterruptedException if an interrupt occurs
*/
public SelfSignedKeyStore() throws IOException {
this(RELATIVE_PATH);
@@ -87,7 +86,6 @@ public class SelfSignedKeyStore {
* @param relativePath path to the keystore, relative to the "user.dir" system
* property
* @throws IOException if an I/O error occurs
- * @throws InterruptedException if an interrupt occurs
*/
public SelfSignedKeyStore(String relativePath) throws IOException {
keystoreName = System.getProperty("user.dir") + "/" + relativePath;